使用Moq的单元测试cosmosDb方法

因为没有测试CosmosDb的文档,所以我想自己做,但是这样做很麻烦。例如,我想测试一个如下所示的插入方法:

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

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

alanpiter 回答:使用Moq的单元测试cosmosDb方法

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

假设像下面的例子

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将使它成为集成测试,这将需要另一种测试安排。

本文链接:https://www.f2er.com/3137295.html

大家都在问