簡體   English   中英

如何使用 Mockito 通過注釋注入模擬集合

[英]How to inject mock collection by annotation with Mockito

我創建了一個帶有兩個參數的參數化類。 一種是字符串類型,另一種是抽象類的列表類型。 類構造函數看起來像下面的代碼。

public TestService(Tenant tenant, List<AbstractService> testServices) {
        testServicesMap = testServices.stream().collect(Collectors.toMap(AbstractService::getType, Function.identity()));
}

現在我想為這個類編寫 Junit 測試用例,為此我有以下代碼。

    @Mock
    protected Tenant tenant;

    @Mock
    private List<AbstractService> testServices;

    @InjectMocks
    private TestService testService;

    @Before
    public void setup() {
        testServices.add(new JobService(new JobEventService()));
        testServices.add(new ApplicationService(new ApplicationEventService()));
        testServices.add(new UserService(new UserEventService()));
//      notificationService = new NotificationService(tenant, notificationServices);
//      MockitoAnnotations.initMocks(notificationService);
    }

我還嘗試啟用兩條注釋行,但現在可以使用了。 以下是系統在啟動時拋出的錯誤。

org.mockito.exceptions.base.MockitoException: 
Cannot instantiate @InjectMocks field named 'notificationService' of type 'class com.test.TestService'.
You haven't provided the instance at field declaration so I tried to construct the instance.   
However the constructor or the initialization block threw an exception : `null`.    

有人可以幫忙嗎?

您將模擬與真實對象混合在一起,因為您創建了一個列表模擬,然后在該列表上調用add方法,然后您希望stream()像往常一樣工作。

Mockito mocks 默認不做任何事情,所以你必須告訴它:

Mockito.when(testServices.stream())
       .thenReturn(Stream.of(new JobService(new JobEventService())));

或者在您的情況下更好的是從testServices刪除@Mock並為其分配一個新的ArrayList

問題是您嘗試模擬列表,並且調用了 list.stream(),它在模擬中默認返回 null。

重復問題的常見解決方案是使用列表的@Spy。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM