我第一次使用NUnit测试框架,每当我为我的代码运行测试时,它仅传递Assert.False命令,而使我使用的每个Assert.True都失败。当我运行以下测试时,只有TestNotAreYou()是唯一通过的测试。我的代码有误还是存在技术问题?
代码:
using System;
using NUnit.Framework;
using System.Collections.Generic;
namespace Week22
{
[TestFixture]
public class Test
{
private IdentifiableObject id;
[SetUp]
public void SetUp()
{
id = new IdentifiableObject(new string[] { "fred", "bob" });
}
[Test]
public void TestAreYou()
{
IdentifiableObject id = new IdentifiableObject(new string[] { "fred", "bob" });
Assert.True(id.AreYou("fred"));
Assert.True(id.AreYou("bob"));
}
[Test]
public void TestNotAreYou()
{
IdentifiableObject id = new IdentifiableObject(new string[] { "fred", "bob" });
Assert.False(id.AreYou("wilma"));
Assert.False(id.AreYou("boby"));
}
[Test]
public void TestCaseSens()
{
IdentifiableObject id = new IdentifiableObject(new string[] { "fred", "bob" });
Assert.True(id.AreYou("fred"));
Assert.True(id.AreYou("bob"));
Assert.True(id.AreYou("Fred"));
Assert.True(id.AreYou("bOB"));
}
[Test]
public void TestFirstID()
{
IdentifiableObject id = new IdentifiableObject(new string[] { "fred", "bob" });
Assert.True(id.FirstID == "fred");
}
[Test]
public void TestAddID()
{
IdentifiableObject id = new IdentifiableObject(new string[] { "fred", "bob" });
id.AddIdentifier("wilma");
Assert.True(id.AreYou("fred"));
Assert.True(id.AreYou("bob"));
Assert.True(id.AreYou("wilma"));
}
}
}
正在测试的程序:
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
namespace Week22
{
public class IdentifiableObject
{
private List<string> _identifiers = new List<string>();
public IdentifiableObject(string[] idents)
{
Array.ForEach(idents, s => AddIdentifier("true"));
}
public bool AreYou(string id)
{
return _identifiers.Contains(id.ToLower());
}
public string FirstID
{
get
{
return _identifiers.First();
}
}
public void AddIdentifier(string id)
{
_identifiers.Add(id.ToLower());
}
}
}
答案 0 :(得分:4)
这与单元测试无关。在代码中,您正在遍历标识符:
Array.ForEach(idents, s => AddIdentifier("true"));
您要为每个标识符添加字符串“ true”。而是添加s
。
您可以调试单元测试。然后设置一个断点并逐步执行代码以检查变量。
答案 1 :(得分:0)
您的方法public void AddIdentifier(string id)
我相信只会添加"true"
或尝试替换
public IdentifiableObject(string[] idents)
{
Array.ForEach(idents, s => AddIdentifier("true"));
}
与
public IdentifiableObject(string[] idents)
{
Array.ForEach(idents, s => AddIdentifier(s));
}
答案 2 :(得分:0)
我猜您应该将s
传递给函数,而不是"true"
。
此处:Array.ForEach(idents, s => AddIdentifier("true"));
应为:Array.ForEach(idents, s => AddIdentifier(s));