0

私は3つのクラスを持っています:

public class SomeDAO {

   // that method I'd want to catch and change
   public void getObj() { ... }

}

public class MainService {

    private Service2 service2;

    public void doMain() {
        service2.doSomethingAnother();
    }

}

public class Service2 {

    private SomeDAO someDAO

    public void doSomethingAnother() {
        someDAO.getObj();
    }
}

必要なのはdoMainを呼び出すことですが、 service2.doSomethingAnother()内にカスタムの someDao.getObj() を使用します。

public TestClass {

    @InjectMocks
    private final MainService mainService = new MainService();

    @InjectMocks
    private final Service2 service2 = new Service2();

    @Mock
    private SomeDAO someDao;

    @Test
    public void testMe() {

        // substitution
        when(someDao.getObj()).thenReturn(new MyObj());

        // then I'm calling the outer method
        mainService.doMain();

    }

}

そのテストを実行すると、mainService.doMain()に NPE があります: service2 in null..

testMeオブジェクト内のservice2は有効で null ではなく、クラス変数として宣言され、初期化されています。

@InjectMock の動作を誤解しているかどうか

4

1 に答える 1