TestInventoryContext

Similar to TestUserInterface used in the previous chapter, the TestInventoryContext class will be used to mock the behavior of our repository by implementing the IInventoryContext interface. This class will support the three methods of the interface, as well as supporting two additional methods for retrieving the books that have been added to the collection during the unit test and for retrieving the books that have been updated during the unit test.

To support the TestInventoryContext class, two collections will be used:

private readonly IDictionary<string, Book> _seedDictionary;
private readonly IDictionary<string, Book> _books;

The first is used to store the starting collection of the books, while the second is used to store the final collection of the books. The constructor is shown in the following code; note how the dictionaries are copies of each other:

public TestInventoryContext(IDictionary<string, Book> books)
{
_seedDictionary = books.ToDictionary(book => book.Key,
book => new Book { Id = book.Value.Id,
Name = book.Value.Name,
Quantity = book.Value.Quantity });
_books = books;
}

The IInventoryContext methods are written to update and return just one of the collections, as follows:

public Book[] GetBooks()
{
return _books.Values.ToArray();
}

public bool AddBook(string name)
{
_books.Add(name, new Book() { Name = name });

return true;
}

public bool UpdateQuantity(string name, int quantity)
{
_books[name].Quantity += quantity;

return true;
}

At the end of the unit test, the two remaining methods can be used to determine the difference between the starting and ending collections:

public Book[] GetAddedBooks()
{
return _books.Where(book => !_seedDictionary.ContainsKey(book.Key))
.Select(book => book.Value).ToArray();
}

public Book[] GetUpdatedBooks()
{
return _books.Where(book => _seedDictionary[book.Key].Quantity != book.Value.Quantity)
.Select(book => book.Value).ToArray();
}
There is some confusion in the software industry around the differences between mocks, stubs, fakes, and other terms used to identify and/or categorize types or services used in testing that are not suitable for production but are necessary for the unit test. These dependencies may have functionality that is different, missing, and/or the same as their real counterparts.

For example, the TestUserInterface class could be referred to as a mock as it provides some expectation (for example, assert statements) of the unit test while the TestInventoryContext class would be a fake, as it provides a working implementation. In this book, we will not follow these classifications too strictly.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.30.232