learningUser
learningUser

Reputation: 482

Mocking a method within a class using Mockito spy

Refering to mock methods in same class

class Temp() {

public boolean methodA(String param) {

     try {

         if(methodB(param))
               return true;

         return false;
     } catch (Exception e) {
           e.printStackTrace();
     }
}
}

The test class

@Test
public void testMethodA() {

Temp temp = new Temp();
Temp spyTemp = Mockito.spy(temp);

Mockito.doReturn(true).when(spyTemp).methodB(Mockito.any()); 
boolean status = temp.methodA("XYZ");

Assert.assertEquals(true, status);
}

When calling the real class temp to methodA should return the mocked method B value. Thus returning true. Why is this incorrect. I encounter the same problem. I want to run the test on the real class and not for mock object as suggested by the answer. I want to run the class methodA and expect the mocked object spyTemp methodB value when it is called

Upvotes: 1

Views: 12071

Answers (1)

LenglBoy
LenglBoy

Reputation: 1441

Here is the Problem: methodA() you´re callint is from temp and you´ve defined a returning value from tempSPY.

So you need to call tempSpy.methodA() and then it´s returning the value of methodB() you´ve defined.

Here the solution if methodB() is public - spy temp/cut and call it this way:

// temp = cut
@Test
public void testMethodA_valid() {
    // given
    Temp spyTemp = Mockito.spy(temp);
    boolean expected = true;
    Mockito.doReturn(expected).when(spyTemp).methodB(Mockito.any(String.class)); 

    // when
    boolean actual = spyTemp.methodA("XYZ");

    // then (faster readable)       
    Mockito.verify(spyTemp, times(1)).methodB(any(String.class))
    Mockito.verifyNoMoreInteraction(<ALL YOUR MOCKS HERE>);
    Assert.assertEquals(expected, is(equalTo(actual)));
}

If methodB() is private you can´t define what it should return. Then is´t just this and if error occures then methodB() got wrong behaviour:

@Test
public void testMethodA_valid() {
    // given
    boolean expected = true;

    // when
    boolean actual = temp.methodA("XYZ");

    // then (faster readable)       
    Assert.assertEquals(expected, is(equalTo(actual)));
}

Upvotes: 6

Related Questions