簡體   English   中英

使用 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.Z3A580F142203677F1FZBC3098.

信用: @MatiasQuaranta

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM