Home > Blockchain >  Use result of one mock call in another
Use result of one mock call in another

Time:12-30

How can I use/inject the result of one mock into another?

I think I did it in the wrong way

The int param is always null

I use spy because the method I test is void. Can I do it using mockito?

@RunWith(MockitoJUnitRunner.class)
public class Test {

    @Mock
    Utils utils;

    @Mock
    Custom custom;

    @Spy
    @InjectMocks
    MyService service;

    @Test
    public void test(){
        Mockito.when(utils.get("p")).thenReturn(1); //use result of it in the next mock call

        Mockito.when(custom.isValid(1)).thenReturn(true); //custom use 1 here
        Mockito.doCallRealMethod().when(service).doIt("p");

        service.doIt("p");

        Mockito.verify(service,Mockito.times(1)).doIt("p");
    }
}
@Service
public class MyService {
    Utils utils;
    Custom custom;

    public MyService(Utils utils) {
        this.utils = utils;
    }

    public void doIt(String value){
        int param = utils.get(value);

        if(custom.isValid(param)){
            //do it
        }
    }
}

CodePudding user response:

You're mocking with wrong parameter, change your test like that:

public class Test {

   @Mock
   Utils utils;

   @InjectMocks
   MyService service;


   @BeforeEach
   void setUp(){
     initMocks(this);
   }

   @Test
   public void test(){  
       Mockito.when(utils.get(any())).thenReturn(1);

       service.doIt("p");

       Mockito.verify(utils).get(any());
   }
}

Instead any() you can put any another variable but it should be the same variable with variable which you call the service

CodePudding user response:

You don't actually need to Spy MyService. You can simplify your test and get it to work:

@RunWith(MockitoJUnitRunner.class)
public class Test {

   @Mock
   Utils utils;

   @InjectMocks
   MyService service;

    @Test
    public void test(){
        // Arrange
        Mockito.doReturn(1).when(utils.get("p"));
        Mockito.when(custom.isValid(1)).thenReturn(true);

        // Act
        service.doIt("p");

        // Assert
        Mockito.verify(utils, Mockito.times(1)).get("p");
        // You should also confirm that whatever is done in `if(param==1)` is actually done
    }
}
  • Related