Reputation: 25
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"));
}
Upvotes: 0
Views: 861
Reputation: 44931
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.
Upvotes: 1
Reputation: 585
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.
Upvotes: 1