我在使用 Java 中的 ErrorCollectors 时遇到了一些问题。
我有一些代码,正在比较两个值。如果值匹配,则结果为通过。如果值不匹配,则失败。听起来很简单。所以我创建了一个基本的测试用例:
public class CB_Test {
@Rule
public ErrorCollector collector = new ErrorCollector();
@Before
public void setUp() {
//steps = new WebDriverSteps(new FirefoxDriver());
//steps = new WebDriverSteps();
}
@Test
public void testme() {
String checkMe;
String value;
checkMe = "1234";
value = "2234";
System.out.println("value coming in : " + value);
System.out.println("value to check : " + checkMe);
collector.checkThat("Check values match", value, is(checkMe));
}
}
其行为完全符合我的预期。然而我想让这段代码能够从其他地方调用。所以我创建了这样的“主”文件:
public class ABC_Test {
@Before
public void setUp() {
//steps = new WebDriverSteps(new FirefoxDriver());
//steps = new WebDriverSteps();
}
@Test
public void check() {
CheckVal dv = new CheckVal();
try {
dv.checkTable("4234");
} catch (AssertionError er) {
System.out.println("22");
} catch (Exception e) {
System.out.println("23");
} catch (Throwable t) {
System.out.println("24");
}
}
}
并将代码移至:
public class CheckVal {
@Rule
public ErrorCollector collector = new ErrorCollector();
public void checkTable(String value) {
String checkMe;
checkMe = "1234";
System.out.println("value coming in : " + value);
System.out.println("value to check : " + checkMe);
collector.checkThat("Check values match", value, is(checkMe));
}
}
但是现在,当我运行代码时,即使我引入一个值导致生成失败,我也总是获得通过。我看不出我在这里做错了什么。 (我知道代码很困惑 - 这只是我尝试将事情分解为最简单的方法来尝试查看我的问题。)
最佳答案
@Rule
不包含在由测试运行程序运行并处理所有注释的测试类中。您的代码此时只是代码。
您需要更改代码以将 @Rule
移动到被测试的类,以便处理注释:
import org.junit.*;
import org.junit.rules.ErrorCollector;
public class ABC_Test {
@Rule
public ErrorCollector collector = new ErrorCollector();
@Before
public void setUp() {
//steps = new WebDriverSteps(new FirefoxDriver());
//steps = new WebDriverSteps();
}
@Test
public void check() {
CheckVal dv = new CheckVal(collector);
try {
dv.checkTable("4234");
} catch (AssertionError er) {
System.out.println("22");
} catch (Exception e) {
System.out.println("23");
} catch (Throwable t) {
System.out.println("24");
}
}
}
然后修改可重用类以接受 ErrorCollector
并正常处理:
import org.junit.*;
import org.junit.rules.ErrorCollector;
import org.hamcrest.CoreMatchers;
public class CheckVal {
public ErrorCollector collector = null;
public CheckVal(ErrorCollector collector) {
this.collector = collector;
}
public void checkTable(String value) {
String checkMe;
checkMe = "1234";
System.out.println("value coming in : " + value);
System.out.println("value to check : " + checkMe);
collector.checkThat("Check values match", value, CoreMatchers.is(checkMe));
}
}
IntelliJ(或您的测试运行程序)然后按预期报告错误:
java.lang.AssertionError: Check values match
Expected: is "1234"
but: was "4234"
关于java - JUnit + Java + ErrorCollector 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207398/