Unit test failing as unable to mock MongoDb Filter Definition using NSubstitute

135 Views Asked by At

Im trying to write a unit test, which will confirm that my mongodb repository's Get document method is working. Current Code:

[Fact]
public async Task GivenExistingDocumentId_WhenGetAsync_ThenDummyProjectionReturnedSuccessfully()
{
    // Arrange
    var documentId = "123idempotentkey";
    var sourceCollection = "testcollection";

    var dummyProjectionDto = new DummyProjectionDto
    {
        IdempotencyKey = "123idempotentkey",
        Description = "test-description"
    };

    // Ensure the filter is properly initialized
    var filter = Builders<DummyProjectionDto>.Filter.Eq("_id", documentId);
    Assert.NotNull(filter);

    var cursor = Substitute.For<IAsyncCursor<DummyProjectionDto>>();
    cursor.Current.Returns(new List<DummyProjectionDto> { dummyProjectionDto });

    // Ensure filter parameter is not null when calling FindAsync
    _mongoCollectionMock.FindAsync(Arg.Is(filter), null, Arg.Any<CancellationToken>()).Returns(cursor);

    // Act
    var result = await _repository.GetAsync(documentId, sourceCollection, default);

    // Assert
    result.Should().NotBeNull();
    result.IdempotencyKey.Should().Be(dummyProjectionDto.IdempotencyKey);
    result.Description.Should().Be(dummyProjectionDto.Description);
}

Error I'm getting:

Message:  System.ArgumentNullException : Value cannot be null. (Parameter 'filter')

Stack Trace:  Ensure.IsNotNull[T](T value, String paramName) IMongoCollectionExtensions.FindAsync[TDocument](IMongoCollection1 collection, FilterDefinition1 filter, FindOptions`2 options, CancellationToken cancellationToken) DummyProjectionRepositoryTests.GivenExistingDocumentId_WhenGetAsync_ThenDummyProjectionReturnedSuccessfully() line 98 --- End of stack trace from previous location ---

I can confirm that the filter object is definitely not null, and the Assertion line passes.

My GetAsync implementation looks like this:

public async Task<DummyProjection> GetAsync(string documentId, string sourceCollection, CancellationToken ct = default)
{
    var filter = Builders<DummyProjectionDto>.Filter.Eq("_id", documentId);

    var result = await _database
        .GetCollection<DummyProjectionDto>(GetCollectionName(sourceCollection))
        .FindAsync(filter, null, ct);

    var projectionDto = await result.SingleOrDefaultAsync(ct);

    if (projectionDto == null)
    {
        throw new MongoException($"Document with ID {documentId} not found.");
    }
    else
    {
        var projectionDocument = new DummyProjection()
        {
            IdempotencyKey = projectionDto.IdempotencyKey,
            Description = projectionDto.Description,
        };

        return projectionDocument;
    }
}

Why is my test throwing an ArgumentNullException for 'filter' when it is not null?

0

There are 0 best solutions below