簡體   English   中英

如何使用Easymock / Powermock模擬對象響應帶參數的方法

[英]How to use easymock/powermock mock objects to respond to methods with arguments

我正在嘗試對Y類進行單元測試。

我有X班

public class X {
    private List<B> getListOfB(List<A> objs) {
    }
}

現在是另一個Y類

public class Y {
    private X x;

    public Z getZ() {
        List<A> aObjs = created inline.
        // I am having problems over here
        List<B> bObjs = x.getListOfB(aObjs);
    }
}

我正在嘗試測試Y,但似乎無法理解。 所以這是我到目前為止所遇到的,我被困住了

@Test
public void testgetZ() {
    X x = createMock(X.class);
    Y y = new Y(x);
    // How do I make this work?
    y.getZ();
}

您需要在X類的模擬實例上添加期望。 這些期望將設置X對象以返回可以測試的B對象的列表。

我還提到了捕獲的使用。 在EasyMock中,捕獲可用於對傳遞給模擬方法的對象執行斷言。 如果(例如您的示例)無法提供傳遞給模擬對象的實例化對象,則此功能特別有用。

因此,我認為您希望測試看起來像這樣:

@Test
public void thatYClassCanBeMocked() {
    final X mockX = createMock(X.class);
    final Y y = new Y(mockX);

    //Set up the list of B objects to return from the expectation
    final List<B> expectedReturnList = new List<B>();

    //Capture object for the list Of A objects to be used in the expectation
    final Capture<List<A>> listOfACapture = new Capture<List<A>>();

    //expectation that captures the list of A objects provided and returns the specified list of B objects
    EasyMock.expect( mockX.getListOfB( EasyMock.capture(listOfACapture) ) ).andReturn(expectedReturnList);

    //Replay the mock X instance
    EasyMock.replay(mockX);

    //Call the method you're testing
    final Z = y.getZ();

    //Verify the Mock X instance
    EasyMock.verify(mockX);

    //Get the captured list of A objects from the capture object
    List<A> listOfA = listOfACapture.getValue();

    //Probably perform some assertions on the Z object returned by the method too.
}

暫無
暫無

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

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