【发布时间】:2015-08-27 02:33:14
【问题描述】:
我想知道要测试的对象是否应该是一个字段,并因此在 SetUp 方法期间设置(即 JUnit、nUnit、MS 测试……)。
考虑以下示例(这是带有 MsTest 的 C♯,但任何其他语言和测试框架的想法应该类似):
public class SomeStuff
{
public string Value { get; private set; }
public SomeStuff(string value)
{
this.Value = value;
}
}
[TestClass]
public class SomeStuffTestWithSetUp
{
private string value;
private SomeStuff someStuff;
[TestInitialize]
public void MyTestInitialize()
{
this.value = Guid.NewGuid().ToString();
this.someStuff = new SomeStuff(this.value);
}
[TestCleanup]
public void MyTestCleanup()
{
this.someStuff = null;
this.value = string.Empty;
}
[TestMethod]
public void TestGetValue()
{
Assert.AreEqual(this.value, this.someStuff.Value);
}
}
[TestClass]
public class SomeStuffTestWithoutSetup
{
[TestMethod]
public void TestGetValue()
{
string value = Guid.NewGuid().ToString();
SomeStuff someStuff = new SomeStuff(value);
Assert.AreEqual(value, someStuff.Value);
}
}
当然,只有一个测试方法,第一个例子太长了,但是如果有更多的测试方法,这可能是安全的一些冗余代码。
每种方法的优缺点是什么?有没有“最佳实践”?
【问题讨论】:
标签: unit-testing