简体   繁体   中英

How to mock helper methods used in service class?

How to mock helper methods used in service class. I tried to search but couldn't find, can you guide me?How to mock helper methods used in service class. I tried to search but couldn't find, can you guide me?

Service class function:

@Autowired
private MongoOperationsUtil myUtil;
@Override
public MyResponse getUsage(MyData input)
{
    myUtil.checkExistance(input.getName);
    MyResponse resp = new MyResponse();
    resp.setUsage(usage);
    resp.setMetaInfo(input);
      
    return resp;
}

Helper class method - content:
@Autowired
private RedisUtil redisUtil;
///RedisUtil is a class I created for crud ops in redis

public void checkExistance(String name){

    boolean inputFound = redisUtil.isKeyExists(name);
    if (!inputFound) {
         redisUtil.insert(name);
        
    }
    else{
        redisUtil.update(name);
     }

}

this is test logic: @SpringBootTest @RunWith(MockitoJUnitRunner.class) public class ApiUsageServiceTests { MongoOperationsUtil mongoUtilMock =Mockito.mock(MongoOperationsUtil.class);

@Test
public void getUsageTest() throws Exception{
 System.out.println("Checking getUsage() from service layer");

doNothing().when(mongoUtilMock).checkExistance(anyString());
// when()
mongoUtilMock.checkExistance(Mockito.anyString());
verify(mongoUtilMock,  
times(1)).checkExistance(Mockito.anyString());
}}

Now I need to write testcase for getUsage, by mocking checkExistance helper method, so how to do that to ensure coverage of LOC?

@Autowired
private MongoOperationsUtil myUtil;

you use @Autowired in myUtil. So the object is injected into spring container.

If you want to mock it in your test case, try to use @MockBean for MongoOperationUtil field.

Then you could try

    Mockito.when(myUtil.checkExistance(XXX)).thenReturn(YYY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM