Java JUnit代码中new运算符之后的代码块

时间:2012-10-24 20:43:29

标签: java unit-testing

这是JUNIT4中包含的示例JUnit测试代码。它显示了两种情况:类型安全方式和动态方式。我试着使用类型安全的方式。

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Some simple tests.
 */
public class SimpleTest extends TestCase {
    protected int fValue1;
    protected int fValue2;

    SimpleTest(String string)
    {
        super(string);
    }

    @Override
    protected void setUp() {
        fValue1 = 2;
        fValue2 = 3;
    }

    public static Test suite() {

          /*
           * the type safe way
           */
          TestSuite suite= new TestSuite();
          suite.addTest(
              new SimpleTest("add") {
                   protected void runTest() { testAdd(); }
              }
          );

          suite.addTest(
              new SimpleTest("testDivideByZero") {
                   protected void runTest() { testDivideByZero(); }
              }
          );
          return suite;
    }

    ...

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }
}

我不确定这段代码。

suite.addTest(
    new SimpleTest("add") {
        protected void runTest() { testAdd(); }
        }
    );
  • 新的简单(“添加”){...}如何运作?我的意思是,代码块如何跟随新运算符?
  • 为什么需要阻止{...}?我试过没有它,我没有编译/运行时错误。

2 个答案:

答案 0 :(得分:2)

在这个片段中:

suite.addTest(
    new SimpleTest("add") {
        protected void runTest() { testAdd(); }
    }
);

创建anonymous inner class并将其作为参数传递给addTest方法。 你调用了SimpleTest构造函数,它将String作为参数,因此你需要添加另一个构造函数。至于Q3问题,TestCase也有no-arg构造函数,所以这段代码是正确的而不添加额外的构造函数:

suite.addTest(
    new SimpleTest() {
        protected void runTest() { testAdd(); }
    }
);

答案 1 :(得分:0)

我有一个创建和使用匿名内部类的简单示例。对我来说Inner有点误导,因为它似乎没有使用内部类,只是改变了一些方法动作。

class Ferrari {
    public void drive() {
        System.out.println("Ferrari");
    }
}

// Example 1: You can modify the methods of an object.
class Car {
    Ferrari p = new Ferrari() {
        public void drive() {
            System.out.println("anonymous Ferrari");
        }
    };
}

class AnonymousAgain {
    public void hello(Ferrari car) {
        car.drive();
    }

    public static void main(String[] args) {
        AnonymousAgain a = new AnonymousAgain();
        // Example 2
        a.hello(new Ferrari() {
            public void drive() {
                System.out.println("The power of inner");
            }
        });
    }
}