我正在尝试测试作为 mvc 控制器一部分的 rest 调用。我的单元测试当前返回 404 错误代码,而不是 200 状态代码,这将确定请求已成功发送。
这是我尝试测试的方法的签名:
@PreAuthorize("hasRole('ROLE_SSL_USER')")
@PostMapping(value = "/employee", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> postEmployee(HttpEntity<String> httpEntity, @RequestHeader("DB-Client-Id") String clientId,
@RequestHeader("X-Forwarded-Client-Dn") String dn) throws IOException, ValidationException {}
这是我的单元测试类:
public class ControllerTest {
@InjectMocks
private Controller aController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(aController).build();
}
@Test
public void PostEmpTest() {
try {
this.mockMvc.perform(post("/employee")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我是否从 perform(( 调用中缺少导致 404 错误请求代码的内容?
我用于控制器测试的代码如下
@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
@AutoConfigureWebClient
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void entityTypes() throws Exception {
String json = "...";
mockMvc.perform(
post("URL")
.contentType(APPLICATION_JSON_UTF8)
.content(json))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
;
}
}
试试吧 - 我希望它会有所帮助。
PS:另外,我不确定,但看起来您需要在控制器方法声明中添加@RequestBody:
public ResponseEntity<Object> postEmployee(
@RequestBody HttpEntity<String> httpEntity,
@RequestHeader("DB-Client-Id") String clientId,
@RequestHeader("X-Forwarded-Client-Dn") String dn) throws IOException, ValidationException {}