Skip to content

Latest commit

 

History

History
104 lines (84 loc) · 3.59 KB

File metadata and controls

104 lines (84 loc) · 3.59 KB
name testing-patterns-dotnet
summary Testing Couchbase .NET applications — unit testing with Moq, integration testing with Testcontainers.Couchbase, scope/collection isolation
description Testing Couchbase .NET applications — unit testing with Moq, integration testing with Testcontainers.Couchbase, scope/collection isolation
compatibility .NET SDK 3.x. xUnit + Moq + Testcontainers.Couchbase.
metadata
last_verified min_server_version handoff
2026-05
7.0
condition skill
user asks about testing concepts or strategy
testing-patterns
condition skill
user asks about connection setup or SDK configuration
server-connection-dotnet

Testing Couchbase .NET Applications

Unit Testing

Mock ICouchbaseCollection using Moq. Install: dotnet add package Moq.

using Moq;
using Couchbase.KeyValue;
using Xunit;

public class UserRepositoryTests
{
    [Fact]
    public async Task GetUser_ReturnsCorrectDocument()
    {
        var mockCollection = new Mock<ICouchbaseCollection>();
        var mockResult = new Mock<IGetResult>();
        mockResult.Setup(r => r.ContentAs<User>()).Returns(new User { Name = "Alice" });
        mockCollection.Setup(c => c.GetAsync("user::alice", null))
                      .ReturnsAsync(mockResult.Object);

        var repo = new UserRepository(mockCollection.Object);
        var user = await repo.GetUserAsync("user::alice");

        Assert.Equal("Alice", user.Name);
    }
}

See shared mock examples for the full pattern reference.

Integration Testing with testcontainers

Install: dotnet add package Testcontainers.Couchbase

using Testcontainers.Couchbase;
using Xunit;

public class OrderRepositoryTests : IAsyncLifetime
{
    private readonly CouchbaseContainer _container = new CouchbaseBuilder()
        .WithImage("couchbase/server:7.6")
        .Build();

    public Task InitializeAsync() => _container.StartAsync();
    public Task DisposeAsync() => _container.DisposeAsync().AsTask();

    [Fact]
    public async Task UpsertAndGet_Works()
    {
        var cluster = await Cluster.ConnectAsync(
            _container.GetConnectionString(),
            new ClusterOptions().WithCredentials(_container.Username, _container.Password)
        );
        var col = (await cluster.BucketAsync("default")).DefaultCollection();
        await col.UpsertAsync("order::1", new { status = "pending" });
        var result = await col.GetAsync("order::1");
        Assert.Equal("pending", result.ContentAs<dynamic>().status.ToString());
    }
}

Scope/Collection Isolation

private static string _testScope;

public static async Task CreateScopeAsync(IBucket bucket)
{
    _testScope = $"test_{Guid.NewGuid():N}".Substring(0, 16);
    var mgr = bucket.Collections;
    await mgr.CreateScopeAsync(_testScope);
    await mgr.CreateCollectionAsync(new CollectionSpec(_testScope, "orders"));
}

public static async Task DropScopeAsync(IBucket bucket)
    => await bucket.Collections.DropScopeAsync(_testScope);

Common Errors in Tests

Error Likely cause in tests Fix
DocumentNotFoundException Key not seeded before test Seed data in InitializeAsync
BucketNotFoundException Test bucket not created Use default bucket or create in container setup
UnambiguousTimeoutException Container not ready Call await cluster.WaitUntilReadyAsync(TimeSpan.FromSeconds(10))
AuthenticationFailureException Wrong test credentials Use _container.Username/Password