使用JUnit捕获自定义异常

时间:2016-03-15 17:31:33

标签: java junit

我正在为我尝试捕获JUnit的方法编写exception测试用例,但由于某种原因,我的测试没有达到异常。方法很长但我只需要捕获if块中的异常。

待测方法:

public void createClient() throws EISClientException {
    if( client == null ) {
        ClientConfig c = new ClientConfig();

        //Add Glocal JSON/Jackson Provider
        c.register( JacksonFeature.class );

        if ( isDisableSslValidation() ) {  
            try {
                client = ClientBuilder.newBuilder().sslContext( SslUtil.createGullibleSslContext() )
                            .hostnameVerifier( SslUtil.gullibleVerifier ).withConfig( c ).build();
            } catch( Exception e ) {
                throw new EISClientException( e );
            }
        } else {
            client = ClientBuilder.newBuilder().withConfig( c ).build();
        }

        //Add Client Properties
        if( clientProperties.size() > 0 ) {
            for( String key : clientProperties.keySet() ) {
                client.property( key, clientProperties.get( key ) );
            }
        }

        //Add Client Filters
        if( clientFilters != null && clientFilters.size() > 0 ) {
            for( IClientFilter cf : clientFilters ) {
                client.register( cf.getFilter() );
            }
        }

    }
}

JUnit测试:

@Test
public void testCreateClientException() throws Exception {
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    Client client = mock(Client.class);

    boolean caughtException = false;
    try {
        clientConfiguration.setDisableSslValidation(true);
        client = ClientBuilder.newBuilder().build();
        clientConfiguration.createClient();

    } catch (EISClientException ex) {
        caughtException = true;
    }
    assertTrue(caughtException);
}

看起来如果客户端没有构建,那么抛出exception但如果我在任何方法中传递null作为参数,我肯定得到NullPointerException

任何帮助都将不胜感激。

由于

2 个答案:

答案 0 :(得分:0)

在执行测试之前,您正在设置模拟客户端。在您正在测试的方法中,它启动if (client == null)我认为这是评估为false并且方法中没有处理任何内容

答案 1 :(得分:0)

实际上,在JUnit中有一种更简洁的方法来验证抛出的异常:

@Test(expected=EISClientException.class)
public void testCreateClientException() throws Exception {
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    Client client = mock(Client.class);
    clientConfiguration.setDisableSslValidation(true);
    client = ClientBuilder.newBuilder().build();
    clientConfiguration.createClient();
}

此测试只有在抛出异常时才会成功(我知道这不能直接回答你的问题)