JUnit:测试java反射异常



我有一个类MyTransformFunctions,有反射方法(名称:transform)像这样:

public class MyTransformFunctions
{
Logger LOG = Logger.getLogger( MyTransformFunctions.class );
public MyRecord transform( String functionName, MyRecord argRecord, String argFieldToProcess )
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,Exception
{
    try
    {
        Method method = this.getClass().getDeclaredMethod( functionName, argRecord.getClass(), argFieldToProcess.getClass() );
        argRecord = (MyRecord) method.invoke( this, argRecord, argFieldToProcess );
    }
    catch ( NoSuchMethodException e )
    {
        LOG.error( "[ Method not found exception] : Method name '" + functionName + "'" + " field name: '" + argFieldToProcess
                + "' " + e );
        throw e;
    }
    catch ( java.lang.IllegalAccessException e )
    {
        LOG.error( "[ Illegal Access exception] : Method name '" + functionName + "'" + " field name: '" + argFieldToProcess
                + "' " + e );
        throw e;
    }
    catch ( java.lang.reflect.InvocationTargetException e )
    {
        LOG.error( e.getCause().getMessage() + "[ Invocation Target not found exception] : Method name '" + functionName + "'"
                + " field name: '"
                + argFieldToProcess
                + "' " + e );
        throw e;
    }
    catch ( Exception e )
    {
        LOG.error( e.getCause().getMessage() + "[ Transformer function exception ] : Method name '" + functionName + "'"
                + " field name: '"
                + argFieldToProcess
                + "' " + e );
        throw e;
    }

    return argRecord;
}
public MyFuction( MyRecord record, String fieldNameToProcess )
{
    LOG.debug( "convert2GoogleDate function called" );
    return record;
}
}

我正试图编写junit测试来检查从转换方法抛出的个别异常并获得编译错误。我的测试看起来像:

@Test(expected = NoSuchMethodException.class)
public void testFailedGetMethod() throws NoSuchMethodException
{
    MyRecord record = new MyRecord();
    transformer.transform( "junk", record, "junk" );
}

我在编译过程中得到"未处理的异常"。

任何建议吗?

谢谢

您的transform方法抛出的不仅仅是NoSuchMethodException。它还抛出IllegalAccessExceptionInvocationTargetExceptionException

此编译错误与JUnit无关,而是与声明由transform抛出的那些异常未被您的测试方法捕获这一事实有关。因为Exception是这里所有抛出异常的超类,您可以通过声明您的测试方法来抛出Exception来快速修复这个问题。

public void testFailedGetMethod() throws Exception

这将使它编译。然而,仅仅扔一个Exception不是一个好的做法。最好使用Exception的特定子类,有时这会导致您创建自己的Exception子类来表示这种异常情况,例如

public void testFailedGetMethod() throws NoSuchMethodException,
    IllegalAccessException, InvocationTargetException, SomeOtherException

相关内容

  • 没有找到相关文章

最新更新