2012-03-22 76 views
0

编辑:我想写一个失败的测试用例不是积极的。如何测试illegalaccessException?

我正在为我的Java代码编写测试用例。如何为使用反射API的方法编写测试用例。由此产生的代码给我IllegalAccessException。如何在我的JUnit测试用例中创建一个场景,以便我可以测试异常。

public double convertTo(String currency, int amount) { 
    Class parameters[] = {String.class, int.class}; 
    try { 
     Method classMethod = clazz.getMethod("convertTo", parameters); 
     return ((Double) classMethod.invoke(exhangeObject, new Object[]{currency, amount})).doubleValue(); 
    } catch (NoSuchMethodException e) { 
     throw new CurrencyConverterException(); 
    } catch (InvocationTargetException e) { 
     throw new CurrencyConverterException(); 
    } catch (IllegalAccessException e) { 
     System.out.println(e.getClass()); 
     throw new CurrencyConverterException(); 
    } 
} 

感谢, 斯利拉姆

回答

4

由于反射测试方法的实现细节,你并不需要特别照顾它。为了测试这种方法,简单地做:

@Test 
public void shouldNotThrowException() throws Exception { 
    testSubject.convertTo("JPY", 100); 
} 

如果有CurrencyConverterException抛出,测试将失败。

,或者更明确地:

@Test 
public void shouldNotThrowException() { 
    try { 
     testSubject.convertTo("JPY", 100); 
    } catch(CurrencyConverterException e) { 
     fail(e.getMessage()); 
    } 
} 

注意,当你捕捉异常并抛出一个新的你应该总是链的新原始异常。例如:

} catch (IllegalAccessException e) { 
    throw new CurrencyConverterException(e); 
} 

编辑:您是否在寻找这种模式呢?如何确保引发异常。两种型号:

// will pass only if the exception is thrown 
@Test(expected = CurrencyConverterException.class) 
public void shouldThrowException() { 
    testSubject.doIt(); 
} 

@Test 
public void shouldThrowException() { 
    try { 
     testSubject.doIt(); 
     fail("CurrencyConverterException not thrown"); 
    } catch (CurrencyConverterException e) { 
     // expected 
     // use this variant if you want to make assertions on the exception, e.g. 
     assertTrue(e.getCause() instanceof IllegalAccessException); 
    } 
} 
+0

不,我想要写一个失败的测试情况。不是积极的。 – sriram 2012-03-22 23:33:42

+0

查看我的更新回答。 – Synesso 2012-03-22 23:56:42

+0

第二个。 shouldThrowException – sriram 2012-03-23 00:01:27