0

This the definition of my class:

class A
{
    public b method1()
    {
        //some code
    }
}

class Z
{
    A a = new A();
    public c method2()
    {
        z = a.method1();
        //some code validating z
    }
}

I want to test method2 using junit. The method1() call in method2() should return a valid z. How should I go ahead?

  • Did you mean you want to mock method**1**??? You shouldn't be mocking the method you want to test... – Codebender Jun 30 '15 at 12:08
  • If you want to test some method with mockito its better that make you a new class and make the correct anotattions, remember to import the JAR necessary. Here is an example. However, ive never seen a mocked method like. @mock public void {}; – carlos gil Jun 30 '15 at 12:16
  • http://www.adictosaltrabajo.com/tutoriales/mockito-example/ – carlos gil Jun 30 '15 at 12:16
  • Please note the changes in the question – Nissan Modi Jun 30 '15 at 12:17

1 Answers1

0

What should b, c and z be in your sample-code?

Usually you mock every other object your method under test is invoking or those invoked objects require, f.e. a.method1() call can be mocked like this:

// Arrange or given
Z sut = new Z();
Object method1RetValue = new Object();
A mockedA = mock(A.class); 
Mockito.when(mockedA.method1()).thenReturn(method1RetValue);

// set the mocked version of A as a member of Z
// use one of the following instructions therefore:
sut.a = mockedA;
sut.setA(mockedA);
Whitebox.setInternalState(sut, "a", mockedA);    

// Act or when
Object ret = sut.method2();
// Assert or then
assertThat(ret, is(equalTo(...)));

As a is a member of your test-class, you will need to set the mocked version first though, either via direct field assignment, setter-methods or via Whitebox.setInternalState(...) as depicted in the sample code above.

Note that the mocked method currently returns an object, you can return what ever the method returns. But as your example lacks a real type I just used an object here.

Roman Vottner
  • 12,213
  • 5
  • 46
  • 63
  • Thanks Roman! But, assume that "z" is a complex data type and cannot be used as "method1RetValue". It HAS to be computed using an actual call. I have seen Mocktio.when(mockedA.method1()).thenRealMethodCall() sort of functions but it doesnt work. Can you please help me? – Nissan Modi Jun 30 '15 at 16:38
  • If you want to invoke a real method call simply use `spy(new A())` instead of `mock(A.class)` f.e. If `method2()` however should return a fully instantiated obect of type `Z` you should consider returning a fake-object, which you fill with data you need for the test, instead of the real object. Remember that unit-tests simply checks the logic within the method you are testing - nothing more, nothing less. If you want to test that the real objects play together as expected, consider implementing an integration or even end-to-end test – Roman Vottner Jun 30 '15 at 17:05