![](/img/trans.png)
[英]Spring Boot @MockBeans - How to use the same beans in multiple test classes
[英]@MockBeans example use
我有一个使用多个服务的控制器类。 我为该控制器编写了一个测试,例如:
@RunWith(SpringRunner.class)
@WebMvcTest(value = PurchaseController.class, secure = false)
public class PurchaseControllerTest {
@MockBean
private ShoppingService shoppingService;
@MockBean
private ShopRepository shopRepository;
@MockBean
private SomeOtherRepository someOtherRepository;
@Autowired
private MockMvc mockMvc;
// ... some tests goes here
问题是,往往会有许多这样的模拟,因此会有很多代码行。 我知道这可能是代码异味的迹象,但这不是我现在的意思。
我注意到,还有一个@MockBeans
批注具有@Target(ElementType.TYPE)
。 所以我想我可以尝试:
@RunWith(SpringRunner.class)
@WebMvcTest(value = PurchaseController.class, secure = false)
@MockBeans(value = {ShoppingService.class, ShopRepository.class})
public class PurchaseControllerTest {
但是它不会进行事件编译。
我的问题是:我们如何使用@MockBeans
注释? 它适用于我的情况吗?
@MockBeans
只是@MockBean
乘以的可重复注释。 如果您需要重用这个模拟的bean,则可以放入一个class / config类。 但是您需要使用@Autowired
提供模拟服务。 因此,在您的情况下应该是:
.....
@MockBeans({@MockBean(ShoppingService.class), MockBean(ShopRepository.class)})
public class PurchaseControllerTest {
@Autowired
ShoppingService shoppingService;
@Autowired
ShopRepository shopRepository;
.....
}
@MockBeans
的主要思想是在一个地方重复@MockBean
。 对我而言,它仅对某些可重用的配置/通用类有用。
@MockBean
创建一个模拟,@ @Autowired
是从上下文自动装配的bean,在您的情况下,将标记/创建bean标记为模拟,然后@Autowired
模拟的bean注入到您的autowired字段中。
所以,如果你有很多领域自动装配与@MockBeans
(或乘@MockBean
)可以配置它是在一个地方或模拟不(在@MockBeans
类级别),你不需要改变@Autowired
到@Mock
在您的测试类中(例如,如果您删除@MockBeans
所有未@MockBeans
自动装配的bean都将自动关联为上下文中的bean,如果您撤消删除,则将在模拟的bean中工作(在此注释中配置))。
如果要避免在一个类中出现很多依赖关系,可以将所有依赖关系提取到某个父类中,但是由于Java不支持该类的多重继承,因此不一定总是有帮助。
Javadoc说它被用作
容器注释聚合了几个{@link MockBean}注释。
所以你可以写
@MockBeans({@MockBean(ShoppingService.class), @MockBean(ShopRepository.class)})
public class PurchaseControllerTest {
@Autowire ShoppingService
在这里工作
要么
也可以与Java 8对可重复注释的支持结合使用
@MockBean(ShoppingService.class)
@MockBean(ShopRepository.class)
public class PurchaseControllerTest {
Java 8启用了可重复注释 ,并且出于兼容性原因,重复注释存储在容器注释@MockBeans
,该容器注释由Java编译器自动生成。 为了使编译器执行此操作,您需要做两件事:
@Repeatable(MockBeans.class)
注释类型@MockBean
@MockBeans
您所用的最短变体是@MockBean
,它支持所需的@MockBean
类的多个值
@MockBean({ShoppingService.class, ShopRepository.class})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.