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

7

Service2没有注入MainService,因为它不是一个模拟。因此,server2您的mainService对象的属性是null

您还试图模拟太深。正确的测试方法MainService是模拟Service2and not的依赖关系SomeDAO

Service2模拟SomeDAO.

public TestClass {

    @InjectMocks
    private MainService mainService;

    @Mock
    private Service2 service2;

    @Before
    public void setUp() {
        initMocks(this);
    }

    @Test
    public void testMe() {
        mainService.doMain();

        verify(service2).doSomethingAnother();

    }

}
于 2013-04-19T08:49:58.250 回答