Skip to main content

Lesson 8 of 8

Mini Project: Full Test Suite for Blog API

Write a complete test suite for the Blog API from Module 5: unit tests for PostService (with Moq), integration tests for PostsController (with WebApplicationFactory), FluentAssertions throughout, TestContainers for slug uniqueness constraint test, and builder pattern for test data.

45 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Quick Quiz - Testing with xUnit, Moq & Integration Tests

Complete Blog API Test Suite

Complete Blog API Test Suite
// ━━ Unit tests - PostService ━━
public class PostServiceUnitTests
{
    private readonly Mock<IPostRepository> _postRepo = new();
    private readonly Mock<IPublisher> _publisher = new();

    [Fact]
    public async Task CreatePost_ValidRequest_ReturnsSuccessWithSlug()
    {
        var request = new CreatePostRequest("My First Post", "Content here", null, Guid.NewGuid());
        var expectedSlug = "my-first-post";

        _postRepo.Setup(r => r.SlugExistsAsync(expectedSlug, It.IsAny<CancellationToken>()))
            .ReturnsAsync(false);

        var service = new PostService(_postRepo.Object, _publisher.Object);
        var result = await service.CreateAsync(request, CancellationToken.None);

        result.IsSuccess.Should().BeTrue();
        result.Value!.Slug.Should().Be(expectedSlug);
        _postRepo.Verify(r => r.Add(It.Is<Post>(p => p.Slug == expectedSlug)), Times.Once);
    }

    [Fact]
    public async Task CreatePost_DuplicateSlug_AppendsUniqueId()
    {
        var request = new CreatePostRequest("Duplicate Post", "Content", null, Guid.NewGuid());
        _postRepo.SetupSequence(r => r.SlugExistsAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync(true)   // first slug taken
            .ReturnsAsync(false); // with suffix: available

        var service = new PostService(_postRepo.Object, _publisher.Object);
        var result = await service.CreateAsync(request, CancellationToken.None);

        result.IsSuccess.Should().BeTrue();
        result.Value!.Slug.Should().StartWith("duplicate-post-");
    }
}

// ━━ Integration test - full HTTP round trip ━━
public class PostsApiIntegrationTests(ApiWebApplicationFactory factory)
    : IClassFixture<ApiWebApplicationFactory>
{
    private readonly HttpClient _client = factory.CreateClient();

    [Fact]
    public async Task GET_Post_BySlug_ExistingPost_Returns200()
    {
        using var scope = factory.Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<BlogDbContext>();
        var post = new PostBuilder().Published().WithSlug("test-slug").Build();
        db.Posts.Add(post);
        await db.SaveChangesAsync();

        var response = await _client.GetAsync("/api/posts/test-slug");
        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
        var body = await response.Content.ReadFromJsonAsync<PostDto>();
        body!.Slug.Should().Be("test-slug");
    }
}

// ━━ PostBuilder ━━
public class PostBuilder
{
    private bool _published = false;
    private string _slug = "test-post";
    public PostBuilder Published() { _published = true; return this; }
    public PostBuilder WithSlug(string slug) { _slug = slug; return this; }
    public Post Build() => new() { Id = Guid.NewGuid(), Title = "Test", Slug = _slug, Content = "Content", IsPublished = _published, PublishedAt = _published ? DateTime.UtcNow : null };
}

// Stub types
record CreatePostRequest(string Title, string Content, string? Summary, Guid AuthorId);
class Post { public Guid Id { get; set; } public string Title { get; set; } = ""; public string Slug { get; set; } = ""; public string Content { get; set; } = ""; public bool IsPublished { get; set; } public DateTime? PublishedAt { get; set; } }
record PostDto(Guid Id, string Slug, string Title);
record Result<T>(bool IsSuccess, T? Value = default) { public static Result<T> Success(T v) => new(true, v); }
class PostService { public PostService(IPostRepository r, IPublisher p) { } public Task<Result<PostDto>> CreateAsync(CreatePostRequest r, CancellationToken ct) => Task.FromResult(Result<PostDto>.Success(new PostDto(Guid.NewGuid(), r.Title.ToLower().Replace(" ", "-"), r.Title))); }
interface IPostRepository { Task<bool> SlugExistsAsync(string slug, CancellationToken ct); void Add(Post p); }
interface IPublisher { }
class BlogDbContext { public System.Collections.Generic.List<Post> Posts { get; set; } = []; public Task<int> SaveChangesAsync() => Task.FromResult(0); }

Tip

Tip

Practice Mini Project Full Test Suite for Blog API in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Full Test Suite for Blog API from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Full Test Suite for Blog API is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done