Lesson 63 of 93 · 6 min read · Updated

Testing Business Rules Below the Web Layer in ASP.NET Core Applications

The most valuable unit tests in a web application often do not touch the web at all. When a business rule lives in a plain class, you can test every boundary with fast, simple tests that need no controller, no HttpContext and no mocks. This lesson tests a pricing rule that sits underneath an MVC controller and shows how that keeps the controller tests small.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2

That is the whole list. The test class imports only FluentAssertions and the domain namespace. No ASP.NET Core type appears in it.

The Rule as a Pure Function

The product catalogue has one pricing rule with three parts: a price must be positive, must not exceed an upper limit, and must not rise by more than 50% in a single change.

M07.WebApp/Domain/PricingRules.cs

/// <summary>
/// The most valuable unit tests are written here: pure business rules with
/// no dependency at all on the web, HTTP or MVC.
/// Controller tests only verify the HTTP CONTRACT.
/// </summary>
public static class PricingRules
{
/// <summary>The highest acceptable product price.</summary>
public const decimal MaxPrice = 1_000_000m;

/// <summary>The rate a price increase may not exceed in a single change.</summary>
public const decimal MaxIncreaseRate = 0.50m;

/// <summary>
/// Is the new price acceptable?
/// Rule: the price must be positive, must not exceed the upper limit and
/// must not rise more than 50% above the current price.
/// </summary>
public static bool CanChangePrice(decimal currentPrice, decimal newPrice, out string? reason)
{
if (newPrice <= 0)
{
reason = "Fiyat pozitif olmalıdır.";
return false;
}

if (newPrice > MaxPrice)
{
reason = $"Fiyat {MaxPrice:0} üzerinde olamaz.";
return false;
}

if (currentPrice > 0 && newPrice > currentPrice * (1 + MaxIncreaseRate))
{
reason = "Tek seferde %50'den fazla zam yapılamaz.";
return false;
}

reason = null;
return true;
}
}

The reasons are user-facing Turkish messages: "Price must be positive", "Price cannot be above 1000000" and "A price cannot be raised by more than 50% at once". The method returns a decision and a reason. The controller decides how to show the reason, for example as a ModelState error. The rule does not know that ModelState exists.

A current price of 0 means "new product". In that case there is nothing to compare with, so the increase check is skipped. The Create action passes currentPrice: 0m; the Edit action passes the stored price.

One Theory for All the Boundaries

Because the rule is a pure function, a single [Theory] can list every interesting case as a row of data.

M07.WebApp.Tests/BusinessRuleTests.cs

[Theory]
[InlineData(0, 100, true)] // new product: no current price
[InlineData(100, 150, true)] // boundary: exactly a 50% increase
[InlineData(100, 150.01, false)] // boundary: one cent above 50%
[InlineData(100, 90, true)] // a discount is always allowed
[InlineData(100, 0, false)] // must be positive
[InlineData(100, -5, false)]
public void CanChangePrice_EnforcesIncreaseLimit(
decimal currentPrice, decimal newPrice, bool expected)
{
PricingRules.CanChangePrice(currentPrice, newPrice, out _).Should().Be(expected);
}

Read the rows as a specification. The two middle cases sit right on the boundary: 150 is exactly 50% more than 100 and is allowed, while 150.01 is one cent above and is rejected. Those two rows pin down that the comparison is > and not >=. A rule tested only with 100 and 200 would pass with either operator.

C# attributes cannot hold decimal constants, so the InlineData values are written as int and double. xUnit converts them to the decimal parameters before the test runs. For values like 150.01 this is exact enough, but for money values with many digits, consider MemberData that builds the decimal values in code.

The out _ discard says that this theory only cares about the decision, not the reason.

Checking the Reason Too

Two more tests check the reason output. One checks that a rejection explains itself; the other checks that an accepted price carries no leftover message.

M07.WebApp.Tests/BusinessRuleTests.cs

[Fact]
public void CanChangePrice_AboveMaxPrice_IsRejectedWithReason()
{
var allowed = PricingRules.CanChangePrice(
currentPrice: 0m, PricingRules.MaxPrice + 1m, out var reason);

allowed.Should().BeFalse();
reason.Should().Contain("üzerinde olamaz");
}

[Fact]
public void CanChangePrice_WhenAllowed_ReasonIsNull()
{
PricingRules.CanChangePrice(100m, 120m, out var reason).Should().BeTrue();

reason.Should().BeNull();
}

The first test builds its input from PricingRules.MaxPrice + 1m instead of the literal 1000001. If the limit changes, the test still checks "one above the limit". The second test matters because the controller uses reason! only after a false result. If an accepted price ever came back with a message, a future caller might show it by mistake.

Why This Keeps Controller Tests Small

Count the cases. The rule has six interesting price combinations. The Edit action has four paths: invalid model, missing product, rule violation and success. If the rule lived inside the controller, you would be tempted to test every price combination through every path, with a mock repository and TempData in each test. That is the combination explosion.

With the rule below the web layer, the work splits cleanly:

  1. BusinessRuleTests covers every price boundary, with no web types.
  2. The controller tests cover each HTTP path once. For the rule, one test is enough: "when the rule says no, show the form with a Price error".

Rule of thumb: if your web layer tests suffer from a combination explosion, the business rule is probably in the wrong layer. Move it into a plain class and test it there.

There is also a speed benefit. These tests create no objects except the inputs. They run in microseconds, so you can add a new boundary row whenever a bug report shows a case you missed.

Summary

  1. Keep business rules in plain classes with no dependency on ASP.NET Core; their tests need no controller, context or mocks.
  2. Use one [Theory] with InlineData rows as a readable specification of the rule.
  3. Test both sides of each boundary, such as exactly 50% and one cent above, to pin down > versus >=.
  4. Build boundary inputs from the rule's constants, such as MaxPrice + 1m, so tests follow changes to the limit.
  5. A combination explosion in controller tests means a rule should move down a layer.