[英]Verifiyng behavior of mock type without instance controlling
我正在为内部目的开发JUnit的自定义运行器,例如,我为测试方法引入了自定义批注,在应用该方法时,应使我的运行器在没有该批注的所有其他测试方法之后运行带有该批注的运行方法。
我想编写junit测试来验证我的自定义运行器的行为。
测试类别:
public class TestClass {
@Test
@CustomAnnotation
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
}
将测试我的跑步者的抽象代码:
public class MyCustomRunnerTest {
@Test
public void order() throws InitializationError {
// Arrange
// Some code of mocking library might be placed here
// Act
MyCustomRunner runner = new MyCustomRunner(TestClass.class);
runner.run(new RunNotifier());
// Assert
// Here I want to verify that method test1() has been called
// after method test2()
}
}
是否有任何模拟库可让我执行此类验证? 还是有其他方法可以检查?
为什么不将确定测试方法运行顺序的逻辑提取到单独的类或方法中? 此方法应按测试方法名称(或其他描述符)的运行顺序返回列表。 然后,您的测试将归结为将其传递给测试类,并断言输出为{“ test2”,“ test1”}。 无需嘲笑。
更好的解决方案
使用RunListener记录运行程序正在运行的测试方法。 当然,您将拥有自己的MyCustomRunner类,但是其余代码可以像下面的示例中所示:
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
@RunWith(BlockJUnit4ClassRunner.class)
public class RunnerTest {
// dummy "custom" test runner
public static class MyCustomRunner extends BlockJUnit4ClassRunner {
public MyCustomRunner(Class<?> klass) throws InitializationError {
super(klass);
}
}
public static class TestClass {
@Test
public void test1() {}
@Test
public void test2() {}
}
@Test
public void myCustomRunnerExecutesTestsInOrder() throws InitializationError {
RunNotifier notifier = new RunNotifier();
Collection<String> runTestMethods = new ArrayList<>();
notifier.addListener(new RunListener() {
@Override
public void testStarted(Description description) throws Exception {
runTestMethods.add(description.getMethodName());
}
});
new MyCustomRunner(TestClass.class).run(notifier);
// assert that the collection contains methods names in the specified order
assertThat(runTestMethods, contains("test1", "test2"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.