由于没有用于测试 CosmosDb 的文档,因此我正在尝试自己进行测试,但我无法做到。例如,我想测试一个如下所示的插入方法:
public async Task AddSignalRConnectionAsync(ConnectionData connection)
{
if (connection != null)
{
await this.container.CreateItemAsync<ConnectionData>(connection, new PartitionKey(connection.ConnectionId));
}
}
我需要做的是测试这个方法是否成功地在 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);
}
}
}
在上面的例子中,被测方法依赖于
Container
和 ConnectionData
,测试时需要提供。除非你想击中
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
}
根据上述孤立的单元测试示例,可以验证被测主题方法在参数不为空时会调用预期的方法。
使用真实
Container
将使其成为集成测试,这将需要不同类型的测试安排。您还可以在此处查看开发人员如何对 SDK 进行单元测试
https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests
信用:@MatiasQuaranta
关于c# - 使用 Moq 对 cosmosDb 方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768313/