使用 Spring Boot 在 spring 上下文中模拟 bean [英] Mocking beans in spring context using Spring Boot
本文介绍了使用 Spring Boot 在 spring 上下文中模拟 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 Spring Boot 1.3.2,但我注意到问题,我的测试类中的 ComponentScan 不起作用.我想模拟一些 Spring Bean.spring boot 会阻塞 ComponentScan 吗?
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?
测试配置类:
@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);
}
}
推荐答案
此问题的解决方案
测试配置类,重要的是排除SpringBootApplicationConfigutation并添加@ComponentScan:
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);
}
}
并测试:
@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);
}
}
这篇关于使用 Spring Boot 在 spring 上下文中模拟 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文