Issue
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
}
}
}
Solution
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
}
}
Answered By - João Dias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.