简体   繁体   中英

Mocking creation of object inside other class

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM