为了单独对该方法进行单元测试,需要模拟被测类的依赖关系。
假设如下示例
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