简体   繁体   中英

Mocking constructor using junit 5, mockito

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);
        }
      }
    }
@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());
        }
    }
}

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.

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