Przejdź do treści
Biblioteka skilli
Programowanie · Testowanie

xunit

/xunit

Opisuje testy w xUnit.net dla .NET: Fact, Theory, fixtures, wstrzykiwanie zależności oraz mockowanie w Moq i NSubstitute.

Licencja
MIT
Ostatnia zmiana repozytorium
21.10.2026

Ocena i bezpieczeństwo

95/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść30 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 21.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Opisuje testy w xUnit.net dla .NET: Fact, Theory, fixtures, wstrzykiwanie zależności oraz mockowanie w Moq i NSubstitute.

Wyzwalacze z opisu

xUnit.NET testingFactTheoryInlineDataMoqNSubstituteC# unit test
Oryginalny opis (EN)

xUnit.net testing framework with Fact, Theory, fixtures, DI, and mocking with Moq and NSubstitute. Covers .NET testing best practices. USE WHEN: user mentions "xUnit", ".NET testing", "Fact", "Theory", "InlineData", "Moq", "NSubstitute", "C# unit test" DO NOT USE FOR: NUnit - use `nunit`, Vitest - use `vitest`, Jest - use `jest`, Playwright - use `playwright`

Jak działa

  1. Basic Tests
  2. Theory (Parameterized Tests)
  3. Mocking with Moq
  4. Mocking with NSubstitute
  5. Fixtures (Shared Context)
  6. FluentAssertions (Optional)
  7. Anti-Patterns
  8. Quick Troubleshooting
Sekcje z nagłówków SKILL.md, w oryginale · 178 linii, 522 słów
Podgląd SKILL.md
---
name: xunit
description: |
  xUnit.net testing framework with Fact, Theory, fixtures, DI, and mocking
  with Moq and NSubstitute. Covers .NET testing best practices.

  USE WHEN: user mentions "xUnit", ".NET testing", "Fact", "Theory", "InlineData",
  "Moq", "NSubstitute", "C# unit test"

  DO NOT USE FOR: NUnit - use `nunit`, Vitest - use `vitest`,
  Jest - use `jest`, Playwright - use `playwright`
allowed-tools: Read, Grep, Glob, Write, Edit
---
# xUnit.net - Quick Reference

> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `xunit` for comprehensive documentation.

## Basic Tests

```csharp
public class UserServiceTests
{
    [Fact]
    public async Task GetById_ExistingUser_ReturnsUser()
    {
        // Arrange
        var repository = new Mock<IUserRepository>();
        repository.Setup(r => r.GetByIdAsync(1))
            .ReturnsAsync(new User { Id = 1, Name = "Alice" });

        var service = new UserService(repository.Object, Mock.Of<ILogger<UserService>>());

        // Act
        var result = await service.GetByIdAsync(1);

        // Assert
        Assert.NotNull(result);
        Assert.Equal("Alice", result.Name);
    }

    [Fact]
    public async Task GetById_NonExistingUser_ReturnsNull()
    {
        var repository = new Mock<IUserRepository>();
        repository.Setup(r => r.GetByIdAsync(999)).ReturnsAsync((User?)null);

        var service = new UserService(repository.Object, Mock.Of<ILogger<UserService>>());

        var result = await service.GetByIdAsync(999);

        Assert.Null(result);
    }
}
```

## Theory (Parameterized Tests)

```csharp
[Theory]
[InlineData("", false)]
[InlineData("a", false)]
[InlineData("ab", true)]
[InlineData("valid@email.com", true)]
public void Validate_Name_ReturnsExpected(string name, bool expected)
{
    var validator = new UserValidator();
    var result = validator.IsValidName(name);
    Assert.Equal(expected, result);
}

[Theory]
[MemberData(nameof(GetTestUsers))]
public async Task Create_ValidUser_Succeeds(CreateUserRequest request)
{
    // Test with complex objects
}

public static IEnumerable<object[]> GetTestUsers()
{
    yield return new object[] { new CreateUserRequest("Alice", "alice@test.com") };
    yield return new object[] { new CreateUserRequest("Bob", "bob@test.com") };
}
```

## Mocking with Moq

```csharp
// Setup
var mock = new Mock<IUserRepository>();

// Return value
mock.Setup(r => r.GetByIdAsync(It.IsAny<int>()))
    .ReturnsAsync(new User { Id = 1, Name = "Test" });

// Callback
mock.Setup(r => r.AddAsync(It.IsAny<User>()))
    .Callback<User>(user => user.Id = 42)
    .Returns(Task.CompletedTask);

// Verify
mock.Verify(r => r.AddAsync(It.Is<User>(u => u.Name == "Alice")), Times.Once);
mock.Verify(r => r.DeleteAsync(It.IsAny<int>()), Times.Never);

// Sequence
mock.SetupSequence(r => r.GetByIdAsync(1))
    .ReturnsAsync(new User { Name = "First" })
    .ReturnsAsync(new User { Name = "Second" });
```

## Mocking with NSubstitute

```csharp
var repository = Substitute.For<IUserRepository>();

// Return value
repository.GetByIdAsync(1).Returns(new User { Id = 1, Name = "Test" });

// Verify
await repository.Received(1).AddAsync(Arg.Is<User>(u => u.Name == "Alice"));
await repository.DidNotReceive().DeleteAsync(Arg.Any<int>());
```

## Fixtures (Shared Context)

```csharp
// Class fixture - shared per test class
public class DatabaseFixture : IAsyncLifetime
{
    public AppDbContext Context { get; private set; } = default!;

    public async Task InitializeAsync()
    {
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
        Context = new AppDbContext(options);
        await Context.Database.EnsureCreatedAsync();
    }

    public async Task DisposeAsync()
    {
        await Context.DisposeAsync();
    }
}

public class UserRepositoryTests : IClassFixture<DatabaseFixture>
{
    private readonly AppDbContext _context;

    public UserRepositoryTests(DatabaseFixture fixture)
    {
        _context = fixture.Context;
    }
}

// Collection fixture - shared across test classes
[CollectionDefinition("Database")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture> { }

[Collection("Database")]
public class OrderRepositoryTests { }
```

## FluentAssertions (Optional)

```csharp
// Install: dotnet add package FluentAssertions
result.Should().NotBeNull();
result.Name.Should().Be("Alice");
result.Age.Should().BeGreaterThan(0).And.BeLessThan(150);
users.Should().HaveCount(3).And.OnlyContain(u => u.IsActive);
```

## Anti-Patterns

| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| Testing implementation details | Brittle tests | Test behavior |
| Shared mutable state | Flaky tests | Use fresh fixtures per test |
| No assertion message | Hard to debug | Use descriptive assertions |
| Testing private methods | Coupling to internals | Test through public API |

## Quick Troubleshooting

| Issue | Likely Cause | Solution |
|-------|--------------|----------|
| Test not discovered | Missing `[Fact]`/`[Theory]` | Add test attribute |
| Fixture not shared | Missing `IClassFixture<T>` | Implement fixture interface |
| Mock returns null | Missing setup | Add `.Setup()` for the call |
| Async test deadlock | Missing `async` keyword | Use `async Task` return type |

Wersje

RepozytoriumWynikLicencja
Ta strona · claude-dev-suite/claude-dev-suite95MIT
managedcode/dotnet-skills100MIT
G1Joshi/Agent-Skills100MIT

Migawka bazy z 28.10.2026 · wersja paczki c9fea48f1313 (skrót SHA-256 całej paczki)

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100xunit-nunit
    Projektuje, implementuje i optymalizuje testy jednostkowe i integracyjne .NET w xUnit, NUnit lub MSTest, z mockami i asercjami.
  • 100xunit-test-generator
    Generuje kompletne klasy testów xUnit dla kodu C#/.NET: przypadki brzegowe, testy z parametrami i mockowanie w Moq lub NSubstitute.
  • 95dotnet-testing
    Pisze testy .NET w xUnit z Moq lub NSubstitute, asercjami FluentAssertions i pomiarem pokrycia kodu coverlet.
  • 100dotnet-unit-tests
    Pomaga pisać testy jednostkowe .NET (C#, F#, VB.NET) w xUnit: Fact, Theory z InlineData, fixtury, równoległość, ITestOutputHelper, filtrowanie i dotnet test w CI z raportem trx i pokryciem.
  • 100csharp-xunit
    Pisze, przegląda i refaktoryzuje testy jednostkowe C# z XUnit v3, NSubstitute, FluentAssertions i Atc.Test, według konwencji nazw ClassName_MethodUnderTest_ExpectedBehavior.
  • 100orchardcore-unit-test
    Pisze i uruchamia testy OrchardCore: testy jednostkowe xUnit, integracyjne oparte na SiteContext, mocki Moq i testy funkcjonalne Playwright.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.