簡體   English   中英

為什么我們不能使用Mockito為Parameterized Constructor創建間諜

[英]why cannot we create spy for Parameterized Constructor using Mockito

我的代碼中只有參數化構造函數,我需要通過它注入。

我想間諜參數化構造函數注入模擬對象作為我的junit的依賴項。

public RegDao(){
 //original object instantiation here
Notification ....
EntryService .....
}

public RegDao(Notification notification , EntryService entry) {
 // initialize here
}

we have something like below : 
RegDao dao = Mockito.spy(RegDao.class);

但是我們有什么東西可以在構造函數中注入模擬對象並窺探它嗎?

您可以通過在junit中使用參數化構造函數實例化主類,然后從中創建一個間諜來實現。

我們假設你的主要班級是A 其中BC是它的依賴關系

public class A {

    private B b;

    private C c;

    public A(B b,C c)
    {
        this.b=b;
        this.c=c;
    }

    void method() {
        System.out.println("A's method called");
        b.method();
        c.method();
        System.out.println(method2());

    }

    protected int method2() {
        return 10;
    }
}

然后,您可以使用參數化類為此編寫junit,如下所示

@RunWith(MockitoJUnitRunner.class)
public class ATest {

    A a;

    @Mock
    B b;

    @Mock
    C c;

    @Test
    public void test() {
        a=new A(b, c);
        A spyA=Mockito.spy(a);

        doReturn(20).when(spyA).method2();

        spyA.method();
    }
}

測試類的輸出

A's method called
20
  1. 這里BC是使用參數化構造函數在類A注入的模擬對象。
  2. 然后我們創建了A名為spyAspy
  3. 我們通過修改A類中受保護方法method2的返回值來檢查spy是否真的有效,如果spyA不是A的實際spyA是不可能的。

聽起來你可能錯過了依賴注入解決方案。 Mockito非常適合與你的DI一起注射嘲笑。 例如,您可以使用CDI,使用@Inject注釋NotificationEntryService成員,在測試中為兩者聲明@Mock s,然后讓Mockito將這些注入您的RegDao進行測試。

這是我認為你試圖運行的測試的工作模型:

import static org.junit.Assert.assertEquals;

import javax.inject.Inject;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class MockitoSpyInjection {
    static class Notification { }
    static class EntryService { }
    static class RegDao {
        @Inject
        Notification foo;

        @Inject
        EntryService  bar;

        public RegDao() {
        }

        public RegDao(Notification foo, EntryService bar) {
            this.foo = foo;
            this.bar = bar;
        }

        public Notification getFoo() {
            return foo;
        }

        public EntryService getBar() {
            return bar;
        }

    }


    @Mock
    Notification foo;

    @Mock
    EntryService bar;

    @Spy
    @InjectMocks
    RegDao dao;

    @Test
    public void test() {
        assertEquals(foo, dao.getFoo());
        assertEquals(bar, dao.getBar());
    }
}

暫無
暫無

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

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