Robert Strauch
Robert Strauch

Reputation: 12906

Spring Boot integration test fails with "No qualifying bean" for MockMvc

I'd like to create an integration test for my Spring Boot application checking that a controller returns the correct HTTP status when sending an email.

This is how my test looks like:

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@Profile("test")
public class EmailControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Rule
    public SmtpServerRule smtpServerRule = new SmtpServerRule(2525);

    private static final String RESOURCE_PATH = "/mail";

    @Test
    public void whenValidInput_thenReturns200() throws Exception {
        final EmailNotification emailNotification = EmailNotification.builder()
                .emailAddress("[email protected]")
                .subject("TEST_SUBJECT")
                .content("TEST_CONTENT")
                .build();
        mockMvc.perform(post(RESOURCE_PATH)
                .contentType(APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(emailNotification))
        ).andExpect(status().isOk());
    }
}

However it fails with the following excetpion:

No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I looked at the Spring Boot tutorials on integration testing but cannot see what's wrong.

This is the controller under test:

@RestController
public class EmailController {

    private static final Logger LOG = LoggerFactory.getLogger(EmailController.class.getName());

    private final EmailService emailService;

    @Autowired
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @PostMapping(value = "/mail", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void send(@Valid @RequestBody EmailNotification emailNotification) {
        try {
            emailService.sendEmail(emailNotification);
        } catch (MailException | MessagingException e) {
            LOG.error("Error sending email: (recipient address: {}): {}", emailNotification.getEmailAddress(), e.getMessage());
        }
    }
}

Upvotes: 0

Views: 769

Answers (1)

Giovanni Silva
Giovanni Silva

Reputation: 714

Remove the @Profile and add @ActiveProfiles("test") from your test class they are not the same. @Profile conditional evaluates the bean if the profile passed as argument is enabled, @ActiveProfiles change the profile to the profile passed as a argument, or in other words, activate it.

Upvotes: 2

Related Questions