需要帮助才能理解JUnit RunListener

时间:2015-07-22 19:20:24

标签: java junit

请耐心等待,这将是漫长的。 我写了以下TestRunner.java

import java.util.ArrayList;
import java.util.List;
import org.junit.runner.JUnitCore;
import org.junit.runner.notification.RunListener;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

class TestRunner {
  public static void main (String args[]) {
    List<Class<?>> classes = new ArrayList<Class<?>>();
    for (String each : args) {
      try {
        classes.add(Class.forName(each));
      } catch (ClassNotFoundException e) {
        System.out.println("Class Not found");
      }
    }

   JUnitCore core = new JUnitCore();
   RunListener listener = new MyListener();
   core.addListener(listener);
   core.run(classes.toArray(new Class[0]));   
  }
}

class MyListener extends RunListener {
  public void testRunStarted(Description description) throws Exception {
    System.out.println("Number of tests to execute: " + description.testCount());
  }

  public void testRunFinished(Result result) throws Exception {
    System.out.println("Number of tests executed: " + result.getRunCount());
  }

  public void testStarted(Description description) throws Exception {
    System.out.println("Starting: " + description.getMethodName());
  }

  public void testFinished(Description description) throws Exception {
    System.out.println("Finished: " + description.getMethodName());
  }

  public void testFailure(Failure failure) throws Exception {
    System.out.println("Failed: " + failure.getDescription().getMethodName());
  }

  public void testAssumptionFailure(Failure failure) {
    System.out.println("Failed: " + failure.getDescription().getMethodName());
  }

  public void testIgnored(Description description) throws Exception {
    System.out.println("Ignored: " + description.getMethodName());
  }
}

我有Abc.java

class Abc {
  public int add(int a, int b) {
    return a + b;
  }
}

我有AbcTest.java

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class AbcTest {
  @Test 
  public void testAdd() {
    System.out.println("add");
    int a = 0;
    int b = 0;
    Abc instance = new Abc();
    int expResult = 0;
    int result = instance.add(a, b);
    assertEquals(expResult, result);
  }
}

我正在使用命令

运行测试
java -cp .:/path/to/junit4.jar TestRunner AbcTest

我看到的输出是

Number of tests to execute: 1
Starting: testAdd
add **<- This is my problem**
Finished: testAdd
Number of tests executed: 1

我想知道为什么当我完全构建自己的RunListner类时,JUnit仍在打印第3行?并且,我如何通过JUnit的defult打印语句?

1 个答案:

答案 0 :(得分:5)

JUnit没有打印第3行,你是。它在你的测试代码中:

 @Test 
 public void testAdd() {
     System.out.println("add");