text
stringlengths
0
13.4k
// Use a separate context to read data back from the "DB"
using (var context = new ApplicationDbContext(options))
{
var itemsInDatabase = await context
.Items.CountAsync();
Assert.Equal(1, itemsInDatabase);
103
Unit testing
var item = await context.Items.FirstAsync();
Assert.Equal("Testing?", item.Title);
Assert.Equal(false, item.IsDone);
// Item should be due 3 days from now (give or take a second)
var difference = DateTimeOffset.Now.AddDays(3) - item.DueAt;
Assert.True(difference < TimeSpan.FromSeconds(1));
}
The first assertion is a sanity check: there should never be more than one
item saved to the in-memory database. Assuming that's true, the test
retrieves the saved item with FirstAsync and then asserts that the
properties are set to the expected values.
Both unit and integration tests typically follow the AAA (Arrange-
Act-Assert) pattern: objects and data are set up first, then some
action is performed, and finally the test checks (asserts) that the
expected behavior occurred.
Asserting a datetime value is a little tricky, since comparing two dates for
equality will fail if even the millisecond components are different.
Instead, the test checks that the DueAt value is less than a second away
from the expected value.
Run the test
On the terminal, run this command (make sure you're still in the
AspNetCoreTodo.UnitTests directory):
dotnet test
The test command scans the current project for tests (marked with
[Fact] attributes in this case), and runs all the tests it finds. You'll see
output similar to:
Starting test execution, please wait...
104
Unit testing
Discovering: AspNetCoreTodo.UnitTests
Discovered: AspNetCoreTodo.UnitTests
Starting: AspNetCoreTodo.UnitTests
Finished: AspNetCoreTodo.UnitTests
Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.9074 Seconds
You now have one test providing test coverage of the TodoItemService .
As an extra challenge, try writing unit tests that ensure:
The MarkDoneAsync() method returns false if it's passed an ID that
doesn't exist
The MarkDoneAsync() method returns true when it makes a valid
item as complete