この Q&Aは既に読みましたが、問題は解決しませんでした。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
まったく同じコントローラーで使用すると、期待どおりに機能することに注意してください。