text
stringlengths 0
13.4k
|
|---|
tests that exercise your ASP.NET Core application. Unit tests are small
|
tests that make sure a single method or chunk of logic works properly.
|
Integration tests (sometimes called functional tests) are larger tests that
|
simulate real-world scenarios and test multiple layers or parts of your
|
application.
|
98
|
Unit testing
|
Unit testing
|
Unit tests are small, short tests that check the behavior of a single
|
method or class. When the code you're testing relies on other methods
|
or classes, unit tests rely on mocking those other classes so that the test
|
only focuses on one thing at a time.
|
For example, the TodoController class has two dependencies: an
|
ITodoItemService and the UserManager . The TodoItemService , in turn,
|
depends on the ApplicationDbContext . (The idea that you can draw a
|
line from TodoController > TodoItemService > ApplicationDbContext is
|
called a dependency graph).
|
When the application runs normally, the ASP.NET Core service container
|
and dependency injection system injects each of those objects into the
|
dependency graph when the TodoController or the TodoItemService is
|
created.
|
When you write a unit test, on the other hand, you have to handle the
|
dependency graph yourself. It's typical to provide test-only or "mocked"
|
versions of those dependencies. This means you can isolate just the logic
|
in the class or method you are testing. (This is important! If you're testing
|
a service, you don't want to also be accidentally writing to your
|
database.)
|
Create a test project
|
It's a best practice to create a separate project for your tests, so they are
|
kept separate from your application code. The new test project should
|
live in a directory that's next to (not inside) your main project's directory.
|
99
|
Unit testing
|
If you're currently in your project directory, cd up one level. (This root
|
directory will also be called AspNetCoreTodo ). Then use this command to
|
scaffold a new test project:
|
dotnet new xunit -o AspNetCoreTodo.UnitTests
|
xUnit.NET is a popular test framework for .NET code that can be used to
|
write both unit and integration tests. Like everything else, it's a set of
|
NuGet packages that can be installed in any project. The dotnet new
|
xunit template already includes everything you need.
|
Your directory structure should now look like this:
|
AspNetCoreTodo/
|
AspNetCoreTodo/
|
AspNetCoreTodo.csproj
|
Controllers/
|
(etc...)
|
AspNetCoreTodo.UnitTests/
|
AspNetCoreTodo.UnitTests.csproj
|
Since the test project will use the classes defined in your main project,
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.