Mockito not working for inner method variable of HttpURLConnection

this is the method for which junit is written

public boolean isSelfServicePortalServerAvailable(String crmEndPoint) {
        boolean isServerAvailable = false;
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(crmEndPoint);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            isServerAvailable = true;
            connection.disconnect();
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return isServerAvailable;
    }

This is the test case wriiten

@Mock
private URL mockUrl;

@Mock
private HttpURLConnection mockConnection;

@Mock
private ISelfServiceDao selfServiceDao;

@Mock
private RestTemplate restTemplate;

@InjectMocks
private SelfServiceCoreClaimImpl selfServiceCoreClaimImpl = new SelfServiceCoreClaimImpl(restTemplate);



@Test
public void testIsSelfServicePortalServerAvailable_Success() throws IOException {
    
    when(mockUrl.openConnection()).thenReturn(mockConnection);
    doNothing().when(mockConnection).connect();
    doNothing().when(mockConnection).disconnect();

    boolean result = selfServiceCoreClaimImpl.isSelfServicePortalServerAvailable("http://test-url.com");
    assertTrue(result);
}

errors org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):

  1. -> at com.acentra.ssp.impl.SelfServiceCoreClaimImplTest.testIsSelfServicePortalServerAvailable_Success(SelfServiceCoreClaimImplTest.java:71)
  2. -> at com.acentra.ssp.impl.SelfServiceCoreClaimImplTest.testIsSelfServicePortalServerAvailable_Success(SelfServiceCoreClaimImplTest.java:72)
  3. -> at com.impl.SelfServiceCoreClaimImplTest.testIsSelfServicePortalServerAvailable_Success(SelfServiceCoreClaimImplTest.java:73)
    Please remove unnecessary stubbings More info: javadoc for UnnecessaryStubbingException class.
    at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:192)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)

Not calling mock … can someone help me on this

I would try:

    public boolean isSelfServicePortalServerAvailable(String crmEndPoint) {
        boolean isServerAvailable = false;
        try {
            HttpURLConnection connection = getHttpURLConnection(crmEndPoint);
            connection.connect();
            isServerAvailable = true;
            connection.disconnect();
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return isServerAvailable;
    }

    private HttpURLConnection getHttpURLConnection(String crmEndPoint) throws IOException {
        URL url = new URL(crmEndPoint);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        return connection;
    }

And then test

    @Mock
    private HttpURLConnection mockConnection;

    @Mock
    private ISelfServiceDao selfServiceDao;

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    @Spy
    private SelfServiceCoreClaimImpl selfServiceCoreClaimImpl;



    @Test
    public void testIsSelfServicePortalServerAvailable_Success() throws IOException {
        String crmEndPoint = "http://test-url.com";
        doReturn(mockConnection).when(selfServiceCoreClaimImpl).getHttpURLConnection(crmEndPoint);
        doNothing().when(mockConnection).connect();
        doNothing().when(mockConnection).disconnect();

        boolean result = selfServiceCoreClaimImpl.isSelfServicePortalServerAvailable(crmEndPoint);
        assertTrue(result);
    }

You can’t just inject mock for objects that are created inside the method (like the new URL(crmEndPoint);).

The @InjectMocks will automatically inject the mocks inside private fields, or setters or constructor parameters.

If an object is created inside a method then you have to consider the following:

  1. Is this object a stateless? Then I have to receive it from the constructor or DI system and then mock it. So I have to refactor the method and remove the creation of the new object.
  2. Is this object a DTO? Then I don’t need to mock it.
  3. If none of the above, which means the object creation can’t be avoided, (probably your case as I can tell) then you have to use the MockedConstruction.
    Also for the mocked construction to work you will need the following dependency in Maven:
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>some version here</version>
    <scope>test</scope>
</dependency>

I’ve done few tweaking in your junit, and it runs perfectly fine.

    @Test
    public void testIsSelfServicePortalServerAvailable_Success() throws IOException {
        HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class);
        URL mockUrl = Mockito.mock(URL.class);
        SelfServiceCoreClaimImpl selfServiceCoreClaimImpl= new SelfServiceCoreClaimImpl();
        Mockito.doReturn(mockConnection).when(mockUrl).openConnection();
        Mockito.doNothing().when(mockConnection).connect();
        Mockito.doNothing().when(mockConnection).disconnect();

        boolean result = selfServiceCoreClaimImpl.isSelfServicePortalServerAvailable("http://test-url.com");
        assertTrue(result);
    }

7

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật