使用Spring Boot在spring上下文中模拟bean

时间:2016-01-27 21:33:03

标签: spring unit-testing spring-boot

我使用的是Spring Boot 1.3.2,我发现问题,我的测试类中的ComponentScan无法正常工作。我想嘲笑一些Spring Beans。弹簧启动是否会阻止ComponentScan?

测试配置类:

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

    @Bean
    @Primary
    public OfferRepository offerRepository() {
        return mock(OfferRepository.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);
    }
}

1 个答案:

答案 0 :(得分:0)

解决此问题

测试配置类,排除SpringBootApplicationConfigutation并添加@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);
    }

}

并测试:

    @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);
        }
    }