Java JUnit代码中新运算符后的代码块
这是JUNIT4中包含的JUnit测试代码示例。它显示了两种情况:类型安全方式和动态方式。我试着用打字安全的方式Java JUnit代码中新运算符后的代码块,java,unit-testing,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 fValu
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(); }
}
);
- 新的Simple(“add”){…}是如何工作的?我的意思是,代码块如何跟随新操作符
- 为什么需要{…}块?我在没有它的情况下进行了尝试,没有出现编译/运行时错误
suite.addTest(
new SimpleTest("add") {
protected void runTest() { testAdd(); }
}
);
创建并将其作为参数传递给addTest方法。
您调用了以字符串为参数的SimpleTest构造函数,因此需要添加另一个构造函数。至于第3个问题,TestCase也没有参数构造函数,因此此代码在不添加其他构造函数的情况下是正确的:
suite.addTest(
new SimpleTest() {
protected void runTest() { testAdd(); }
}
);
我有一个创建和使用匿名内部类的简单示例。对我来说,
internal
有点误导,因为它似乎没有使用内部类,只是更改了一些方法操作
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");
}
});
}
}