public class Service1 {

private Service2 service2;

// FunctionA
private FuncA(Object1 obj1) {

    /*
    code to make Obj2 from Obj1
    */

    service2.FuncB(obj2);
  }

}

public class Service2 {
  // FunctionB
  private FuncB(Object2 obj) {
    obj.field=value;
  }

}


我正在尝试为Func A(如上所述)编写单元测试用例,并且为此需要模拟Func B(如上所述)。
请帮助我如何在Java 7中做到这一点。

附言Java新手

最佳答案

您需要将要测试的service2类中的Service1成员设置为由模拟框架创建的模拟对象。可能看起来像这样:

public class Service1Test {

    @Mock
    private Service2 service2;

    @InjectMocks // service2 mock will be injected into service1
    private Service1 service1;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void doTest() {

        Object someObject = null; // create object matching your needs
        service1.FuncA(someObject);

        Object someOtherObj = null; // create object matching your needs
        verify(service2, times(1)).FuncB(someOtherObj);

        // perform additional assertions
    }
}

09-11 18:32