0

これは私のクラスの定義です:

class A
{
    public b method1()
    {
        //some code
    }
}

class Z
{
    A a = new A();
    public c method2()
    {
        z = a.method1();
        //some code validating z
    }
}

junitを使用してmethod2をテストしたい。method2() の method1() 呼び出しは、有効な z を返す必要があります。どうすればいいですか?

4

1 に答える 1

0

サンプルコードには何bを入れるべきですか?cz

通常、テスト対象のメソッドが呼び出している、または呼び出されたオブジェクトが必要とする他のすべてのオブジェクトをモックします。fea.method1()呼び出しは次のようにモックできます。

// Arrange or given
Z sut = new Z();
Object method1RetValue = new Object();
A mockedA = mock(A.class); 
Mockito.when(mockedA.method1()).thenReturn(method1RetValue);

// set the mocked version of A as a member of Z
// use one of the following instructions therefore:
sut.a = mockedA;
sut.setA(mockedA);
Whitebox.setInternalState(sut, "a", mockedA);    

// Act or when
Object ret = sut.method2();
// Assert or then
assertThat(ret, is(equalTo(...)));

はテストクラスのメンバーであるためa、直接フィールド割り当て、セッター メソッド、またはWhitebox.setInternalState(...)上記のサンプル コードに示されているように、最初にモック バージョンを設定する必要があります。

モックされたメソッドは現在オブジェクトを返すことに注意してください。メソッドが返すものは何でも返すことができます。しかし、あなたの例には実際の型がないため、ここではオブジェクトを使用しました。

于 2015-06-30T12:57:48.827 に答える