【发布时间】:2010-05-27 14:51:09
【问题描述】:
我一直在开发一个必须使用 JUnit 进行测试的 Java 应用程序。我边走边学。到目前为止,我发现它很有用,尤其是与 Eclipse JUnit 插件结合使用时。
玩了一会儿之后,我开发了一种一致的方法来为没有返回值的函数构建单元测试。我想在这里分享它并请其他人发表评论。您是否有任何建议的改进或替代方法来实现相同的目标?
常见的返回值
首先,有一个枚举用于存储表示测试结果的值。
public enum UnitTestReturnValues
{
noException,
unexpectedException
// etc...
}
广义测试
假设正在编写一个单元测试:
public class SomeClass
{
public void targetFunction (int x, int y)
{
// ...
}
}
将创建 JUnit 测试类:
import junit.framework.TestCase;
public class TestSomeClass extends TestCase
{
// ...
}
在这个类中,我创建了一个函数,用于每次调用被测试的目标函数。它捕获所有异常并根据结果返回一条消息。例如:
public class TestSomeClass extends TestCase
{
private UnitTestReturnValues callTargetFunction (int x, int y)
{
UnitTestReturnValues outcome = UnitTestReturnValues.noException;
SomeClass testObj = new SomeClass ();
try
{
testObj.targetFunction (x, y);
}
catch (Exception e)
{
UnitTestReturnValues.unexpectedException;
}
return outcome;
}
}
JUnit 测试
JUnit 调用的函数以函数名中的小写“test”开头,它们在第一个失败的断言时失败。要在上面的 targetFunction 上运行多个测试,它会写成:
public class TestSomeClass extends TestCase
{
public void testTargetFunctionNegatives ()
{
assertEquals (
callTargetFunction (-1, -1),
UnitTestReturnValues.noException);
}
public void testTargetFunctionZeros ()
{
assertEquals (
callTargetFunction (0, 0),
UnitTestReturnValues.noException);
}
// and so on...
}
如果您有任何建议或改进,请告诉我。请记住,我正在学习如何使用 JUnit,所以我确信现有的工具可以使这个过程变得更容易。谢谢!
【问题讨论】:
-
void 函数一般都有副作用,你能测试一下吗?
标签: unit-testing junit exception