text
stringlengths
0
13.4k
you'll need to add a reference to the AspNetCoreTodo project:
dotnet add reference ../AspNetCoreTodo/AspNetCoreTodo.csproj
Delete the UnitTest1.cs file that's automatically created. You're ready
to write your first test.
If you're using Visual Studio Code, you may need to close and
reopen the Visual Studio Code window to get code completion
working in the new project.
Write a service test
100
Unit testing
Take a look at the logic in the AddItemAsync() method of the
TodoItemService :
public async Task<bool> AddItemAsync(
TodoItem newItem, ApplicationUser user)
{
newItem.Id = Guid.NewGuid();
newItem.IsDone = false;
newItem.DueAt = DateTimeOffset.Now.AddDays(3);
newItem.UserId = user.Id;
_context.Items.Add(newItem);
var saveResult = await _context.SaveChangesAsync();
return saveResult == 1;
}
This method makes a number of decisions or assumptions about the new
item (in other words, performs business logic on the new item) before it
actually saves it to the database:
The UserId property should be set to the user's ID
New items should always be incomplete ( IsDone = false )
The title of the new item should be copied from newItem.Title
New items should always be due 3 days from now
Imagine if you or someone else refactored the AddItemAsync() method
and forgot about part of this business logic. The behavior of your
application could change without you realizing it! You can prevent this by
writing a test that double-checks that this business logic hasn't changed
(even if the method's internal implementation changes).
It might seem unlikely now that you could introduce a change in
business logic without realizing it, but it becomes much harder to
keep track of decisions and assumptions in a large, complex
project. The larger your project is, the more important it is to have
automated checks that make sure nothing has changed!
101
Unit testing
To write a unit test that will verify the logic in the TodoItemService ,
create a new class in your test project:
AspNetCoreTodo.UnitTests/TodoItemServiceShould.cs
using System;
using System.Threading.Tasks;
using AspNetCoreTodo.Data;
using AspNetCoreTodo.Models;
using AspNetCoreTodo.Services;