为了单独对该方法进行单元测试,需要模拟被测类的依赖项。
假设像下面的例子
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
}
根据上述隔离的单元测试示例,可以验证被测对象方法在参数不为null时将调用预期方法。
使用真实的Container
将使它成为集成测试,这将需要另一种测试安排。
本文链接:https://www.f2er.com/3137295.html