Issue
Spring Boot here. I currently have the following 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);
}
}
I would like to write an integration test for it that:
- Mocks or stubs an HTTP request to the URL; and
- Allows me to inject the
FizzbuzzController
(under test) with a mockedFizzbuzzService
or the real thing; and - Allows me to inspect the HTTP response coming back from the method (check status code, check response entity, etc.)
My best attempt thus far:
@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);
}
}
When I run this, the test fails to run and it is clear (looking at the logs) that Spring is loading the entire application context of my app, whereas I just want it to isolate the context to this test class, the main FizzbuzzController
class, and anything in the dependency tree underneath it.
Can anyone spot where I'm going awry?
Solution
You need another context for testing. I'm suggesting you to have a separate Test config:
@TestConfiguration
@Slf4j
@EnableJpaRepositories("tth.patientportal.repository")
public class TestConfig { // bean configs goes here for testing if you need to change
// context}
and in a controller test build the context like below:
@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());
}
}
Answered By - Juliyanage Silva
Answer Checked By - Senaida (JavaFixing Volunteer)