junit 4.10如何在测试开始运行之前打印测试用例名称..
所以我在这里打印" sampleTest"。
如何在junit 4.10中执行此操作?提前谢谢
class1:
TestSuite all = new TestSuite();
all.addTestSuite(class2);
all.run(result);
class2:
public class profileTest extends TestCase()
{
//I want to print the test cases name before the test actually starts executing
@Test
public void sampleTest1(){
//Some code here.
}
@Test
public void sampleTest2(){
//some more code here.
}
}
答案 0 :(得分:17)
借鉴Duncan's answer至问题Get name of currently executing test in JUnit 4
@Rule
public TestRule watcher = new TestWatcher() {
protected void starting(Description description) {
System.out.println("Starting test: " + description.getMethodName());
}
};
@Test
public void someTest() {
// do some testing
}
@Test
public void someOtherTest() {
// do some other testing
}
如果你在一个更大的项目中,你可以
您正在混合使用junit3和junit4样式。你无法扩展TestCase(junit3样式),然后尝试依赖注释驱动的junit4样式。在这里阅读如何使用junit4
创建测试套装底线是
extends TestCase
答案 1 :(得分:1)
你可以编写一个实现TestRules的类,并在其中定义测试规则,在每次测试之前和之后编写的内容(你还可以添加测量测试时间和其他东西),比如这个类:
package Test;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import org.junit.rules.ExternalResource;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class TestRulesSetter implements TestRule {
private OutputStream out = null;
private final TestCasePrinter printer = new TestCasePrinter();
private String beforeContent = null;
private String afterContent = null;
private long timeStart;
private long timeEnd;
public TestRulesSetter(OutputStream os) {
out = os;
}
private class TestCasePrinter extends ExternalResource {
@Override
protected void before() throws Throwable {
timeStart = System.currentTimeMillis();
out.write(beforeContent.getBytes());
};
@Override
protected void after() {
try {
timeEnd = System.currentTimeMillis();
double seconds = (timeEnd-timeStart)/1000.0;
out.write((afterContent+"Time elapsed: "+new DecimalFormat("0.000").format(seconds)+" sec\n").getBytes());
} catch (IOException ioe) { /* ignore */
}
};
}
public final Statement apply(Statement statement, Description description) {
beforeContent = "\n[TEST START] "+description.getMethodName()+"\n"; // description.getClassName() to get class name
afterContent = "[TEST ENDED] ";
return printer.apply(statement, description);
}
}
然后在您的测试用例中,您可以添加该测试规则setter的实例,并使用注释@Rule将System.out传递给它,如下所示:
package Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
public class rsdg {
@Rule
public TestRulesSetter pr = new TestRulesSetter(System.out);
@Test
public void test1() {
}
@Test
public void test2() {
}
@Test
public void test3() {
}
}
这种方式可以让您对格式化测试的方式进行大量控制
答案 2 :(得分:0)
String name = new Object(){}.getClass().getEnclosingMethod().getName();
答案 3 :(得分:0)
我将测试套件转换为junit4,@ Rule为我工作 删除了“扩展TestCase”
suite.addTest(new JUnit4TestAdapter(Test1.class));