简体   繁体   中英

unit test failing for converting string list to lowercase in c#

My unit test keeps failing in c# and I've tried a few different methods. Any help would be greatly appreciated. It's just not converting the book I add to lowercase. So the test fails

    private List<string> _number;

    public Book (string[] id)
    {
        //_number = idents.Select (d => d.ToLower ()).ToList ();

        _number = new List<string>(id);
        _number = _number.ConvertAll (d => d.ToLower ());
    }

    public bool Exist (string id)
    {
        return _number.Contains (id);
    }

    public void AddBook (string id)
    {
        _number.Add (id.ToLower());
    }
    _______________________________________________________________________________

    [Test ()]
    public void TestAddBook ()
    {
        Book id = new Book (new string[] {"ABC", "DEF"});
        id.AddBook ("GHI");

        Assert.AreEqual (true, id.Exist ("ghi"));
    }

Shouldn't the testmethod be like that:

[TestMethod]
public void TestAddBook ()
{
    Book id = new Book (new string[] {"ABC", "DEF"});
    id.AddBook ("GHI");

    Assert.AreEqual (true, id.Exist ("ghi"));
}

This is at least what my psycic crystal-ball senses.

A better way to solve this problem isn't actually converting keys to lowercase, it is to use a construct that can store the keys in a case-insensitive manner. This will save processing time and reduce programming errors.

If all you are interested in storing is the book key, then I would strongly suggest using HashSet instead.

The List's Contains method is O(n) while the Hashset's is O(1) . This is a significant difference if you have a lot of entries.

Here is a rewrite of the Book class using a HashSet:

public class Book
{
    private HashSet<string> _number;

    public Book(string[] id)
    {
        _number = new HashSet<string>(id, StringComparer.InvariantCultureIgnoreCase);
    }

    public bool Exist(string id)
    {
        return _number.Contains(id);
    }

    public void AddBook(string id)
    {
        _number.Add(id);
    }
}

With this revised class, you don't have to make any changes to your test method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM