做了个简单的单元测试框架,只算个毛坯,遇到一些问题。
1、由于没有完整的堆栈跟踪,所以无法打印出断言失败的行号。
2、无法获得行号,成功、失败或异常都需要显示这个。
3、由于unittest关键字后面的块是一个函数,所以把这个单元测试放在里面时,成了内嵌类,这时D禁止调用static ctor。当然这不算是个大问题。
只做了简单输出,没什么实际用途。代码如下:
输出:
setUp
runTest: testFoo
in unittest.MathTest.testFoo assertEqual(1, 1), result: true
in unittest.MathTest.testFoo assertNotEqual(1, 0), result: true
runTest: testBar
in unittest.MathTest.testBar assertEqual(1, 0), result: false
in unittest.MathTest.testBar assertNotEqual(1, 1), result: false
tearDown
1、由于没有完整的堆栈跟踪,所以无法打印出断言失败的行号。
2、无法获得行号,成功、失败或异常都需要显示这个。
3、由于unittest关键字后面的块是一个函数,所以把这个单元测试放在里面时,成了内嵌类,这时D禁止调用static ctor。当然这不算是个大问题。
只做了简单输出,没什么实际用途。代码如下:
class TestCase
{
public
template TestCases(Methods ...)
{
static this()
{
typeof(this) instance = new typeof(this);
instance.setUp();
instance.beginTest((typeof(this)).classinfo.name);
mixin (_TestCases!(Methods));
instance.endTest();
instance.tearDown();
}
}
protected:
void setUp(){}
void tearDown(){}
void beginTest(char[] classname)
{
this.classname = classname;
}
void endTest()
{
}
void assertEqual(T,U)(T t, U u)
{
bool pass = (t == u);
addTestResult(classname, methodname, pass, std.string.format("assertEqual(", t, ", ", u, ")"));
}
void assertNotEqual(T,U)(T t, U u)
{
bool pass = (t != u);
addTestResult(classname, methodname, pass, std.string.format("assertNotEqual(", t, ", ", u, ")"));
}
private:
void beginMethodTest(char[] methodname)
{
this.methodname = methodname;
}
void endMethodTest()
{
}
void runTest(lazy void dg)
{
writefln("runTest: " ~ methodname);
try
{
dg();
}
catch(Exception ex)
{
addTestException(classname, methodname, ex);
}
}
void addTestResult(char[] classname, char[] methodname, bool pass, char[] info)
{
writefln("in ", classname, ".", methodname, " ", info, ", result: ", pass);
}
void addTestException(char[] classname, char[] methodname, Exception ex)
{
writefln("in ", classname, ".", methodname, " ", ex);
}
template _TestCases(Methods ...)
{
static if (Methods.length > 0)
{
const char[] _TestCases =
"instance.beginMethodTest(\"" ~ Methods[0] ~ "\");\n" ~
"instance.runTest(instance." ~ Methods[0] ~ "());\n" ~
"instance.endMethodTest();\n" ~
_TestCases!(Methods[1..$]);
}
else
{
const char[] _TestCases = "";
}
}
char[] classname;
char[] methodname;
}
import std.stdio;
class MathTest : TestCase
{
mixin TestCases!(
"testFoo",
"testBar"
);
void setUp()
{
writefln("setUp");
}
void tearDown()
{
writefln("tearDown");
}
void testFoo()
{
assertEqual(1, 1);
assertNotEqual(1, 0);
}
void testBar()
{
assertEqual(1, 0); // must fail
assertNotEqual(1, 1); // must fail
}
}
void main()
{
}
输出:
setUp
runTest: testFoo
in unittest.MathTest.testFoo assertEqual(1, 1), result: true
in unittest.MathTest.testFoo assertNotEqual(1, 0), result: true
runTest: testBar
in unittest.MathTest.testBar assertEqual(1, 0), result: false
in unittest.MathTest.testBar assertNotEqual(1, 1), result: false
tearDown