我是……单元测试的初学者。
我刚刚阅读了一些单元测试最佳实践。有点理解单元测试旨在防止对代码进行的更改会破坏应用程序。我们将希望在所有对象的公共 API(getter、方法)上创建测试用例来测试对象的行为,看看是否符合我们的预期。
所以现在..我有一个简单的类需要测试:
public class Foo{
private readonly string _text;
public Foo(string initialText)
{
this._text = initialText;
}
public string Text {get;}
//Some other methods that will use this Text property to parsing, comparasion etc
public string RichTextFormat {....}
}
在这里,就像在评论中一样,这个Text属性在解析、比较等方面使用了很多地方。
所以我认为确保Text属性完全返回我在构造函数中传递的内容非常重要。
这是我写的测试用例...
[TestMethod]
public void Text_WhenInitialTextIsNull()
{
string initalizeText = null;
Foo realFoo = new Foo(initalizeText);
Assert.AreEqual(initalizeText, realFoo.Text);
}
[TestMethod]
public void Text_WhenInitialTextIsEmpty()
{
string initalizeText = string.Empty;
Foo realFoo = new Foo(initalizeText);
Assert.AreEqual(initalizeText, realFoo.Text);
}
[TestMethod]
public void Text_WhenInitialTextIsOneLetter()
{
string initalizeText = "A";
Foo realFoo = new Foo(initalizeText);
Assert.AreEqual(initalizeText, realFoo.Text);
}
[TestMethod]
public void Text_WhenInitialTextIsOneSpecialCharacter()
{
string initalizeText = "!";
Foo realFoo = new Foo(initalizeText);
Assert.AreEqual(initalizeText, realFoo.Text);
}
[TestMethod]
public void Text_WhenInitialTextIsOneSentense()
{
string initalizeText = "Hello, World!";
Foo realFoo = new Foo(initalizeText);
Assert.AreEqual(initalizeText, realFoo.Text);
}
[TestMethod]
public void Text_WhenInitialTextIsOneParagraph()
{
string initalizeText = "Who's the Smartphone Winner? " + System.Environment.NewLine +
" On the smartphone front, however, iSuppli put Apple at number one," +
" while Strategy Analytics pointed to Samsung. " + System.Environment.NewLine +
" According to iSuppli, Apple shipped 35 million smartphones in the first quarter" +
" to Samsung's 32 million. Strategy Analytics, however, said Samsung's total was" +
" 44.5 million to Apple's 35.1 million. Nokia landed at number three on both lists" +
" with 12 percent market share. ";
Foo realFoo = new Foo(initalizeText);
Assert.AreEqual(initalizeText, realFoo.Text);
}
我想知道这……是不是太重了?