Mokito with local variables

I have a simple method that returns a String .

It also creates a local List . I want to check the value added on a local List .

Here is an example

 package com.impl; import java.util.ArrayList; import java.util.List; import com.test.domain.CustomerVo; public class ClassImpl { public String assignGift(CustomerVo customerVo) { List<String> listOfGift = new ArrayList<String>(); if (customerVo.getName().equals("Joe")) { listOfGift.add("ball"); } else if ((customerVo.getName().equals("Terry"))) { listOfGift.add("car"); } else if (customerVo.getName().equals("Merry")) { listOfGift.add("tv"); }else { listOfGift.add("no gift"); } return "dummyString"; } } 

How can I check this when customerVo.getName.equals("Terry") , car added to the local List .

+4
source share
1 answer

It's not so easy.

You need to use something like powermock .

With powermock created, create a script before the method is called and plays it, which means that you can tell the constructor of the ArrayList class to ArrayList for the call and return a mock , not a real ArrayList .

This will allow you to claim on mock .

Something like this should work:

 ArrayList listMock = createMock(ArrayList.class); expectNew(ArrayList.class).andReturn(listMock); 

So, when your method creates a local List , powermock will return your mock List .

More details here .

This mix is ​​valid for unit testing outdated code that was not written for verification. I would highly recommend rewriting the code if possible so that such complex bullying should not occur.

+3
source

Source: https://habr.com/ru/post/1480322/


All Articles