Home > Blockchain >  Mocking constructor using junit 5, mockito
Mocking constructor using junit 5, mockito

Time:06-16

How do I write junit 5/Mockito test case for this class.

public class ExternalApiClientHandler {

private final ExternalApiServiceHelper externalApiServiceHelper;

@Autowired
public ExternalApiClientHandler(String soapUrl) {
    ExternalApiServiceWsProxy externalApiServiceWsProxy = new ExternalApiServiceWsProxy(soapUrl);
    this.externalApiServiceHelper= new ExternalApiServiceHelper (externalApiServiceWsProxy );
}

public ExternalApiServiceHelper getExternalApiServiceHelper() {
    return externalApiServiceHelper;
}

}

I don't want to use PowerMock as no support for junit 5. How do I fit double constructors in my code using mockConstruction provided by Mockito? https://rieckpil.de/mock-java-constructors-and-their-object-creation-with-mockito/

class CheckoutServiceTest {
      @Test
      void mockObjectConstruction() {
        try (MockedConstruction<PaymentProcessor> mocked = Mockito.mockConstruction(PaymentProcessor.class,
          (mock, context) -> {
            // further stubbings ...
            when(mock.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
          })) {
    
          CheckoutService cut = new CheckoutService();
    
          BigDecimal result = cut.purchaseProduct("MacBook Pro", "42");
    
          assertEquals(BigDecimal.TEN, result);
        }
      }
    }

CodePudding user response:

@Test
public void testConstructor() {
    try (MockedConstruction mocked1 = mockConstruction(ExternalApiServiceWsProxy.class)) {
        try (MockedConstruction mocked2 = mockConstruction(ExternalApiServiceHelper.class)) {
            ExternalApiClientHandler  externalApiClientHandler = new ExternalApiClientHandler("localhost");
            assertNotNull(externalApiClientHandler.getExternalApiServiceHelper());
            assertEquals(1, mocked1.constructed().size());
            assertEquals(1, mocked2.constructed().size());
        }
    }
}

CodePudding user response:

Do not initialise in the constructor. Follow DI and inject the service instead. Read more about DI and writing testable code would help you to design it better.

  • Related