Issue
I am new to Junit and trying to write test case for the following scenario.
public List<String> transformColumns(String action){
return action.equals("delete"))?
tableInsert("onetwo", false)
:tableInsert("onetwothree", true);
}
If, I pass action value as transformColumns("delete"), tableInsert("onetwo", false) method should be called with value of false in second parameter. How to validate the parameter value of called method in Junit?
Solution
You can use Mockito to verify that some method is called. In this case you can use spy()
on the object you want to test, call the transformColumns()
method and check with verify()
, that the tableInsert()
method was indeed called. The unit test method might look like this:
@Test
public void mockitoTest() {
Foobar mock = Mockito.spy(Foobar.class);
mock.transformColumns("delete");
Mockito.verify(mock).tableInsert(Mockito.anyString(), Mockito.eq(false));
}
This test will pass, as the call transformColumns("delete")
will call the tableInsert()
method internally with the false
value for the second argument. If you change the argument for transformColumns()
or change the expected argument false
to true
you will see that this unit test method will fail with an error like this (the expression Mockito.eq(true)
was used to show the error):
Argument(s) are different! Wanted:
foobar.tableInsert(<any string>, true);
-> at testing.AllTests.mockitoTest(AllTests.java:14)
Actual invocations have different arguments:
foobar.transformColumns("delete");
-> at testing.AllTests.mockitoTest(AllTests.java:12)
foobar.tableInsert("onetwo", false);
-> at testing.Foobar.transformColumns(Foobar.java:8)
Answered By - Progman
Answer Checked By - Cary Denson (JavaFixing Admin)