1

I have a unit test that is testing a RestController using @WebMvcTest. The the controller class autowires a service class that I would like to mock. I found that I can use @Profile and @Configuration to create a config class for specifying primary beans to use when a profile is active. I tried adding an active profile to my unit test class, but it says it failed to load the ApplicationContext. I'm not sure how I can do that while using @WebMvcTest.

@ActiveProfiles("mockServices")
@RunWith(SpringRunner.class)
@WebMvcTest(VoteController.class)
public class VoteControllerTest {
...

It seems I may be approaching this wrong. Any help is appreciated.

Edit:

Here is my configuration class:

@Profile("mockService")
@Configuration
public class NotificationServiceTestConfiguration {

    @Bean
    @Primary
    public VotingService getVotingService() {
        return Mockito.mock(VotingService.class);
    }
}

The error I'm actually getting is:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'VotingService'

I was able to solve it by using @MockBean for VotingService in my Unit Test class. However, I want to use the Profile configuration I have in NotificationServiceTestConfiguration without having to call out mock beans.

Any thoughts?

srowley
  • 837
  • 1
  • 12
  • 24

0 Answers0