简体   繁体   中英

Mocking beans in spring context using Spring Boot

I'm using Spring Boot 1.3.2, and I notice problem, ComponentScan in my test class is not working. And I want to mock some of Spring Beans. Is spring boot blocking ComponentScan?

Test config class:

@Configuration
@ComponentScan(value = {"myapp.offer", "myapp.image"})
public class TestEdge2EdgeConfiguration {

    @Bean
    @Primary
    public OfferRepository offerRepository() {
        return mock(OfferRepository.class);
    }

}

Test class:

@ContextConfiguration(classes=TestEdge2EdgeConfiguration.class, loader=AnnotationConfigContextLoader.class)
public class OfferActionsControllerTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private OfferRepository offerRepository;

    @Autowired
    private OfferActionsController offerActionsController;

    @BeforeMethod
    public void setUp(){

        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void saveOffer() {
        //given
        BDDMockito.given(offerRepository.save(any(Offer.class))).willReturn(new Offer());
        //when
        ResponseEntity<Offer> save = offerActionsController.save(new Offer());

        //then
        org.springframework.util.Assert.notNull(save);
    }
}

Solution of this problem

Test config class, it's important to exclude SpringBootApplicationConfigutation and add @ComponentScan:

@ComponentScan(basePackages = "com.example", excludeFilters =
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
            value = {SpringBootApplicationConfigutation.class, MyDao.class}
    )
)
@Configuration
public class TestEdge2EdgeConfiguration {

    @Bean
    public OfferRepository offerRepository() {
        return mock(OfferRepository.class);
    }

}

And test:

    @SpringApplicationConfiguration(classes=TestEdge2EdgeConfiguration.class)
    public class OfferActionsControllerTest extends AbstractTestNGSpringContextTests {

        @Autowired
        private OfferRepository offerRepository;

        @Autowired
        private OfferActionsController offerActionsController;

        @BeforeMethod
        public void resetMock() {
           Mockito.reset(offerRepository);
        }

        @Test
        public void saveOffer() {
            //given
            BDDMockito.given(offerRepository.save(any(Offer.class))).willReturn(new Offer());
            //when
            ResponseEntity<Offer> save = offerActionsController.save(new Offer());        
            //then
            org.springframework.util.Assert.notNull(save);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM