junit之记录执行的listener

  在junit 4中,有的时候可以在所有测试开始前,后,每个测试执行前,后进行监测,
需要继承的是RunListener类,例子如下,

首先是两个要测试的类,

public class TestFeatureOne {
	@Test
	public void testFirstFeature()
	{
		Assert.assertTrue(true);
	}
}


 
public class TestFeatureTwo {
	@Test
	public void testSecondFeature()
	{
		Assert.assertTrue(true);
	}

	@Test
	@Ignore
	public void testSecondFeatureIngored()
	{
		Assert.assertTrue(true);
	}


   然后写一个继承runlistner的类,如下:
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 testcases to execute : " + description.testCount());
	}

	/**
	 *  Called when all tests have finished
	 * */
	public void testRunFinished(Result result) throws java.lang.Exception
	{
		System.out.println("Number of testcases 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());
	}




public static void main(String[] args)
	{
		JUnitCore runner = new JUnitCore();
		//Adding listener here
		runner.addListener(new ExecutionListener());
		runner.run(TestFeatureOne.class, TestFeatureTwo.class);
	}




    分别是在所有的测试进行前,进行后,每个测试开始前,调用失败后,监视忽略调的测试调用的,所以结果为:
 
  
Number of testcases to execute : 3
Starting execution of test case : testFirstFeature
Finished execution of test case : testFirstFeature
Starting execution of test case : testSecondFeature
Finished execution of test case : testSecondFeature
Execution of test case ignored : testSecondFeatureIngored
Number of testcases executed : 2

你可能感兴趣的:(JUnit)