elf*_*elf 8 java testing junit
给定一个toString方法:
public String toString()
{
String accountString;
NumberFormat money = NumberFormat.getCurrencyInstance();
accountString = cust.toString();
accountString += " Current balance is " + money.format (balance);
return accountString;
}
Run Code Online (Sandbox Code Playgroud)
我怎么用Junit测试它?
duf*_*ymo 13
这是我如何做到的:
public class AccountTest
{
@Test
public void testToString()
{
Account account = new Account(); // you didn't supply the object, so I guessed
String expected = ""; // put the expected value here
Assert.assertEquals(expected, account.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在想这个,虽然我觉得duffymo的答案很好,但这不是最好的.
我看到的问题是你不能总是知道的事情,或者正如你在评论中指出的那样,换行符和其他可能无关紧要的空格字符.
所以我认为更好的是不使用assertEquals,我会说使用assertTrue与contains(检查字符串中是否存在特定的String)和/或匹配(使用正则表达式来查看String是否包含某种模式).
假设您正在使用定义为的Name类
public class Name {
// each of these can only be alphabetic characters
String first;
String middle;
String last;
// a bunch of methods here
String toString(){
String out = "first=" + first + "\n" +
"middle=" + middle + "\n" +
"last=" + last + "\n" +
"full name=" + first + " " middle + " " + last;
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在用以下方法测试它(假设name是在先前的setUp方法中创建的Name对象)
void toStringTest1(){
String toString = name.toString();
// this test checks that the String at least is
// outputting "first=" followed by the first variable
// but the first variable may incorrect 1's and 0's
assertTrue(toString.contains("first=" + first));
}
void toStringTest2(){
String toString = name.toString();
// this test checks that the String has "first="
// followed by only alphabetic characters
assertTrue(toString.matches("first=[a-zA-Z]*?"));
}
Run Code Online (Sandbox Code Playgroud)
这种测试比duffymo所说的要强大得多.如果您希望toString包含哈希码,您将无法事先知道预期值可能是什么.
这也可以让您涵盖更多的可能性.可能是您的一个预期值恰好是它适用的情况.
另外,请记住,您还需要进行测试(在我的给定情况下)来设置第一个变量.虽然有人可能会认为进行setFirst测试就足够了,但最好还是进行更多的测试,因为可能是setFirst工作但是你有一些失败的toString(也许你先拆分并添加:没有意识到)
更多种类的测试总是更好!
一个非常好的用于在模型类上测试 toString 的库:https : //github.com/jparams/to-string-verifier
样本:
@Test
public void myTest()
{
ToStringVerifier.forClass(Student.class).verify();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23185 次 |
最近记录: |