我在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"