Database Reference
In-Depth Information
// test
var books = repository.BooksByCategory("Construction");
Assert.AreEqual(books.Count(), 1);
}
[TestMethod]
public void TestBooksPublishedInTheYear()
{
var repository = new BookRepository.BookRepository(_context);
var construction = new Category { Name = "Construction" };
var book = new Book { Title = "Building with Masonary",
Author = "Dick Kreh",
PublishDate = new DateTime(1998, 1, 1) };
book.Category = construction;
repository.InsertCategory(construction);
repository.InsertBook(book);
repository.SaveChanges();
// test
var books = repository.BooksByYear(1998);
Assert.AreEqual(books.Count(), 1);
}
}
7.
Right-click the Test project, and select Add New Item. Select Application Configuration File
from the General templates. Copy the <connectionStrings> section from the App.config file
in the BookRepository project, and insert it into the new App.config file in the Test project.
8.
Right-click the Test project, and select Set as Startup Project. Select Debug Start
Debugging, or press F5 to execute the tests. Make sure that there are no active connections
to the Test database. Active connections will cause the DropDatabase() method to fail.
How It Works
There are two common approaches to testing that are used with Entity Framework. The first approach is to test the
business logic implemented in your objects. For this approach, you test against a “fake” database layer because your
focus is on the business logic that governs the interactions of the objects and the rules that apply just before objects
are persisted to the database. We illustrated this approach in Recipe 8-8.
A second approach is to test both the business logic and the persistence layer by interacting with the real
database. This approach is more extensive, and also more costly in terms of time and resources. When it is
implemented in an automated test harness, like the ones often used in a continuous integration environment, you
need to automate the creation and dropping of the test database.
Each test iteration should start with a database in a known clean state. Subsequent test runs should not
be affected by residue left in the database by previous tests. Dropping and creating databases together with the
end-to-end code exercise requires more resources than the business logic only testing, as illustrated in Recipe 8-8.
In the unit tests in Listing 8-19, we checked to see whether the database exists in the Test Initialize phase.
If the database exists, it is dropped with the DropDatabase() method. Next we create the database with the
CreateDatabase() method. These methods use the connection string contained in the App.config file.
This connection string would likely be different from the development database connection string. For simplicity,
we used the same connection string for both.
 
Search WWH ::




Custom Search