1
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;  
  }

}

I am trying to write Unit Test Case for Func A (as mentioned above) and for that need to mock Func B(as mentioned above). Pls. help how can I do that in Java 7.

Ps. Newbie to Java

ankita gupta
  • 193
  • 1
  • 3
  • 12
  • 1
    i guess the code you are providing doesn't compile – Jens Mar 23 '17 at 07:57
  • Func . what it is? – santosh gore Mar 23 '17 at 07:57
  • 1
    Welcome to So. Please write the question assuming that what is clear to you, may not be clear to others. What is UT ? Where is `Func` defined ? – c0der Mar 23 '17 at 08:00
  • @c0der Can you pls. see the Sample code too. Func is Function and clearly specified. – ankita gupta Mar 23 '17 at 08:33
  • @ankitagupta your code is either not Java or incomplete. If it was Java `Func` would be the return type of the function `B` in your `Service2` class. But as you are calling `service2.funcB(...)` in your code, there is some mismatch.... – dpr Mar 23 '17 at 08:35
  • "Func is Function and clearly specified." - Not in the snippet you gave us. As is, function B in Service2 class is never called. – Fildor Mar 23 '17 at 08:47

1 Answers1

1

You need to set the service2 member in your Service1 class, that you are going to test, to a mock object created by your mocking framework. This could look something like this:

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
    }
}
dpr
  • 10,591
  • 3
  • 41
  • 71