我正在尝试为类编写测试,似乎我无法设置我的 CheckLoginAsync 方法。此 CheckLoginAsync 方法有2个参数。第二个参数是可选的,如下所示:
public async Task CheckLoginAsync(ISettings userSettings, CancellationToken? cancellationToken = null);
设置代码如下:
backendFacadeMock = new Mock<BackendFacade>(MockBehavior.Strict);
backendFacadeMock
.Setup(bf => bf.Initialize())
.Returns(() => Task.FromResult(0));
backendFacadeMock
.Setup(bf => bf.CheckLoginAsync(It.IsAny<ISettings>(), It.IsAny<CancellationToken?>()))
.Returns(() => Task.FromResult(0));
nullBackendFacadeMock = new Mock<IBackendFacade>(MockBehavior.Strict);
backendFacadeFactoryMock = new Mock<IBackendFacadeFactory>(MockBehavior.Strict);
backendFacadeFactoryMock
.Setup(bf => bf.CreateBackendFacade())
.Returns(() => backendFacadeMock.Object);
backendFacadeFactoryMock
.Setup(bf => bf.CreateNullBackendFacade())
.Returns(() => nullBackendFacadeMock.Object);
正在测试的代码如下:
private async Task<IBackendFacade> CreateBackendFacade()
{
IBackendFacade backendFacade = _backendFacadeFactory.CreateBackendFacade();
try
{
await backendFacade.CheckLoginAsync(_userSettings);
await backendFacade.Initialize();
}
catch (Exception e)
{
backendFacade = _backendFacadeFactory.CreateNullBackendFacade();
}
return backendFacade;
}
上述代码中的 CheckLoginAsync 调用会引发以下异常:
IBackendFacade.CheckLoginAsync(Mock<de.cas.officeintegration.outlook.core.application.ISettings:00000001>.Object, null) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
测试本身:
[Test]
public async Task GetBackendFacadeAsync_NoException_ReturnsABackendFacadeObject()
{
var backendFacadeProvider = new BackendFacadeProvider(backendFacadeFactoryMock.Object, userSettingsMock.Object);
IBackendFacade backendFacade = await backendFacadeProvider.GetBackendFacadeAsync();
Assert.AreSame(backendFacadeMock.Object, backendFacade);
}
提前致谢!