Reputation: 31
I'm trying to test methods inside my controller and one of the classes have creation of the object inside it like this:
NewPaymentModel pModel = new NewPaymentModel();
Then I have if statement:
if (pModel.getErrors().isEmpty()) {
This is exactly what I want to mock. My code is below:
Pr4Error error = Mockito.mock(Pr4Error.class);
List<Pr4Error> listOfErrors = new ArrayList<>();
listOfErrors.add(error);
final NewPaymentModel pModel =
PowerMockito.mock(NewPaymentModel.class, Mockito.RETURNS_DEEP_STUBS);
PowerMockito.whenNew(NewPaymentModel.class).withNoArguments().
thenReturn(pModel);
Mockito.doReturn(pModel).when(facade).addNewPayment(pModel);
when(pModel.getErrors().isEmpty()).thenReturn(true);
EDIT. What I got when run unit tests is nullpointerexception on last line of code.
Upvotes: 0
Views: 5397
Reputation: 140623
The direct answer has already been given here. Basically there are various pre-requisites that your code has to conform to; for example you need to use the @PrepareForTest annotation (so that the power magic can kick in to manipulate byte code of your production classes).
The real answer is: when you are writing your own code, then simply write easy to test code. Start here. Meaning: instead of calling new
within your production code, you could for example dependency-inject a factory for such objects. And that factory can be mocked the "normal" way. And your need to mock new
vanishes; you can get rid of PowerMock(ito) ... and end up with better designed production code!
Upvotes: 1