7

テストメソッドの内部メソッド呼び出しをモックしようとしています

私のクラスは次のようになります

public class App {
public Student getStudent() {
    MyDAO dao = new MyDAO();
    return dao.getStudentDetails();//getStudentDetails is a public 
                                  //non-static method in the DAO class
}

getStudent() メソッドの junit を作成するときに、PowerMock で行をモックする方法はありますか

dao.getStudentDetails();

または、DBに接続する実際のdao呼び出しの代わりに、junit実行中にAppクラスにモックdaoオブジェクトを使用させますか?

4

3 に答える 3

13

whenNew()PowerMockのメソッドを使用できます( https://github.com/powermock/powermock/wiki/Mockito#how-to-mock-construction-of-new-objectsを参照) 。

完全なテスト ケース

import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(App.class)
public class AppTest {
    @Test
    public void testGetStudent() throws Exception {
        App app = new App();
        MyDAO mockDao = Mockito.mock(MyDAO.class);
        Student mockStudent = Mockito.mock(Student.class);

        PowerMockito.whenNew(MyDAO.class).withNoArguments().thenReturn(mockDao);
        Mockito.when(mockDao.getStudentDetails()).thenReturn(mockStudent);
        Mockito.when(mockStudent.getName()).thenReturn("mock");

        assertEquals("mock", app.getStudent().getName());
    }
}

このテストケース用に簡単な Student クラスを作成しました。

public class Student {
    private String name;
    public Student() {
        name = "real";
    }
    public String getName() {
        return name;
    }
}
于 2013-01-03T13:47:08.403 に答える
1

モッキング フレームワークを最大限に活用するには、MyDAO オブジェクトをインジェクトする必要があります。Spring our Guice のようなものを使用するか、単純にファクトリ パターンを使用して DAO オブジェクトを提供することができます。次に、単体テストでは、実際の DAO オブジェクトではなくモック DAO オブジェクトを提供するテスト ファクトリを用意します。次に、次のようなコードを記述できます。

Mockito.when(mockDao.getStudentDetails()).thenReturn(someValue);
于 2012-01-13T16:45:07.107 に答える
-1

Mockito にアクセスできない場合は、PowerMock を使用して同じ目的を実行することもできます。たとえば、次のことができます。

@RunWith(PowerMockRunner.class)
@PrepareForTest(App.class)
public class AppTest {
    @Test
    public void testGetStudent() throws Exception {
        MyDAO mockDao = createMock(MyDAO.class);
        expect(mockDao.getStudentDetails()).andReturn(new Student());        
        replay(mockDao);        

        PowerMock.expectNew(MyDAO.class).andReturn(mockDao);
        PowerMock.replay(MyDAO.class);         
        // make sure to replay the class you expect to get called

        App app = new App();

        // do whatever tests you need here
    }
}
于 2013-04-22T17:57:44.270 に答える