测试时我期望的状态是200,但我现在得到的是404。
我对Mockido来说相当新,所以如果有一些我想念的简单。请告诉我。
我在控制器中创建了一个POST请求,它接受一个Long对象列表。如果没有异常发生,则返回OK状态:
@PostMapping(path = "/postlist")
public ResponseEntity<Void> updateAllInList(@RequestBody List<Long> ids) {
try {
// method from ControllerService.java here using ids
return ResponseEntity.status(HttpStatus.OK).body(null);
} catch (InvalidContentException e) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(null);
}
当我使用REST客户端POST时,我得到了正确的结果。我POST的原始有效载荷是这样的:
[
2, 1
]
然而,单元测试给了我一个404。
我创建Test类的方式是这样的:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({ @ContextConfiguration(classes = RootConfiguration.class), @ContextConfiguration(classes = WebConfiguration.class) })
@Category(UnitTest.class)
public class ControllerTest {
private static final String POST_REQUEST = "[ 2, 1 ]";
@Autowired private WebApplicationContext webApplicationContext;
@Autowired private ControllerService controllerService;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
doNothing().when(this.controllerService).updateAllInList(anyList());
doThrow(InvalidContentException.class).when(this.controllerService).updateAllInList(null);
}
@Test
public void updateList() throws Exception {
this.mockMvc.perform(post("http://testhost/api/configuration/postlist").contentType(MediaType.APPLICATION_JSON_UTF8).content(POST_REQUEST))
.andExpect(status().isOk());
}
@Configuration
static class RootConfiguration {
@Bean
public ControllerService ControllerService() {
return Mockito.mock(ControllerService.class);
}
}
@Configuration
@EnableWebMvc
static class WebConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private ControllerService controllerService;
@Bean
public Controller controller() {
return new Controller(controllerService);
}
}
}
我的理论是,在我的测试课中,我插入了错误的内容。但是为什么我们不能插入与真实POST原始有效载荷中使用的内容相同的内容?
感谢。
答案 0 :(得分:0)
使用MockMvc
时,您希望触发控制器的映射,而不是HTTP服务器。
而不是mockMvc.perform(post("http://testhost/api/configuration/postlist")...
尝试mockMvc.perform(post("/configuration/postlist")...