Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

api-integration-testing

БесплатноБез исполняемых скриптовНе проверен

Integration testing patterns for ABP Framework APIs using xUnit and WebApplicationFactory. Use when: (1) testing API endpoints end-to-end, (2) verifying HTTP…

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

API Integration Testing

Test ABP Framework APIs end-to-end using xUnit and WebApplicationFactory.

When to Use

  • Testing API endpoints with real HTTP requests
  • Verifying authorization and authentication
  • Testing request/response serialization
  • End-to-end flow validation
  • Database integration testing

Test Project Setup

Project Structure

test/
├── [Module].HttpApi.Tests/
│   ├── [Module]HttpApiTestBase.cs
│   ├── [Module]HttpApiTestModule.cs
│   ├── Controllers/
│   │   ├── PatientControllerTests.cs
│   │   └── DoctorControllerTests.cs
│   └── TestData/
│       └── TestDataSeeder.cs

Test Base Class

public abstract class ClinicHttpApiTestBase : AbpIntegratedTest<ClinicHttpApiTestModule>
{
    protected HttpClient Client { get; }
    protected IServiceProvider Services => ServiceProvider;

    protected ClinicHttpApiTestBase()
    {
        Client = GetHttpClient();
    }

    protected HttpClient GetHttpClient()
    {
        var factory = new WebApplicationFactory<Program>()
            .WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    // Replace database with in-memory
                    services.RemoveAll<DbContextOptions<ClinicDbContext>>();
                    services.AddDbContext<ClinicDbContext>(options =>
                        options.UseInMemoryDatabase("TestDb"));
                });
            });

        return factory.CreateClient();
    }

    protected async Task AuthenticateAsAsync(string username, string[] permissions = null)
    {
        // Set authentication headers
        var token = GenerateTestToken(username, permissions);
        Client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);
    }

    protected async Task<T> GetAsync<T>(string url)
    {
        var response = await Client.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<T>();
    }

    protected async Task<HttpResponseMessage> PostAsync<T>(string url, T content)
    {
        return await Client.PostAsJsonAsync(url, content);
    }
}

Test Module Configuration

[DependsOn(
    typeof(ClinicHttpApiModule),
    typeof(AbpAspNetCoreTestBaseModule)
)]
public class ClinicHttpApiTestModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        // Configure test-specific services
        context.Services.AddSingleton<ICurrentUser, TestCurrentUser>();
    }
}

Common Test Patterns

CRUD Endpoint Tests

public class PatientControllerTests : ClinicHttpApiTestBase
{
    private const string BaseUrl = "/api/app/patients";

    #region GetList

    [Fact]
    public async Task GetList_ReturnsPagedResult()
    {
        // Act
        var response = await Client.GetAsync(BaseUrl);

        // Assert
        response.StatusCode.ShouldBe(HttpStatusCode.OK);

        var result = await response.Content
            .ReadFromJsonAsync<PagedResultDto<PatientDto>>();
        result.ShouldNotBeNull();
        result.Items.ShouldNotBeNull();
    }

    [Fact]
    public async Task GetList_WithFilter_ReturnsFilteredResults()
    {
        // Act
        var response = await Client.GetAsync($"{BaseUrl}?filter=John");

        // Assert
        response.StatusCode.ShouldBe(HttpStatusCode.OK);
        var result = await response.Content
            .ReadFromJsonAsync<PagedResultDto<PatientDto>>();
        result.Items.ShouldAllBe(p => p.Name.Contains("John"));
    }

    [Fact]
    public async Task GetList_WithPagination_RespectsLimits()
    {
        // Act
        var response = await Client.GetAsync($"{BaseUrl}?skipCount=0&maxResultCount=5");

        // Assert
        var result = await response.Content
            .ReadFromJsonAsync<PagedResultDto<PatientDto>>();
        result.Items.Count.ShouldBeLessThanOrEqualTo(5);
    }

    #endregion

    #region Get

    [Fact]
    public async Task Get_ExistingId_ReturnsPatient()
    {
        // Arrange
        var patientId = TestData.PatientId;

        // Act
        var response = await Client.GetAsync($"{BaseUrl}/{patientId}");

        // Assert
        response.StatusCode.ShouldBe(HttpStatusCode.OK);
        var patient = await response.Content.ReadFromJsonAsync<PatientDto>();
        patient.Id.ShouldBe(patientId);
    }

    [Fact]
    public async Task Get_NonExistingId_Returns404()
    {
        // Act
        var response = await Client.GetAsync($"{BaseUrl}/{Guid.NewGuid()}");

        // Assert
        response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
    }

    #endregion

    #region Create

    [Fact]
    public async Task Create_ValidInput_Returns201WithEntity()
    {
        // Arrange
        var input = new CreatePatientDto
        {
            Name = "Jane Doe",
            Email = "[email protected]",
            DateOfBirth = new Date
Полный SKILL.md на GitHub

Установить api-integration-testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

metadata.json

FAQ

Что делает скилл api-integration-testing?

Integration testing patterns for ABP Framework APIs using xUnit and WebApplicationFactory. Use when: (1) testing API endpoints end-to-end, (2) verifying HTTP status codes and responses, (3) testing authorization, (4) database integration tests.

Как установить скилл api-integration-testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл api-integration-testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить api-integration-testing с