使用 Moq 对 cosmosDb 方法进行单元测试

Unit test cosmosDb methods using Moq

由于没有测试 CosmosDb 的文档,我想自己做,但我做起来有困难。例如,我想测试一个如下所示的插入方法:

public async Task AddSignalRConnectionAsync(ConnectionData connection)
{
    if (connection != null)
    {
        await this.container.CreateItemAsync<ConnectionData>(connection, new PartitionKey(connection.ConnectionId));
    }
}

我需要做的是测试此方法是否成功地在 cosmosDb 上创建了一个项目,或者至少伪造了一个成功的创建。 我该如何测试?

为了单独对该方法进行单元测试,需要模拟被测 class 的依赖关系。

假设如下示例

public class MySubjectClass {
    private readonly Container container;

    public MySubjectClass(Container container) {
        this.container = container;
    }

    public async Task AddSignalRConnectionAsync(ConnectionData connection) {
        if (connection != null) {
            var partisionKey = new PartitionKey(connection.ConnectionId);
            await this.container.CreateItemAsync<ConnectionData>(connection, partisionKey);
        }
    }        
}

上面例子中,被测方法依赖ContainerConnectionData,测试时需要提供

除非您想点击 Container 的实际实例,否则建议模拟依赖项,如果使用实际实现,这些依赖项可能会产生不良行为。

public async Task Should_CreateItemAsync_When_ConnectionData_NotNull() {
    //Arrange
    //to be returned by the called mock
    var responseMock = new Mock<ItemResponse<ConnectionData>>();

    //data to be passed to the method under test
    ConnectionData data = new ConnectionData {
        ConnectionId = "some value here"
    };

    var containerMock = new Mock<Container>();
    //set the mock expected behavior
    containerMock
        .Setup(_ => _.CreateItemAsync<ConnectionData>(
            data, 
            It.IsAny<PartitionKey>(), 
            It.IsAny<ItemRequestOptions>(),
            It.IsAny<CancellationToken())
        )
        .ReturnsAsync(responseMock.Object)
        .Verifiable();

    var subject = new MySubjectClass(containerMock.Object);

    //Act
    await subject.AddSignalRConnectionAsync(data);

    //Assert
    containerMock.Verify(); //verify expected behavior
}

根据上述孤立的单元测试示例,可以验证被测对象方法在参数不为null时会调用预期的方法。

使用真实的 Container 会使这成为一个集成测试,这将需要不同类型的测试安排。

您还可以在此处查看开发人员如何对 SDK 进行单元测试

https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests

来源:@MatiasQuaranta