【问题标题】:Mocking beans in spring context using Spring Boot使用 Spring Boot 在 Spring 上下文中模拟 bean
【发布时间】:2016-01-27 21:33:02
【问题描述】:

我正在使用 Spring Boot 1.3.2,我注意到问题,我的测试类中的 ComponentScan 不起作用。我想模拟一些 Spring Beans。 Spring Boot 会阻塞 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);
    }
}

【问题讨论】:

    标签: spring unit-testing spring-boot


    【解决方案1】:

    这个问题的解决方法

    测试配置类,重要的是排除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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2017-07-30
      • 2016-10-06
      • 1970-01-01
      • 2011-05-15
      相关资源
      最近更新 更多