Reputation: 1423
I have a simple method that returns a String
.
It also creates a local List
. I want to test the value added to the 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 test that when the customerVo.getName.equals("Terry")
, car
is added to the local List
.
Upvotes: 4
Views: 14854
Reputation: 61148
This isn't altogether that easy.
You need to use something like powermock.
With powermock you create create a scenario before then method is called and play it back, this means you can tell the ArrayList
class constructor to anticipate being called and return a mock
rather than a real ArrayList
.
This would allow you to assert on the mock
.
Something like this ought to work:
ArrayList listMock = createMock(ArrayList.class);
expectNew(ArrayList.class).andReturn(listMock);
So when your method creates the local List
powermock will actually return your mock List
.
More information here.
This sort of mocking is really for unit testing of legacy code that wasn't written to be testable. I would strongly recommend, if you can, rewriting the code so that such complex mocking doesn't need to happen.
Upvotes: 3