How do I stub default void method of Mapstruct interface for Unit testing a class that is calling that default method? - junit

I am unit testing a class in Java 8 that is calling a default method of a mapstruct interface and that method returns void. I am not able to stub the method call using Mockito.doNothing()...When(object).method(). The execution enters the actual method (in mapstruct interface) Pls provide your inputs to solve this problem.

Related

Exception being thrown during mocking

I want to mock out a situation where if the service is called with a specific set of inputs, it should return a value, but if it's called with any other inputs throw an exception. So I've got:
doThrow(new ValidationException()).when(mockService).thing(any(), any());
when(mockService.thing(EXPECTED_PARAM_1, EXPECTED_PARAM_2).thenReturn(mockResult);
But when I go to run my test it throws the ValidationException on that second line where I'm creating the mock. It seems as though that second line is being treated as if I was actually calling the service, and since I'm mocking it with params that fit the any() any() it's throwing the exception rather than setting up the additional mock.
Thanks!
It turns out when.thenReturn actually calls the method it's mocking exactly once when the mock is first setup. Since the previous mock setup the default scenario where anytime the method is called it should thrown the exception, the second mock when it does its initial single call triggers the first mock and throws.
The solution to this scenario is to switch the second mock to use doReturn.when instead, as it never actually calls the method.

Cannot Deserialize LifeRay Service Model Object from JSON that came from ElasticSearch, Default Constructor not Found

Using LifeRay portal and ElasticSearch, Serializing custom object composed from ServiceModel Objects, Serialisation goes fine:
public String toJSON(){
return JSONFactoryUtil.looseSerializeDeep(this);
}
I index this into ES which is also fine, it contains list of those objects as well as single object, no problem.
When I Deserialize this I get this Error:
10:10:53,972 ERROR [ExceptionHandlerBridgeImpl:78] jodd.json.JsonException: Default ctor not found for: eu.project.drives.platform.model.model.TainingProvider
For each parameter which is Object from Service Model.
Code (should be ok as well, example for one field):
JSONObject obj = JSONFactoryUtil.createJSONObject(h.getSourceAsString());
TainingProvider t = JSONFactoryUtil.looseDeserialize(obj.getString("provider"), TainingProvider.class);
I cannot simply induce the Default constructor since it is generated by service builder nor I can do the "TainingProviderImpl.class" since it is different project but the Impl class should be what is called through the "TainingProvider.class" and it includes the default constructor.
Thank you.
The provided type when doing a deserialize is an interface in your example, so the internal Parser (here Jodd) might not find an implementation class to use as a bean class.
I did not find a nice solution, but used the internal Jodd parser directly.
When you subclass jodd.json.JsonParser you can overwrite the protected method for instantiation.
#Override
protected Object newObjectInstance(Class targetType) {
if (targetType.isAssignableFrom(TainingProvider.class)) {
return TainingProviderLocalServiceUtil.createTainingProvider(0L);
}
return super.newObjectInstance(targetType);
}
Now you can use the parser directly via parser.parse(obj.getString("provider"), TainingProvider.class)
I am not sure if it possible to hook in this instantiation hints to Liferays JSONFactoryUtil, which would be nicer instead of having a direct dependency to the jodd Parser in your module.

How do you bypass static method calls?

I have this line which is interferring in a unit test:
OtherClass.staticMethodThatWillErrorIfCalled().isAvailable();
If it wasn't static I could just mock OtherClass and then do this:
Mockito.doReturn(null).when(mockedOtherClass).staticMethodThatWillErrorIfCalled();
Mockito.doReturn(true).when(mockedOtherClass).isGuiMode();
and the fact that it will error if called makes my attempts at using powermockito futile.
I'm not sure how I can do this. All I want to do is skip over this line (it's an if check) and continue on as if it had returned true. What is the best way to do this?
I would require more info to give a more specific answer but this is what I am thinking...
First tell PowerMockito that you will be mocking a static method in OtherClass.
#RunWith(PowerMockRunner.class)
#PrepareForTest(OtherClass.class)
These are class level annotations that go on your unit testing class.
Then mock what to do when that method is called.
PowerMockito.mockStatic(OtherClass.class);
Mockito.when(OtherClass.isAvailable()).thenReturn(Boolean.TRUE);
Do this in your #Before method on your unit testing.

Mocking #UriInfo using EasyMock or PowerMock

I have a REST service class in which uriInfo object is automatically injected through #UriInfo annotation. Now, while writing JUnit for this class, I want to get a mock object created for this UriInfo object without introducing any new setter methods into the tested class just for the sake of setting the mocked UriInfo into it. Kindly let me know if you have any suggestions. We are using EasyMock and PowerMock.
You can use Powermock's Whitebox to modify the internal state of an object. One of the simplest invocations is:
Whitebox.setInternalState(tested, myMock);

How to test a void method with JMock

How to test a void method i.e. method that doesn't return anything in JMock?
To test a method that doesn't return anything, regardless of the testing or mocking framework you're using, you test the effect of a call to the method.
With JMock that likely means that you create a mock of something the code you're testing should call, set things up so that your mock is used instead of a real object, and set and verify expectations for calls to that mock.
I might be able to get more specific if you can add specifics to your question.
void methods generally make some changes in the value of the fields of the class. If the field of the class is not private then you can access it in your test class after calling the void method in your test method to assert if you are getting the expected value.