2011-04-16 19 views
5

给定一个toString方法:测试的toString Junit的

public String toString() 
{ 
    String accountString; 
    NumberFormat money = NumberFormat.getCurrencyInstance(); 

    accountString = cust.toString(); 
    accountString += " Current balance is " + money.format (balance); 
    return accountString; 
} 

如何与JUnit测试呢?

回答

10

以下是我会做:

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()); 
    } 
} 
+0

嗨dyffymo,我是试你写什么,但不工作: – elf 2011-04-16 21:50:25

+0

是的,它的作用。你必须做的比我发布的要多。看到我说你必须添加什么东西的地方?您的CLASSPATH中是否有JUnit 4.x?它适用,如果你做得对。你必须做适当的进口等。我假设你知道关于Java的一些东西。 – duffymo 2011-04-16 21:51:12

+0

java.lang.AssertionError:expected:但是: elf 2011-04-16 21:53:36

5

我一直在想这个也和我一想起duffymo的答案是好的,但不是最好的。

我看到的问题是你不能总是知道的东西,或者正如你在评论中指出的那样,换行符和其他空间字符可能并不重要。所以我认为更好的事情是,而不是使用assertEquals,我会说使用assertTrue与contains(检查字符串中是否存在特定的字符串)和/或匹配(使用正则表达式来查看字符串是否包含某种模式)。

比方说,你被定义为

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; 
    } 
} 

一个名称类的工作,所以现在你用下面的(假设名字是现有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]*?")); 
} 
测试这个

这种测试比duffymo所说的要强得多。如果你想要String来包含一个哈希码,你将无法事先知道预期值是什么。

这也可以让你覆盖更多的可能性。这可能是因为你的一个期望值恰好是它适用的情况。

另外,请记住,你也想要测试(在我的情况下)设置第一个变量。虽然人们可能会认为setFirst测试就足够了,但最好在所有板上进行更多的测试,因为它可能是setFirst的工作原理,但是你有一些toString失败(也许你先分裂并添加了一个:没有意识到)

更多种类的测试总是更好!

进行测试,以字符串的模型类
2

一个非常好的图书馆: https://github.com/jparams/to-string-tester

样品:

@Test 
public void myTest() 
{ 
    ToStringTester.forClass(Student.class) 
        .containsAllFields() 
        .verify(); 
} 
+0

虽然这个链接可能回答这个问题,但最好在这里包含答案的基本部分,并提供参考链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/18098198) – 2017-11-29 11:17:52

+0

我是新来的,但会保持这种心态。要回答@Antoni,这在junit测试中起作用。 – 2017-11-29 14:54:17