![](/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.