Org.testng.testngexception: sun.security.provider.certpath.suncertpathbuilderexception: unable to find valid certification path to requested target

The org.testng.testngexception indicates that there is an exception occurring in the TestNG framework. In this case, the specific exception is sun.security.provider.certpath.suncertpathbuilderexception, which means that TestNG is unable to find a valid certification path to the requested target.

This exception usually occurs when TestNG is attempting to establish a secure connection (e.g., HTTPS) to a server but is unable to validate the server’s SSL certificate. The SSL certificate is used to verify the authenticity and integrity of the server.

When TestNG encounters this exception, it means that the server’s SSL certificate cannot be verified using the truststore on the client side. The truststore contains certificates from trusted Certificate Authorities that TestNG can use to validate the server’s certificate.

To resolve this issue, you can try one of the following solutions:

  1. Add the server’s SSL certificate to the truststore:
    This involves obtaining the server’s SSL certificate and adding it to the truststore that TestNG uses. You can do this using the keytool command-line utility provided by Java. Here’s an example:

            keytool -import -alias myserver -keystore truststore.jks -file server.cer
          

    This command imports the server’s SSL certificate (contained in the file server.cer) into the truststore named truststore.jks with the alias myserver.

  2. Disable SSL certificate validation:
    By default, TestNG performs SSL certificate validation. However, you can disable this validation if you trust the server and are willing to accept any certificate presented by it. To disable SSL certificate validation, you can implement a custom X509TrustManager that accepts all certificates. Here’s an example:

            import javax.net.ssl.X509TrustManager;
            import java.security.cert.CertificateException;
            import java.security.cert.X509Certificate;
    
            public class TrustAllCertificates implements X509TrustManager {
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
    
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
    
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }
          

    You can then set this custom X509TrustManager before making any connections:

            TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCertificates() };
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
          

Read more interesting post

Leave a comment