[英]Mock Spring Controller for unit testing
I'm trying to test a rest call that is a part of an mvc controller. 我正在尝试测试作为mvc控制器一部分的rest调用。 My unit test is currently returning a 404 error code, instead of a 200 status code, which would determine that the request was sent successfully.
我的单元测试当前返回的是404错误代码,而不是200状态代码,这将确定请求已成功发送。
Here's the signature of my method that I'm trying to test: 这是我要测试的方法的签名:
@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 {}
Here's my unit test class: 这是我的单元测试课:
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();
}
}
}
Am I missing something from my perform() call that is resulting in the 404 bad request code? 我是否从我的perform()调用中丢失了导致404错误请求代码的内容?
I use for controller tests code like this 我用这样的控制器测试代码
@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))
;
}
}
Try it - I hope, it will help. 试试吧-希望会有所帮助。
PS: also, I'm not sure, but it looks like you need add @RequestBody to your controller method declaration: 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 {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.