Spring Boot version 1.5.4.RELEASE.
Running the application normal works fine.
When running a Unit test, some beans are missing, for example:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in ...service.post.PostService required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
I'm using a MongoDB repository. I solved this by adding a config class which returns this bean.
After this I tried to execute the Unit test again, the following error came up:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in springfox.documentation.spring.data.rest.BasePathAwareServicesProvider required a bean of type 'org.springframework.data.rest.core.config.RepositoryRestConfiguration' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.data.rest.core.config.RepositoryRestConfiguration' in your configuration.
This is raised by the springfox swagger ui Rest documentation. When removing this application dependency, the test completes successfully.
What did I miss here? Some beans cannot be found or auto configured in the Unit test 'environment'.
Update
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTests {
@Test
public void contextLoads() {}
}
@RunWith(SpringRunner.class)
@WebMvcTest(value = ProfileController.class, secure = false)
public class ProfileControllerTest {
private MockMvc mockMvc;
@MockBean private ProfileService profileService;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ProfileController(profileService)).build();
}
@Test
....
}
This is the only test controller I currently have.
Modifying your code to show how to exclude a configuration that is usually required when running Unit tests:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTests {
@Test
public void contextLoads() {}
}
@RunWith(SpringRunner.class)
@WebMvcTest(value = ProfileController.class, secure = false, excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) // or any other configuration.
public class ProfileControllerTest {
private MockMvc mockMvc;
@MockBean private ProfileService profileService;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ProfileController(profileService)).build();
}
@Test
....
}
You can find a complete Spring Boot application that include Integration and Unit tests here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With