A simple way of getting additional beans in the context is via using nested configuration classes within test classes
@TestConfiguration
static class AdditionalConfig {
@Bean
public SomeBean getSomeBean() {
return new SomeBean());
}
}
Example:
Scenario - If you have some Controller say ProductController and you have the corresponding slice-test for the class say ProductionControllerTest
@RestController
public class ProductController {
@Autowired
private IProductService productService;
@Autowired
private IProductValidator productValidator;
@GetMapping("product")
public Product getProduct(@RequestParam Long id) {
Product product = productService.getProduct(id); // you are using mockBean of productService
productValidator.validateProduct(product); // you need real bean of productValidator
return product;
}
}
Corresponding slide test class with an additional bean configuration
@RunWith(SpringRunner.class)
@WebMvcTest
public class ProductControllerSliceTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private IProductService productService;
@Autowired
private ApplicationContext applicationContext;
@TestConfiguration
static class AdditionalConfig {
@Bean
public IProductValidator productValidator() {
return new ProductValidator();
}
}
@Test
public void testProductGetById() throws Exception {
Product testProductWithID1L = new Product(1L, "testProduct");
when(productService.getProduct(anyLong())).thenReturn(testProductWithID1L);
mockMvc.perform(get("/product")
.param("id", "1")).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("name")
.value("testProduct"))
.andExpect(MockMvcResultMatchers.jsonPath("id")
.value("1"));
}
}
Additional thoughts on your scenario: If you really intend to do the unit testing of the controller class then ideally you should mock all the additional dependencies of class that you are testing.
Ideally, the intention of the unit test is to only test the behavior of the object/class under test. All the dependent classes behavior or external calls should be mocked.
When you start testing several classes together under one test, you are moving more towards a component test or integration test