Mockito mocking a class instantiated in a method of the class under test

24 views
Skip to first unread message

Peter Shankey

unread,
Jun 5, 2022, 4:50:30 PMJun 5
to mockito
public class Pojo {
 
 public Integer convert(String s) {
  System.out.println("this should be mocked");
  return new Integer(s);
 }
}


public class App2 {
 
  public Integer convert1() {
   System.out.println("convert1");
   Pojo p = new Pojo();
   Integer i = p.convert("1");
   // do more stuff
   return i;
  }
}


@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class AppTest2 {    
     @Test
     public void testConvert1() throws Throwable {
      App2 ut = Mockito.spy(App2.class);
    //  App2 ut = Mockito.spy(new App2());
    //  Pojo pojoMock = Mockito.spy(Pojo.class);
      Pojo pojoMock = Mockito.mock(Pojo.class);
      Integer integer = new Integer(20);
    //  Mockito.doReturn(integer).when(pojoMock.convert(Mockito.anyString()));
      Mockito.when(pojoMock.convert(Mockito.anyString())).thenReturn(integer); // pojoMock not used
    //  Mockito.when(pojoMock).convert(Mockito.anyString()).thenReturn(integer); // will not compile
    //  Mockito.doReturn(integer).when(ut).convert1(); // does not call App2.convert1
      int result = ut.convert1();
      System.out.println("result=" + result);
     }
 }    

In standard out I should see "convert1" but not "this should be mocked" and have the value of 20 returned by App2.convert1 Tried updating mockito to newest version and using the MockedConstruction but that did not work as well


thanks
Reply all
Reply to author
Forward
0 new messages