JUnit RunListener 示例
JUnit 测试类
我们在下面编写两个测试类仅作为示例。
我们将监视为在这些类中编写的测试而打印的日志。
package com.onitroad.junit; import junit.framework.Assert; import org.junit.Test; public class TestFeatureOne { @Test public void testFirstFeature() { Assert.assertTrue(true); } }
package com.onitroad.junit; import junit.framework.Assert; import org.junit.Ignore; import org.junit.Test; public class TestFeatureTwo { @Test public void testSecondFeature() { Assert.assertTrue(true); } @Test @Ignore public void testSecondFeatureIngored() { Assert.assertTrue(true); } }
JUnit 测试监听器
下面这个监听器将扩展 JUnit 提供的 RunListener 类。
我们可以自由地覆盖任意数量的方法 RunListener 类,从不包含任何方法。
package com.onitroad.junit.suite; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; public class ExecutionListener extends RunListener { /** * Called before any tests have been run. * */ public void testRunStarted(Description description) throws java.lang.Exception { System.out.println("Number of tests to execute : " + description.testCount()); } /** * Called when all tests have finished * */ public void testRunFinished(Result result) throws java.lang.Exception { System.out.println("Number of tests executed : " + result.getRunCount()); } /** * Called when an atomic test is about to be started. * */ public void testStarted(Description description) throws java.lang.Exception { System.out.println("Starting execution of test case : "+ description.getMethodName()); } /** * Called when an atomic test has finished, whether the test succeeds or fails. * */ public void testFinished(Description description) throws java.lang.Exception { System.out.println("Finished execution of test case : "+ description.getMethodName()); } /** * Called when an atomic test fails. * */ public void testFailure(Failure failure) throws java.lang.Exception { System.out.println("Execution of test case failed : "+ failure.getMessage()); } /** * Called when a test will not be run, generally because a test method is annotated with Ignore. * */ public void testIgnored(Description description) throws java.lang.Exception { System.out.println("Execution of test case ignored : "+ description.getMethodName()); } }
JUnit 还支持在通过 RunListener 类执行测试时添加侦听器。
此侦听器可用于从改进日志记录到测试特定逻辑的各种目的。
www. On IT Road .com
执行JUnit 监听器
现在,让我们运行测试并观察监听器输出。
package com.onitroad.junit.suite; import org.junit.runner.JUnitCore; import com.onitroad.junit.TestFeatureOne; import com.onitroad.junit.TestFeatureTwo; public class ExecuteWithRunListener { public static void main(String[] args) { JUnitCore runner = new JUnitCore(); //Adding listener here runner.addListener(new ExecutionListener()); runner.run(TestFeatureOne.class, TestFeatureTwo.class); } }
日期:2020-09-17 00:09:52 来源:oir作者:oir