agentsclimarketplace

Dotnet unit test

Skill CodeMachine0121/DotNet-Developing-Skills/skills/dotnet-unit-test

Use when writing or reviewing unit tests in .NET Core C# projects. Applies to test structure, naming, mocking, assertions, and framework setup using TUnit, NSubstitute, and FluentAssertions.From its SKILL.md

Install
npx -y skills add CodeMachine0121/DotNet-Developing-Skills --skill dotnet-unit-test

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

2 things to look at

  • no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
  • 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

6.4 KB, as published. Nobody here has run it

.NET Core Unit Testing Style

Stack

RoleLibraryVersion
Test frameworkTUnitlatest
Mock frameworkNSubstitutelatest
Assertion libraryFluentAssertionspinned 7.2.2

Package Reference (csproj)

<PackageReference Include="TUnit" Version="*" />
<PackageReference Include="NSubstitute" Version="*" />
<PackageReference Include="FluentAssertions" Version="[7.2.2]" />

FluentAssertions must use bracket notation [7.2.2] to pin the exact version.


Rules at a Glance

RuleDescription
One assertion per testEach test case contains exactly one Should() call
Naming: Method_Scenario_ExpectedBehaviorTest name is the specification
AAA structureArrange / Act / Assert separated by blank lines
Mock only external dependenciesRepositories, HTTP clients — not domain objects
Test public API onlyNever test private or internal implementation details
Fluent test bodyReadable as a sentence; no procedural clutter
Given... prefixMethods that set up mock return values
Create... prefixMethods that instantiate objects under test or test data
Setup in [Before(Test)]SUT and injected interfaces declared and initialized there

Test Structure

Naming Convention

MethodName_Scenario_ExpectedBehavior
// examples
PlaceOrder_WithValidDto_ReturnsSuccessResult
PlaceOrder_WhenUserNotFound_ThrowsNotFoundException
GetTotal_WithDiscount_AppliesDiscountRate

AAA Layout

[Test]
public async Task PlaceOrder_WithValidDto_ReturnsSuccessResult()
{
    // Arrange
    var dto = CreateValidOrderDto();
    GivenUserExists(dto.UserId);

    // Act
    var result = await _sut.PlaceOrder(dto);

    // Assert
    result.IsSuccess.Should().BeTrue();
}

Setup

Declare the SUT and all substituted interfaces as fields. Initialize them in [Before(Test)].

public class OrderServiceTests
{
    private OrderService _sut;
    private IOrderRepository _orderRepo;
    private IUserRepository _userRepo;

    [Before(Test)]
    public void Setup()
    {
        _orderRepo = Substitute.For<IOrderRepository>();
        _userRepo = Substitute.For<IUserRepository>();
        _sut = new OrderService(_orderRepo, _userRepo);
    }
}

Helper Methods

Given... — mock return values

Extract mock setup into Given methods when it would clutter the Arrange block.

private void GivenUserExists(Guid userId)
{
    _userRepo.Get(userId).Returns(new User { Id = userId, Name = "Alice" });
}

private void GivenUserNotFound(Guid userId)
{
    _userRepo.Get(userId).Returns((User?)null);
}

Create... — object construction

Extract new expressions for the SUT's inputs into Create methods.

private static CreateOrderDto CreateValidOrderDto() =>
    new(UserId: Guid.NewGuid(), ProductIds: [Guid.NewGuid()], CouponCode: null);

private static CreateOrderDto CreateOrderDtoWithCoupon(string code) =>
    new(UserId: Guid.NewGuid(), ProductIds: [Guid.NewGuid()], CouponCode: code);

Assertions

Use FluentAssertions. One Should() chain per test.

// value
result.Should().Be(42);
result.Should().BeNull();
result.IsSuccess.Should().BeTrue();

// collection
items.Should().HaveCount(3);
items.Should().Contain(x => x.Id == expectedId);

// async exception
await _sut.Invoking(s => s.PlaceOrder(dto))
    .Should().ThrowAsync<NotFoundException>();

What to Mock

Mock itDon't mock it
Repository interfacesDomain models (Order, User)
HTTP clients / external APIsValue objects
Message bus / email senderPure computation services
File system abstractionsIn-memory collections

Full Example

public class OrderServiceTests
{
    private OrderService _sut;
    private IOrderRepository _orderRepo;
    private IUserRepository _userRepo;

    [Before(Test)]
    public void Setup()
    {
        _orderRepo = Substitute.For<IOrderRepository>();
        _userRepo = Substitute.For<IUserRepository>();
        _sut = new OrderService(_orderRepo, _userRepo);
    }

    [Test]
    public async Task PlaceOrder_WithValidDto_SavesOrder()
    {
        // Arrange
        var dto = CreateValidOrderDto();
        GivenUserExists(dto.UserId);

        // Act
        await _sut.PlaceOrder(dto);

        // Assert
        await _orderRepo.Received(1).Save(Arg.Any<Order>());
    }

    [Test]
    public async Task PlaceOrder_WithValidDto_ReturnsSuccessResult()
    {
        // Arrange
        var dto = CreateValidOrderDto();
        GivenUserExists(dto.UserId);

        // Act
        var result = await _sut.PlaceOrder(dto);

        // Assert
        result.IsSuccess.Should().BeTrue();
    }

    [Test]
    public async Task PlaceOrder_WhenUserNotFound_ThrowsNotFoundException()
    {
        // Arrange
        var dto = CreateValidOrderDto();
        GivenUserNotFound(dto.UserId);

        // Act & Assert
        await _sut.Invoking(s => s.PlaceOrder(dto))
            .Should().ThrowAsync<NotFoundException>();
    }

    // --- Given ---

    private void GivenUserExists(Guid userId) =>
        _userRepo.Get(userId).Returns(new User { Id = userId });

    private void GivenUserNotFound(Guid userId) =>
        _userRepo.Get(userId).Returns((User?)null);

    // --- Create ---

    private static CreateOrderDto CreateValidOrderDto() =>
        new(UserId: Guid.NewGuid(), ProductIds: [Guid.NewGuid()], CouponCode: null);
}

Violation Quick Reference

SymptomFix
Multiple Should() calls in one testSplit into separate test methods
Mock setup inline in test bodyExtract to Given... method
new SomeDto(...) repeated across testsExtract to Create... method
private fields initialized inlineMove to [Before(Test)]
Test name is Test1 or ShouldWorkRename to Method_Scenario_ExpectedBehavior
Mocking a domain model or value objectUse a real instance instead
Testing via reflection or internal membersRedesign — test the public API
Missing blank lines between AAA blocksAdd blank lines to separate Arrange / Act / Assert

Keep looking

Skills are one crate of 608,475. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.