Mocking Matcher with non native class - mockito

I am trying to write a #test in Junit using mockito and powermock. I have no issue stubbing methods that have no parameters. However when I try telling mockedBank to return true no matter what is passed into latePay, I get java.lang.NullPointerException. latePay is a final method that is why I am using powermock. Any suggestions are much appreciated.
BankGenerator mockedBank = PowerMockito.mock(BankGenerator.class);
when(mockedBank.latePay(Matchers.any(MoneyCalculator.class))).thenReturn(true);

Have you added the correct annotations to your class containing the tests?
For example:
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassWithFinalMethod.class)
public class ClassContainingUnitTests {
...
}
I have used PowerMock with EasyMock in the past, and forgetting to include these annotations sometimes resulted in strange results.
For further reference, check here:
http://www.codeproject.com/Articles/806508/Using-PowerMockito-to-Mock-Final-and-Static-Method
Hope this helps.

Related

Trying to define a Mockito-stub executes the mocked method. Why?

We are trying to define a UnitTest where we mock an object which I here called x for simplicity:
...
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import org.kubek2k.springockito.annotations.SpringockitoContextLoader;
import org.kubek2k.springockito.annotations.WrapWithSpy;
...
#ContextConfiguration(
loader = SpringockitoContextLoader.class,
inheritLocations = true)
public class SyncServiceIntegrationTest extends AbstractIntegrationTest {
#Autowired
#WrapWithSpy
private EventDrivenIssueDeliveryConfirmer x;
...
#Before
public void setUp() {
...
doNothing().when(x).foobar(any(Event.class));
}
...
i.e. we want our UT (not shown here) to later NOT call the method foobar on that object x.
Strange enough we get an NPE during initialization of this UT-class. The NPE is thrown by method foobar(), when the passed argument is null.
As turned out this call with argument null happens in the line doNothing()... in the setup-method which in our understanding is supposed to just define the mock-object's stubbing. But instead it evaluates the any(Event.class)-expression which apparently yields null and with that result it then calls the foobar(...)-method on x which causes the NPE.
Besides the NullPointerException we also get an error message from Mockito:
java.lang.NullPointerException: null
... <stack trace omitted for brevity>
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at ch.sst.integration.SyncServiceIntegrationTest .setUp(SyncServiceIntegrationTest.java:69)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
... <examples omitted for brevity>
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at ch.sst.integration.SyncServiceIntegrationTest .setUp(SyncServiceIntegrationTest.java:69)
...
Why is that so??? Why is our stubbing considered "unfinished"? What are we missing here?
Later addition:
The issue seems to have to do with the fact that class
EventDrivenIssueDeliveryConfirmer is marked with #Transactional. Removing/commenting that lets the UT succeed. But of course that's no workaround - we need that annotation.
At least this provides a hint in which direction to search. The wrapping caused by #Transactional and the wrapping done by Mockito seem to step on each other's foot here.
I have the same issue but with a totally different setup: kotlin, mockito and, of course, mockito-kotlin.
I comment on this issue because maybe somebody will come to this question with the kotlin mockito problem in the future? I sure did. Anyhow.
When not declaring a method as open in kotlin it's compiled as a final method which can't be mocked by mockito-kotlin. As a result the method gets executed which to me is kind of weird but that's what it does. It's mentioned in the mockito-kotlin github issues under https://github.com/mockito/mockito-kotlin/issues/314

Is there an alternative to RETURNS_DEEP_STUBS for mocking chained methods with Mockito?

I have a db service save() method which allows method chaining:
#Service
public class Service {
...
public Service save(...) {
...
return this;
}
and this works just great as:
service.save(this).save(that).save(other);
When I come to mock it with Mockito though it breaks unless I use
Service serviceMock = mock(Service.class, RETURNS_DEEP_STUBS);
IIUC though, the use of RETURNS_DEEP_STUBS is considered bad. Is there a better way to mock a class with method call chaining?
Your pattern for save is very similar to a Builder pattern, which makes the question similar to "How to mock a builder with mockito" elsewhere on SO.
Per David Wallace's answer there, you can write an Answer that detects whether the mock is an instance of the return type of the method, and return the mock in only that case. This functionality was also built into the Mockito library as RETURNS_SELF in Mockito 2.0. As with any Answer, you can use this on any specific method call with thenAnswer or as the second parameter of mock to make it the default answer, but bear in mind the Mockito documentation warning that methods with generous return types (e.g. Object) will return the mock whether or not that was intended.

Mockito.when() not working

I am trying to mock a call to a protected method of one of my classes:
import com.couchbase.client.java.view.Stale; // an enum
import com.google.common.base.Optional;
public class MyClass {
public List<String> myList(Optional<Integer> arg1, Optional<Stale> arg2) {
...
}
}
The mock shall be accomplished in the following way:
// Providing types for any() does not change anything
Mockito.when(myClass.myList(Mockito.any(), Mockito.any()).thenReturn(new ArrayList());
Whenever the previous line is executed the actual myList() method is called with null values for arg1 and arg2. Why is the method called, at all? After all, I am trying to avoid any executing thereof...
As Brice mentioned, if your myList method is final, then Java skips virtual method dispatch and will call the original object (not your mock).
If you are spying on an actual class, it is expected behavior that when will call the actual object as part of the stub: after all, in the expression when(foo.bar()) Java doesn't know anything special about when and assumes that it cares about the return value) of foo.bar(), not the call itself. (I walk through the stubbing process in the "Implementation details" section of my answer here.)
This syntax is better for spies:
doReturn(new ArrayList()).when(myClass).myList(any(), any());
Because this different when method receives an object, Mockito can prepare the object to do nothing during the stubbing, which avoids any spurious calls to your myList method.
Although Jeff's answer did not show a workaround for my problem it pointed me into the right direction.
After changing the mocking behaviour to doReturn... I suddenly got an error message. This message told me that myClass is not a mock which makes sense since you can only mock (or stub?) methods of mocked or spied objects. So as Jeff's answer indicates and is explained in the documentation of mockito I created a partial mock of MyClass with
MyClass myClass = Mockito.spy(new MyClass());
With this partial mock Jeff's approach to method mocking suddenly worked (mine still does not and should therefore be avoided).
So: Thank you, Jeff!

Adding methods to class and use them in other groovy code

I'm very new to Groovy. I have a class where I'm adding methods using metaClass. Here is the code I have for Parser.groovy:
PrivateClass.metaClass.convertDDTToMap { obj,fileLocation ->
}
where PrivateClass is a class coming from a jar. Now in other file named Hack.groovy I have the following code:
class Hack extends PrivateClass
{
//.. code
convertDDTToMap(param,param)
}
when I run Hack.groovy, I get the exception that the method convertDDTToMap is not there.
However Parser.groovy is in the same classpath and it gets compiled. But its not adding the method.
Where I'm making the mistake?
Parser.groovy being compiled only is doing nothing, the code there needs to be called. For example using new Parser().run()

Partial Mocking Class with Multiple Static Methods with GMock

I'm using GMock to add some unit testing to our existing Java projects. We have multiple places where the methods needing to be tested are static methods, which utilize additional static methods within the method we want to test.
I would like to be able to partially mock the class, pretty much all static methods on the class other than the initial entry point for testing.
For example:
class StaticClass {
static void method(String one) {
method2()
}
static void method(String one, String two) {
...
}
}
My hope is that I can mock the second static method but as soon as I do, method(String) goes MIA and executing the test fails with an expectation exception. Is there a way I can partially mock the class, maintaining the functionality of the first method but mock the static access of the second method?
I've also tried using metaClass programming to mock the method, but if I set method equal to a closure, the first method goes MIA again. Not sure how to do this with overloaded methods. Any ideas?
In Gmock, it mocks static methods and matches expectations according to their names. It means you cannot mock one overloaded method but not another.
It is the same with MOP of Groovy.
While this doesn't involve GMock specifically, you could extend StaticClass inside your test file and override the methods there

Resources