0

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248

1 Answers1

1

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!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thank you for the answer but I cannot change the code now. I understand idea of factory and dependency injection through the constructor. Also, I have @PrepareForTest annotation... Still, doesn't work. – Łukasz Bocheński Jun 29 '17 at 08:25
  • 1
    Well, then that very first link should most likely do the job. Mocking new is well documented, and it works well - when you follow the documentation exactly. If you think you are; and it is still not working, we need a [mcve]. Your input is not sufficient; as it is **not** showing how you use that very annotation for example. – GhostCat Jun 29 '17 at 08:26