我已经阅读了这个问答,但它并没有解决问题。我正在使用 Spring Boot 1.4.2.RELEASE 并且正在尝试加快测试速度。到目前为止,我已经使用@SpringBootTest
并且正在测试将其中一些更简单的测试切换到@WebMvcTest
.
我的控制器具有以下响应GET
请求的方法。
public ResponseEntity<MappingJacksonValue> fetchOne(@PathVariable Long id, @RequestParam(value = "view", defaultValue = "summary", required = false) String view) throws NotFoundException {
Brand brand = this.brandService.findById(id);
if (brand == null) {
throw new NotFoundException("Brand Not Found");
}
MappingJacksonValue mappingJacksonValue = jsonView(view, brand);
return new ResponseEntity<>(mappingJacksonValue, HttpStatus.OK);
}
我的测试如下所示:
@RunWith(SpringRunner.class)
@WebMvcTest(BrandController.class)
public class BrandSimpleControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BrandService brandService;
@Test
public void testExample() throws Exception {
Brand brand = new Brand(1l);
brand.setName("Test Name");
brand.setDateCreated(new Date());
brand.setLastUpdated(new Date());
when(this.brandService.findById(1l)).thenReturn(brand);
this.mockMvc.perform(get("/api/brands/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is("Test Name")));
}
}
当我运行这个测试时,我没有得到任何内容。我没有做任何与本指南有明显不同的事情,所以不确定我错过了什么。
我应该注意,使用@SpringBootTest
完全相同的控制器可以按预期工作。