Mockito mock all methods call and return - java

I have a problem when writing unit testing with mock. There is a object which I need to mock have a lot getter, which I do call them at the code. However, those are not the purpose of my unit test. So, is there is a way I can mock all the methods instead of mock them one by one.
Here is the code example:
public class ObjectNeedToMock{
private String field1;
...
private String field20;
private int theImportantInt;
public String getField1(){return this.field1;}
...
public String getField20(){return this.field20;}
public int getTheImportantInt(){return this.theImportantInt;}
}
and this is the service class I need to test
public class Service{
public void methodNeedToTest(ObjectNeedToMock objectNeedToMock){
String stringThatIdontCare1 = objectNeedToMock.getField1();
...
String stringThatIdontCare20 = objectNeedToMock.getField20();
// do something with the field1 to field20
int veryImportantInt = objectNeedToMock.getTheImportantInt();
// do something with the veryImportantInt
}
}
within the test class, the test method is like
#Test
public void testMethodNeedToTest() throws Exception {
ObjectNeedToMock o = mock(ObjectNeedToMock.class);
when(o.getField1()).thenReturn(anyString());
....
when(o.getField20()).thenReturn(anyString());
when(o.getTheImportantInt()).thenReturn("1"); //This "1" is the only thing I care
}
So, is there a way that I can avoid writing all the "when" for the useless "field1" to "field20"

You can control the default answers of your mock. When you're creating the mock, use:
Mockito.mock(ObjectNeedToMock.class, new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
/*
Put your default answer logic here.
It should be based on type of arguments you consume and the type of arguments you return.
i.e.
*/
if (String.class.equals(invocation.getMethod().getReturnType())) {
return "This is my default answer for all methods that returns string";
} else {
return RETURNS_DEFAULTS.answer(invocation);
}
}
}));

If you're not interested in the result of getField1() to getField20() in a particular test case, you shouldn't mock it at all. In other words, if all the specific test case should be concerned about is getTheImportantInt(), then your test case should look like this:
#Test
public void testMethodNeedToTest() throws Exception {
ObjectNeedToMock o = mock(ObjectNeedToMock.class);
when(o.getTheImportantInt()).thenReturn("1");
// test code goes here
}

For kotlin users:
val mocked:MyClassToMock = Mockito.mock(MyClassToMock::class.java,
object:Answer<Any> {
override fun answer(invocation: InvocationOnMock?): Any {
if (String::class.java.equals (invocation?.method?.getReturnType())) {
return "Default answer for all methods that returns string";
} else {
return Mockito.RETURNS_DEFAULTS.answer(invocation);
}
}
})

Related

How can I fix this behavior of getMethod()?

In class A, i got a function called updateAttribute. In class B, I got a junit test, which stores during execution this function in a Method object (code is simplified).
public class A {
public Optional<AttributeObject> updateAttribute(
#ApiParam("Qual of attribute") #PathParam("qual") #Qual final String qual,
#NotNull #Valid final UpdateObject a) {
// here, I've cut a few lines of code
return null;
}
}
public class ATest extends AnotherTest {
#Test
public void someTest()
throws NoSuchMethodException, SecurityException {
try (
// some code I've cut
final Method method =
A.getClass().getMethod("updateAttribute", String.class, UpdateObject.class);
// some code I've cut
}
}
}
The junit test fails at this call of .getMethod() with:
java.lang.IllegalArgumentException: HV000181: Wrong number of
parameters. Method or constructor
java.util.Optional"<"packageName.A">"#updateAttribute(String,
UpdateObject) expects 1 parameters, but got 2.
(...)
When I change the call to
final Method method =
A.getClass().getMethod("updateAttribute", String.class);
or similar, the trace just claims - as expected - that this method doesn't exist.Any ideas how to fix this?
Not an answer, just content that doesn't fit into a comment.
Reduced the code to this:
#Test
public void someTest()
throws NoSuchMethodException, SecurityException {
final Method method =
A.class.getMethod("updateAttribute", String.class, Integer.class);
}
}
class A {
public Optional<String> updateAttribute(
final String qual, Integer a) {
return null;
}
}
And that works fine.
Not reproducable.

Mockito mock a method but use its parameters for the mocked return

There is a method public Content createChild(String path, String contentType, Map<String,Object> properties) I'd like to mock.
I want to mock it that way that the method is called with any kind of arguments, therefore when() wouldn't work because I have to tell it what arguments the method should receive to be actually mocked.
So I want to actually react on any method call independent of its given arguments (use spies?) and then call some kind of "callback" to return a Content object which I want build together out of the real arguments given to the method.
I could not find a specific API in Mockito which supports this.
You can use Matchers:
You can try something like:
when(service.createChild(anyString(), anyString(), anyMap()))
.thenReturn(any(Content.class));
Sure you can. I have written simple unit test for this
public class MockitoTest {
private SampleService sampleService;
#Before
public void setUp() throws Exception {
sampleService = Mockito.mock(SampleService.class);
}
#Test
public void mockitoTest() throws Exception {
when(sampleService.createChild(anyString(), anyString(), anyMapOf(String.class, Object.class)))
.thenAnswer(invocationOnMock -> {
//Here you can build result based on params
String pathArg = (String) invocationOnMock.getArguments()[0];
if (pathArg.equals("p1")) {
return new Content("Content for p1");
} else if (pathArg.equals("p2")) {
return new Content("Content for p2");
} else {
return invocationOnMock.callRealMethod();
}
});
Content content = sampleService.createChild("p1", "any", new HashMap<>());
assertEquals("Content for p1", content.getData());
content = sampleService.createChild("p2", "any", new HashMap<>());
assertEquals("Content for p2", content.getData());
content = sampleService.createChild("whatever", "any", new HashMap<>());
assertEquals("original", content.getData());
}
/**
* Sample service with method
*/
private static class SampleService {
public Content createChild(String path, String contentType, Map<String, Object> properties) {
return new Content("original");
}
}
/**
* Content example
*/
private static class Content {
private String data;
Content(String data) {
this.data = data;
}
String getData() {
return data;
}
}
}
You can use matchers
MyClass m = mock(MyClass.class);
when(m.createChild(any(String.class), any(String.class), any(Map.class))).thenReturn(new Content());
You should also be able to use the parameters this way
when(m.createChild(any(String.class), any(String.class), any(Map.class))).thenAnswer(
new Answer<Content>()
{
#Override
public Content answer(final InvocationOnMock invocation) throws Throwable
{
return new Content((String) invocation.getArguments()[0],
(String) invocation.getArguments()[1],
(Map) invocation.getArguments()[2]);
}
}
}
);
You can try something like with use of eq() and any() as per as your requirement:
when(service.createChild(eq("helloe/hi"), any(String.class), any(Map.class)))
.thenReturn(any(Content.class));
eq - If we want to use a specific value for an argument, then we can use eq() method.
any - Sometimes we want to mock the behavior for any argument of the given type

Mocking chained methods calls using PowerMock

I have a class which I would like to test with a public static method that contains some chained method calls. Assuming that an exception occurs during the chained method calls, how do I handle this effectively and make it return some specific value?
Following is the code sample of the test class.
#RunWith(PowerMockRunner.class)
#PrepareForTest({CodeWithPrivateMethod.class,CodeWithAnotherPrivateMethod.class,CodeWithYetAnotherPrivateMethod.class})
public class CodeWithPrivateMethodTest {
#Test
public void when_gambling_is_true_then_always_explode() throws Exception {
CodeWithYetAnotherPrivateMethod codeWithYetAnotherPrivateMethod = PowerMockito.spy(new CodeWithYetAnotherPrivateMethod());
PowerMockito.whenNew(CodeWithYetAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithYetAnotherPrivateMethod);
CodeWithAnotherPrivateMethod codeWithAnotherPrivateMethod = PowerMockito.spy(new CodeWithAnotherPrivateMethod());
PowerMockito.whenNew(CodeWithAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithAnotherPrivateMethod);
PowerMockito.doReturn(true).when(codeWithYetAnotherPrivateMethod, "getGambling");
//PowerMockito.doReturn(codeWithYetAnotherPrivateMethod).when(codeWithAnotherPrivateMethod, "getGambleValue");
PowerMockito.spy(CodeWithPrivateMethod.class);
CodeWithPrivateMethod.startGamble();
}
}
Following is the code sample for the class under test
public class CodeWithPrivateMethod {
public static void startGamble() {
Boolean gamble = CodeWithAnotherPrivateMethod.getGambleValue()
.getGambling();
if (gamble) {
System.out.println("kaboom");
}else{
System.out.println("boom boom");
}
}
}
Following is the code sample for the class that gets called from the class under test
public class CodeWithAnotherPrivateMethod {
static CodeWithYetAnotherPrivateMethod codeWithYetAnotherPrivateMethod = new CodeWithYetAnotherPrivateMethod();
public static CodeWithYetAnotherPrivateMethod getGambleValue() {
return codeWithYetAnotherPrivateMethod; //works fine
return null; // fails
}
}
Following is the code sample for the other class that gets called from the class under test
public class CodeWithYetAnotherPrivateMethod {
public Boolean getGambling() {
return false;
}
}
So Assuming I return a null value from getGambleValue() method of CodeWithAnotherPrivateMethod class, how do I handle this null value effectively in my testclass?
This is how to specify expected exceptions using Mockito:
#Test(expected = NullPointerException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
...
Before I found out about this I would do:
#Test
public void when_gambling_is_true_then_always_explode() throws Exception {
// setup omitted
try {
CodeWithPrivateMethod.startGamble();
}
catch(NullPointerException e) {
// expected
return;
}
fail("Expected NullPointerException");
}
EDIT: Testing multiple classes that call each other statically like this is a severe code smell. Unit tests should test a single class and inline static calls should be limited to utility classes.
Another comment: your example class names are very confusing. Next time please stick with Foo, Bar, Baz or Appple, Pear, Banana.
If you are not getting an NPE then I expect your mocking/spying is interfering. If you call the code under test without mocking/spying the call chain would be:
CodeWithPrivateMethod.startGamble();
->
CodeWithYetAnotherPrivateMethod value = CodeWithAnotherPrivateMethod.getGambleValue();
->
return null;
<-
value.getGambling();
<- throws NullPointerException
What exactly are you trying to find out or achieve?
EDIT: Here's how it should work with PowerMock
#RunWith(PowerMockRunner.class)
#PrepareForTest(CodeWithAnotherPrivateMethod.class)
public class CodeWithPrivateMethodTest {
#Mock
private CodeWithYetAnotherPrivateMethod yetAnotherInstance;
#Test
public final void testStartGamble() {
// SETUP
mockStatic(CodeWithAnotherPrivateMethod.class);
expect(CodeWithAnotherPrivateMethod.getGambleValue())
.andReturn(yetAnotherInstance);
Boolean gamblingValue = true;
expect(yetAnotherInstance.getGambling()).andReturn(gamblingValue);
replayAll();
// CALL
CodeWithPrivateMethod.startGamble();
// VERIFY
verifyAll();
}

Mockito & Junit null pointer exception: name must not be null

I have been trying to run the following test using mockito and junit and I keep on getting "java.lang.NullPointerException: name must not be null"
Can anyone tell me why this is happening?
On debugging, I found out that this exception is thrown when the test executes the following statement in isStopValid(String) method:
FacilityValidationUtil facUtil = new FacilityValidationUtil();
#RunWith(MockitoJUnitRunner.class)
public class MyFormTest{
#InjectMocks MyForm form = new MyForm();
#Mock FacilityValidationUtil facUtil;
#Test
public void testIsStopValid() throws FinderException{
when(facUtil.isFacilityValid("")).thenReturn(false);
form.setOrigin("");
assertEquals(false, form.isStopValid(form.getOrigin()));
}
}
Class with method to be tested:
public class MyForm{
FacilityValidationUtil facUtil = new FacilityValidationUtil();
public boolean isStopValid(String stop){
try {
return facUtil.isFacilityValid(stop);
} catch (FinderException e) {
log.error("Error finding the stop. "+e.getCause());
return false;
}
}
}
public class FacilityValidationUtil{
private FacilityDAO facilityDao = new HibernateFacilityDAO();
public boolean isFacilityValid(String facility) throws FinderException{
boolean test;
FacilityImpl facilityImpl = facilityDao.findFacilityByNassCode(facility);
test = (facilityImpl==null)?false : true;
return test;
}
}
public class HibernateFacilityDAO extends HibernateAbstractDeltaDAO implements FacilityDAO {
public HibernateFacilityDAO() {
super(false);
}
}
Short Answer: You are trying to mock a variable (facUtil) that is local to your isStopValid method, so the mock version of this object in your test is never going to be called because you are 'newing it up" each time.
Long Answer: It looks like you are trying to mock the call to your FacilityValidationUtil class, and if this is the case, then you need to either make the class a field so that Mockito can inject the object by reflection (if this object is thread safe, which it looks like it is) or explore a mocking framework like PowerMockito that will allow you to mock a constructor (google for PowerMockito when new).
PowerMockito.whenNew(FacilityValidationUtil.class).withNoArguments().thenReturn(facUtil);
Mockito doesn't support any mocking of constructor args by default.
EDIT
If you are still having trouble, then I would suggest starting with a smaller example. I've put together one for you that works and uses the code you are trying to test (It's using inner classes though, which Mockito has some quirky rules about, but I'm just doing it to compress the example).
#RunWith(MockitoJUnitRunner.class)
public class MyFormTest {
#InjectMocks
private MyForm form = new MyForm();
#Mock
private FacilityValidationUtil facUtil;
#Test
public void testIsStopValid_false() {
when(facUtil.isFacilityValid("")).thenReturn(false);
assertEquals(false, form.isStopValid(""));
}
#Test
public void testIsStopValid_true() {
when(facUtil.isFacilityValid("")).thenReturn(true);
assertEquals(true, form.isStopValid(""));
}
public class MyForm {
private FacilityValidationUtil facUtil = new FacilityValidationUtil();
public boolean isStopValid(String stop) {
try {
return facUtil.isFacilityValid(stop);
} catch (FinderException e) {
return false;
}
}
}
public class FacilityValidationUtil {
public boolean isFacilityValid(String facility) throws FinderException {
throw new RuntimeException(facility);
}
}
public class FinderException extends RuntimeException {
public FinderException(String message) {
super(message);
}
}
}
What's really important is that your mock is not getting injected correctly. Until you get that resolved, you are going to keep getting the same error. Set a break point in your MyForm at the point you call facUtil.isFaciltyValid and look at the object. It should be a mockito object, not your class.
Good luck.

Making a mocked method return an argument that was passed to it

Consider a method signature like:
public String myFunction(String abc);
Can Mockito help return the same string that the method received?
Since Mockito 1.9.5+ and Java 8+
You can use a lambda expression, like:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
Where i is an instance of InvocationOnMock.
For older versions
You can create an Answer in Mockito. Let's assume, we have an interface named MyInterface with a method myFunction.
public interface MyInterface {
public String myFunction(String abc);
}
Here is the test method with a Mockito answer:
public void testMyFunction() throws Exception {
MyInterface mock = mock(MyInterface.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
#Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
assertEquals("someString",mock.myFunction("someString"));
assertEquals("anotherString",mock.myFunction("anotherString"));
}
If you have Mockito 1.9.5 or higher, there is a new static method that can make the Answer object for you. You need to write something like
import static org.mockito.Mockito.when;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
when(myMock.myFunction(anyString())).then(returnsFirstArg());
or alternatively
doAnswer(returnsFirstArg()).when(myMock).myFunction(anyString());
Note that the returnsFirstArg() method is static in the AdditionalAnswers class, which is new to Mockito 1.9.5; so you'll need the right static import.
With Java 8 it is possible to create a one-line answer even with older version of Mockito:
when(myMock.myFunction(anyString()).then(i -> i.getArgumentAt(0, String.class));
Of course this is not as useful as using AdditionalAnswers suggested by David Wallace, but might be useful if you want to transform argument "on the fly".
I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:
public class RoomService {
public Room findByName(String roomName) {...}
public void persist(Room room) {...}
}
The service mock uses a map to store the Room instances.
RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();
// mock for method persist
doAnswer(new Answer<Void>() {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
Room room = (Room) arguments[0];
roomMap.put(room.getName(), room);
}
return null;
}
}).when(roomService).persist(any(Room.class));
// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
#Override
public Room answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
String key = (String) arguments[0];
if (roomMap.containsKey(key)) {
return roomMap.get(key);
}
}
return null;
}
});
We can now run our tests on this mock. For example:
String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));
With Java 8, Steve's answer can become
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(
invocation -> {
Object[] args = invocation.getArguments();
return args[0];
});
assertEquals("someString", mock.myFunction("someString"));
assertEquals("anotherString", mock.myFunction("anotherString"));
}
EDIT: Even shorter:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(
invocation -> invocation.getArgument(0));
assertEquals("someString", mock.myFunction("someString"));
assertEquals("anotherString", mock.myFunction("anotherString"));
}
This is a pretty old question but i think still relevant. Also the accepted answer works only for String. Meanwhile there is Mockito 2.1 and some imports have changed, so i would like to share my current answer:
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
#Mock
private MyClass myClass;
// this will return anything you pass, but it's pretty unrealistic
when(myClass.myFunction(any())).then(returnsFirstArg());
// it is more "life-like" to accept only the right type
when(myClass.myFunction(any(ClassOfArgument.class))).then(returnsFirstArg());
The myClass.myFunction would look like:
public class MyClass {
public ClassOfArgument myFunction(ClassOfArgument argument){
return argument;
}
}
You can achieve this by using ArgumentCaptor
Imagine you have bean function like so.
public interface Application {
public String myFunction(String abc);
}
Then in your test class:
//Use ArgumentCaptor to capture the value
ArgumentCaptor<String> param = ArgumentCaptor.forClass(String.class);
when(mock.myFunction(param.capture())).thenAnswer(new Answer<String>() {
#Override
public String answer(InvocationOnMock invocation) throws Throwable {
return param.getValue();//return the captured value.
}
});
OR if you fan of lambda simply do:
//Use ArgumentCaptor to capture the value
ArgumentCaptor<String> param = ArgumentCaptor.forClass(String.class);
when(mock.myFunction(param.capture()))
.thenAnswer((invocation) -> param.getValue());
Summary: Use argumentcaptor, to capture the parameter passed. Later in answer return the value captured using getValue.
This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:
#Test
fun demo() {
// mock a sample function
val aMock: (String) -> (String) = mockk()
// make it return the same as the argument on every invocation
every {
aMock.invoke(any())
} answers {
firstArg()
}
// test it
assertEquals("senko", aMock.invoke("senko"))
assertEquals("senko1", aMock.invoke("senko1"))
assertNotEquals("not a senko", aMock.invoke("senko"))
}
You might want to use verify() in combination with the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mock).myFunction(argument.capture());
assertEquals("the expected value here", argument.getValue());
The argument's value is obviously accessible via the argument.getValue() for further manipulation / checking /whatever.
I use something similar (basically it's the same approach). Sometimes it's useful to have a mock object return pre-defined output for certain inputs. That goes like this:
private Hashtable<InputObject, OutputObject> table = new Hashtable<InputObject, OutputObject>();
table.put(input1, ouput1);
table.put(input2, ouput2);
...
when(mockObject.method(any(InputObject.class))).thenAnswer(
new Answer<OutputObject>()
{
#Override
public OutputObject answer(final InvocationOnMock invocation) throws Throwable
{
InputObject input = (InputObject) invocation.getArguments()[0];
if (table.containsKey(input))
{
return table.get(input);
}
else
{
return null; // alternatively, you could throw an exception
}
}
}
);

Categories