$ dotnet testFailed BulkDiscountExpected: 45Actual: 50Failed! 1 failed, 0 passedPassed! 0 failed, 1 passeddotnet testFAILEDPASSEDBulkDiscount's variablesqty–price–total–1public class CartTests {2 [Fact]3 public void BulkDiscount() {4 // Arrange5 int qty = 10, price = 5;6 // Act7 int total = Cart.Total(qty, price);8 // Assert9 Assert.Equal(45, total);10 }11}1public static class Cart {2 public static int Total(3 int qty, int price) {4 // 10 or more items: 10% off5 if (qty > 10) if (qty >= 10)6 return qty * price * 9 / 10;7 return qty * price;8 }9}run10 · 5Total(10, 5)5045result
Front row: the test and the code under testBack row: the console, the test runner and the test's variablesTokens: run, the inputs, the call, the result, the failed or passed AssertFront row: the xUnit test CartTests.cs (Arrange, Act, Assert) and the code under test, Cart.cs. Back row: the console, the test runner (dotnet test) with its result badge, and the test's variables qty, price and total. The test calls Cart.Total(10, 5) and expects 45; the bug on line 5 returns 50, so the Assert fails (red). After the fix (> to >=) the same test passes (green). The console is shortened. The real dotnet test output also shows the build, the test file and line, timing and Skipped/Total counts, and its exact layout depends on the SDK version and test platform.

The test

  1. A unit test is a small method that calls one unit of code, such as one method, with known inputs and checks the result by itself. Here CartTests checks Cart.Total, which should give 10% off for 10 or more items.

Run it: red

Fix it: green

What happens

// step 1/10 · idea
unit        a small piece of code: one method or class
unit test   a method that calls it and checks the result
Shop        the project with Cart.cs (the code)
Shop.Tests  the test project with CartTests.cs
            references Shop + the xUnit NuGet packages
good tests  fast, isolated, repeatable, self-checking

dotnet new xunit makes the test project. It brings the xunit, xunit.runner.visualstudio and Microsoft.NET.Test.Sdk packages from NuGet and a global using for Xunit, which is why CartTests.cs needs no using line. dotnet add reference connects it to Shop. The console is shortened. The real dotnet test output also shows the build, the test file and line, timing and Skipped/Total counts, and its exact layout depends on the SDK version and test platform.