text
stringlengths
0
13.4k
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace AspNetCoreTodo.UnitTests
{
public class TodoItemServiceShould
{
[Fact]
public async Task AddNewItemAsIncompleteWithDueDate()
{
// ...
}
}
}
There are many different ways of naming and organizing tests, all
with different pros and cons. I like postfixing my test classes with
Should to create a readable sentence with the test method name,
but feel free to use your own style!
The [Fact] attribute comes from the xUnit.NET package, and it marks
this method as a test method.
The TodoItemService requires an ApplicationDbContext , which is
normally connected to your database. You won't want to use that for
tests. Instead, you can use Entity Framework Core's in-memory database
provider in your test code. Since the entire database exists in memory,
102
Unit testing
it's wiped out every time the test is restarted. And, since it's a proper
Entity Framework Core provider, the TodoItemService won't know the
difference!
Use a DbContextOptionsBuilder to configure the in-memory database
provider, and then make a call to AddItemAsync() :
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "Test_AddNewItem").Options;
// Set up a context (connection to the "DB") for writing
using (var context = new ApplicationDbContext(options))
{
var service = new TodoItemService(context);
var fakeUser = new ApplicationUser
{
Id = "fake-000",
UserName = "fake@example.com"
};
await service.AddItemAsync(new TodoItem
{
Title = "Testing?"
}, fakeUser);
}
The last line creates a new to-do item called Testing? , and tells the
service to save it to the (in-memory) database.
To verify that the business logic ran correctly, write some more code
below the existing using block: