Assert.True 未通过测试

Assert.True Not Passing Tests

我是第一次使用 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());
    }
}
}

这与单元测试无关。在您的代码中,您正在遍历标识符:

Array.ForEach(idents, s => AddIdentifier("true"));

您要为每个标识符添加字符串 "true"。而是添加 s.

您可以调试单元测试。然后设置断点并逐步执行代码以检查变量。

你的方法 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));
}

我猜你应该将 s 传递给函数,而不是 "true"

此处:Array.ForEach(idents, s => AddIdentifier("true"));

应该是:Array.ForEach(idents, s => AddIdentifier(s));