@SpringBootTest does not autowire JavaMailSender and throws error

T D picture T D · Mar 5, 2017 · Viewed 7.3k times · Source

What am I doing wrong here? My understanding is Spring should autowire JavaMailSender the way its autowiring EventRepository. Any guidance?

application.properties and application-test.properties

mail.host='smtp.gmail.com' -
mail.port=587
mail.username=username
mail.password=password
mail.properties.mail.smtp.starttls.enable=true

My Implementation class : This works fine if I run my application

      @Service
            public class EventService {
             private EventRepository eventRepository;
             private JavaMailSender javaMailSender;

                public EventService(EventRepository eventRepository, JavaMailSender   javaMailSender) {
                    this.eventRepository = eventRepository;
                    this.javaMailSender = javaMailSender;
                }

                public Event send(Event event) {
                   SimpleMailMessage message = new SimpleMailMessage();
                    message.setText("");
                    message.setSubject("");
                    message.setTo("");
                    message.setFrom("");
                    javaMailSender.send(message);
                    return eventRepository.save(event);
                }

            }

My Integration Test class : Able to Autowired EventRepository but not JavaMailSender.

       @RunWith(SpringRunner.class)
        @SpringBootTest
        public class ApplicationIntegrationTests {
            @Autowired
            private EventService eventService;

         @Test
            public void test() throws Exception {
                eventService.save(new Event());
        }

        }

ERROR:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.mail.javamail.**JavaMailSender**' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)

Answer

Tom picture Tom · Mar 6, 2017

Please make sure that your test reside in the same package as your main @SpringBootApplication class.

for example if @SpringBootApplication class is in src/main/java/some/package then your @SpringBootTest need to be in src/test/java/some/package. If it is not, you need to explicitly set @ComponentScan to include some.package. You can also use @SpringBootTest(classes=...), @ContextConfiguration(classes=...)}.

You can also put a @SpringBootConfiguration class in your test package that scans for your main package.