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

Skip to first unread message

Peter Shankey

Jun 5, 2022, 4:50:30 PM6/5/22
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() {
   Pojo p = new Pojo();
   Integer i = p.convert("1");
   // do more stuff
   return i;

public class AppTest2 {    
     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

Reply all
Reply to author
0 new messages