When I first started learning more about unit testing in C#, I had a very simple mental picture:
Write some code, run xUnit, and see if the application works.
That’s not completely wrong.
But it isn’t really what a unit test does.
The important word is unit.
A unit test usually isn’t trying to start my entire ASP.NET Core application, connect to SQL Server, render a Razor View, send an HTTP request, and simulate a real person using the website.
It’s trying to isolate a small piece of my code and verify that it behaves the way I expect.
That distinction helped unit testing make much more sense to me.
What Is the Unit?
The “unit” can be something like:
- A method
- A service
- A calculation
- A validation rule
- Part of a Controller action
For example, suppose my finance application has an account service:
public class AccountService
{
public bool CanWithdraw(decimal balance, decimal amount)
{
if (amount <= 0)
{
return false;
}
return balance >= amount;
}
}
That is very easy to test because it contains a clear rule.
[Fact]
public void CanWithdraw_ReturnsTrue_WhenBalanceIsEnough()
{
var service = new AccountService();
var result = service.CanWithdraw(500m, 100m);
Assert.True(result);
}
I’m not testing ASP.NET Core here.
I’m testing my business rule.
Arrange, Act, Assert
A lot of unit tests follow a pattern called:
ARRANGE
↓
ACT
↓
ASSERT
Arrange
Prepare everything the test needs.
var service = new AccountService();
Act
Execute the behavior I’m testing.
var result = service.CanWithdraw(500m, 100m);
Assert
Verify the result.
Assert.True(result);
I like this pattern because it makes the purpose of the test easy to read.
What About Controllers?
Controllers can also contain behavior worth testing.
Suppose I have:
[HttpPost]
public async Task<IActionResult> Create(CreateAccountViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
await _accountService.CreateAsync(model);
return RedirectToAction(nameof(Index));
}
There are several decisions happening here.
If the model is invalid:
Return the same View
If the model is valid:
Create the account
Redirect to Index
Those decisions are part of my Controller logic.
So I can unit test them.
For example:
[Fact]
public async Task Create_ReturnsView_WhenModelIsInvalid()
{
var mockService = new Mock<IAccountService>();
var controller = new AccountsController(mockService.Object);
controller.ModelState.AddModelError("Name", "Required");
var model = new CreateAccountViewModel();
var result = await controller.Create(model);
Assert.IsType<ViewResult>(result);
}
Now I’m checking one very specific rule:
If ModelState is invalid, does my Controller return the View?
But I’m Not Testing Model Binding
This distinction is important.
In that test, I manually added an error to ModelState.
controller.ModelState.AddModelError("Name", "Required");
The test isn’t proving that ASP.NET Core’s entire HTTP model-binding system works.
ASP.NET Core already has its own tests for ASP.NET Core.
My unit test is checking how my Controller reacts when the model is invalid.
That changed the way I think about unit testing.
I don’t need to retest Microsoft’s framework.
I need to test the decisions I’ve added to it.
Mocking Dependencies
Controllers usually depend on other things.
For example:
public class AccountsController : Controller
{
private readonly IAccountService _accountService;
public AccountsController(IAccountService accountService)
{
_accountService = accountService;
}
}
When I’m unit testing the Controller, I usually don’t want the test talking to a real database.
I want the Controller isolated.
So I can use a mock:
var mockService = new Mock<IAccountService>();
Then I pass the fake dependency into the Controller:
var controller =
new AccountsController(mockService.Object);
Now I can verify that the Controller called the service correctly.
mockService.Verify(
s => s.CreateAsync(model),
Times.Once);
This is another reason dependency injection and unit testing fit together so well.
If a class receives its dependencies from outside, I can replace them during testing.
What Unit Tests Usually Do Not Test
This is where I had to adjust my mental model.
A normal unit test generally does not prove that all of these things work together:
Browser
↓
HTTP Request
↓
Routing
↓
Model Binding
↓
Controller
↓
EF Core
↓
SQL Server
↓
Razor View
↓
HTML Response
That’s a much bigger test.
If I want to test several real components working together, I’m getting into integration testing.
If I want to simulate an actual user’s behavior through the full application, that’s closer to an end-to-end test.
So the tests serve different purposes.
UNIT TEST
Small isolated behavior
INTEGRATION TEST
Several components working together
END-TO-END TEST
The application behaving like the user experiences it
What Should I Unit Test?
As I’m learning to add tests to my own projects, the things that interest me most are places where I’ve made decisions.
For example:
Business Rules
Can this transaction be processed?
Is this amount allowed?
How should this value be calculated?
Controller Decisions
Should this return a View?
Should this redirect?
Should this call a service?
Validation
Is this amount valid?
Is the required information present?
Transformations
Does this data get mapped correctly?
Does this calculation return the expected result?
Those are all behaviors I control.
A Passing Test Isn’t the Goal by Itself
Of course, I could write a meaningless test that always passes.
Assert.True(true);
Very impressive.
Green checkmark achieved. 😂
But the point isn’t simply creating green tests.
The value comes from being able to change code later and have the tests warn me when I’ve accidentally changed behavior that was supposed to stay the same.
That’s where testing starts becoming more than a classroom exercise.
It becomes a safety net.
How I Think About Unit Tests Now
This is the simplest definition that works for me:
A unit test isolates a small piece of my code and asks, “Given this situation, does my code make the decision I expect?”
That makes unit testing feel much less mysterious.
I’m not trying to prove that the entire internet works every time I run xUnit.
I’m testing the logic I wrote.
One small decision at a time.
