我正在尝试测试以下类:
package com.myclass;
public class MyClass {
private Map<String, String> dataMap = new HashMap<>();
public void extractInfoFromLine(String line) throws InvalidInputException {
String[] words = line.split(" ");
if (dataMap.containsKey(words[0])) {
throw new InvalidInputException();
}
dataMap.put(words[0], words[2]);
}
public void confirmInfoPresent(String name) {
// Do something
}
}
使用此TestNG类:
package com.myclass;
public class MyClassTest {
private MyClass myClass;
@DataProvider(name = "invalid-data-provider")
public Object[][] invalidDataProvider() {
return new Object[][] {
{ "A is B", "A"},
{ "A is D", "A"},
};
}
@BeforeTest()
public void setup() {
myClass = new MyClass();
}
@Test(dataProvider = "invalid-data-provider", expectedExceptions = InvalidInputException.class)
public void testExceptionalExtractValueForKey(String line, String name) throws InvalidInputException {
myClass.extractInfoFromLine(line);
myClass.confirmInfoPresent(name);
}
}
我为此定义了以下自定义异常:
package com.myclass;
public class InvalidInputException extends Exception {
public InvalidInputException() {
super();
}
public InvalidInputException(String message) {
super(message);
}
public InvalidInputException(String message, Throwable cause) {
super(message, cause);
}
public InvalidInputException(Throwable cause) {
super(cause);
}
}
但是,当我运行此测试用例时,我收到以下错误:
Expected exception com.myclass.InvalidInputException but got org.testng.TestException:
Method MyClassTest.testExceptionalExtractValueForKey(java.lang.String, java.lang.String)[pri:0, instance:com.myclass.MyClassTest@3930015a] should have thrown an exception of class com.myclass.InvalidInputException
我尝试用标准异常替换我的自定义异常,但结果仍然相同。
有人可以帮帮我吗?
答案 0 :(得分:0)
dataMap.containsKey(words[0]) == false
),因此,“if”语句体内的代码将不会被执行;这意味着您的异常不会被抛出。
由于在@Test注释中设置了“expectedExceptions”属性,TestNg将威胁测试失败。第二次测试迭代将通过,因为dataMap不再为空(dataMap.put(words[0], words[2]
) - 您在第一次运行时添加了数据)。
TestNg doc再次说明了“expectedExceptions”:预期测试方法抛出的异常列表。如果抛出此列表中没有异常或不同的异常,则此测试将标记为失败。