[英]Spring Boot controller test loading entire application context
Spring 在此處啟動。 我目前有以下REST controller:
@RestController
public class FizzbuzzController {
private final FizzbuzzService FizzbuzzService;
public FizzbuzzController(FizzbuzzService FizzbuzzService) {
this.FizzbuzzService = FizzbuzzService;
}
@PostMapping("/Fizzbuzzs/{fizzbuzzId}")
public ResponseEntity<FizzbuzzDTO> addFizzbuzz(@RequestParam("files") List<MultipartFile> files,
@PathVariable String fizzbuzzId) throws IOException {
FizzbuzzDTO fizzbuzzDTO = fizzbuzzService.store(files, fizzbuzzId);
return ResponseEntity.status(HttpStatus.OK).body(fizzbuzzDTO);
}
}
我想為它編寫一個集成測試:
FizzbuzzService
或真實的東西注入FizzbuzzController
(正在測試); 和迄今為止我最好的嘗試:
@WebMvcTest(FizzbuzzController.class)
@EnableConfigurationProperties
@AutoConfigureMockMvc
public class FizzbuzzControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private FizzbuzzService FizzbuzzService;
@Test
public void should_store_fizzbuzz_files() throws Exception {
// I can't even get the test to run
assertTrue(1 == 1);
}
}
當我運行它時,測試無法運行並且很明顯(查看日志)Spring 正在加載我的應用程序的整個應用程序上下文,而我只是希望它隔離這個測試 class 的上下文,主FizzbuzzController
ZA2F2ED4F8EBC2ABCB4ZDC2 ,以及它下面的依賴樹中的任何內容。
誰能發現我哪里出錯了?
您需要另一個上下文進行測試。 我建議你有一個單獨的測試配置:
@TestConfiguration
@Slf4j
@EnableJpaRepositories("tth.patientportal.repository")
public class TestConfig { // bean configs goes here for testing if you need to change
// context}
並在 controller 測試中構建如下上下文:
@RunWith(SpringRunner.class)
@AutoConfigureTestEntityManager
@SpringBootTest
@TestPropertySource("classpath:application-unittest.properties")
@ContextConfiguration(classes = {TestConfig.class})
public class RestControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup()
{
mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void shouldReturnRegisteredUser() throws Exception {
this.mockMvc.
perform(MockMvcRequestBuilders
.post("url")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").exists());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.