Mock a static method and throw exception

860 Views Asked by At

Below is the class. I am trying to mock the static class and throw UrlParsingException.

public class TrustSetup 
{
    private TrustSetup(){

    }
    public static SSLSocketFactory configureCustomTrustManager() throws 
      UrlParsingException, OAuthException {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.XXXXCertificate[] getAcceptedIssuers() {
                    return new XXXXCertificate[0];
                }

                public void checkClientTrusted(
                        java.security.cert.XXXXCertificate[] certs, String authType) throws CertificateException {
                }

                public void checkServerTrusted(
                        java.security.cert.XXXXCertificate[] certs, String authType) throws CertificateException {
                }
            }
        };

        SSLContext sc;
        try {
            sc = SSLContext.getInstance("XXXXXX");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new UrlParsingException(e.getMessage());
        } catch (Exception e) {
            throw new OAuthException(e.getMessage());
        }
        return sc.getSocketFactory();
    }
}

Below is the test class for static class.

@RunWith(PowerMockRunner.class)
@PrepareForTest(TrustSetup.class)
public class UrlExceptionTest {

    @Mock
    private SSLContext context;

    @Test(expected = UrlParsingException.class)

    void URLParsingExceptionWithExceptionTest() throws 
        NoSuchAlgorithmException,UrlParsingException,OAuthException {
        PowerMockito.mockStatic(TrustManagerSetup.class);
        Mockito.when(context.getInstance("XXXXXX")).thenReturn(context);
        TrustManagerSetup.configureCustomTrustManager();
}

Error: "No tests were executed!". Objective is to mock and throw UrlParsingException.

0

There are 0 best solutions below