简体   繁体   中英

How to throw exception in JUnit Test for SSLContextBuilder.create().loadTrustMaterial?

I have tried to write junit tests for the following piece of code but was unable to throw the exception in the test case. The following is the implementation:

public static HttpClientBuilder createTrustAllHttpClientBuilder() {
    try {
        SSLContext sslContext = SSLContextBuilder
                    .create()
                    .loadTrustMaterial(null, (certificate, authType) -> true) <= How to throw exception for this line
                    .build();
    }
    catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException(e);
    }
}

The following is my junit Test:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SSLContextBuilder.class})
public class testClass {

     public void testCase() {
           SSLContextBuilder sslContextBuilder = mock(SSLContextBuilder.class, RETURNS_DEEP_STUBS);
           PowerMockito.mockStatic(SSLContextBuilder.class);
           PowerMockito.when(SSLContextBuilder.create()).thenReturn(sslContextBuilder);
           PowerMockito.when(sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true)).thenThrow(new NoSuchAlgorithmException());
     }
}

I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!

Because you already have a mock, you can use thenThrow instead of thenReturn to have your mock throw the exception.

https://static.javadoc.io/org.mockito/mockito-core/2.2.9/org/mockito/stubbing/OngoingStubbing.html

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