Search code examples
c#testingnunitassert

Assert.True Not Passing Tests


I am using NUnit Testing Framework for the first time and whenever I Run Tests for my code it only passes Assert.False commands, while failing every Assert.True I use. When i run the test below, only TestNotAreYou() is the only one that passes. Is my code wrong or do I have a technical problem?

Code:

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

Program thats being tested:

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

Solution

  • This has nothing to do with unit tests. In your code, you're iterating over the identifiers:

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

    You're adding the string "true" for each identifier. Instead add s.

    You can debug unit tests. Then set a breakpoint and step through your code to inspect your variables.