Moq无法在单元测试中引发异常

时间:2019-09-09 12:04:53

标签: c# .net moq

我有一个Azure功能,可将应用程序设置存储在Azure Blob存储中。为了对获取和添加设置的类进行单元测试,我使用moq使blob存储抽象类(blobStorageRepository)抛出异常。它主要工作。但是,我有两个测试失败。

我还有其他模拟_blobStorageRepository的单元测试。一切正常,包括针对“ Get”方法的测试正确引发了异常,但“ Add”异常测试失败。我已经在下面包含了实际测试

    Fact(DisplayName = "AddUserSettingsAsync - InvalidOperationException")]
    [Trait("Category", "Unit Test")]
    public async Task SettingsStoreAddUserSettingsTestWithException()
    {
        string userObject = Guid.NewGuid().ToString();
        string correlationId = Guid.NewGuid().ToString();

        string body = File.ReadAllText("TestData/userSettings.json");
        UserSettingsObject userSettingsObject = JsonConvert.DeserializeObject<UserSettingsObject>(body);

        var iFunctionEnvironment = TestHelpers.GetEnvironmentVariable("Test");

        Uri.TryCreate("http://localhost", UriKind.Absolute, out Uri uri);

        var iblobStorageRepositoryMoq = new Mock<IBlobStorageRepository>();
        iblobStorageRepositoryMoq
            .Setup(mock => mock.Add(logger, correlationId, body, userObject))
            .ThrowsAsync(new Exception("Function Add threw an exception"));

        var iblobStorageRepository = iblobStorageRepositoryMoq.Object;

        SettingsStore settingsStore = new SettingsStore(iFunctionEnvironment, iblobStorageRepository);

        Exception exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await settingsStore.AddUserSettingsAsync(logger, correlationId, userSettingsObject, userObject));
        Assert.Equal("Function Add threw an exception", exception.Message);
        Assert.Null(exception.InnerException);
    }

这是blogStoreRepository的界面:

Task<bool> Add(ILogger logger, string correlationId, string settingsObject, string settingsObjectName);

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

如果调用的模拟程序的行为不符合预期,通常是因为设置与实际调用的设置不匹配。

考虑使用It.IsAny<T>()

放宽期望
Fact(DisplayName = "AddUserSettingsAsync - InvalidOperationException")]
[Trait("Category", "Unit Test")]
public async Task SettingsStoreAddUserSettingsTestWithException() {
    //Arrange
    string userObject = Guid.NewGuid().ToString();
    string correlationId = Guid.NewGuid().ToString();

    string body = File.ReadAllText("TestData/userSettings.json");
    UserSettingsObject userSettingsObject = JsonConvert.DeserializeObject<UserSettingsObject>(body);

    var iFunctionEnvironment = TestHelpers.GetEnvironmentVariable("Test");

    Uri.TryCreate("http://localhost", UriKind.Absolute, out Uri uri);

    var iblobStorageRepositoryMoq = new Mock<IBlobStorageRepository>();
    iblobStorageRepositoryMoq
        .Setup(mock => mock.Add(It.IsAny<ILogger>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
        .ThrowsAsync(new InvalidOperationException("Function Add threw an exception"));

    //The SUT
    var subjectUnderTest = new SettingsStore(iFunctionEnvironment, iblobStorageRepositoryMoq.Object);

    //Act
    InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(() => subjectUnderTest.AddUserSettingsAsync(logger, correlationId, userSettingsObject, userObject));

    //Assert
    Assert.Equal("Function Add threw an exception", exception.Message);
    Assert.Null(exception.InnerException);
}

请注意对设置的更改,并且如果断言已抛出InvalidOperationException,则模拟实际上应该抛出InvalidOperationException

//...

var iblobStorageRepositoryMoq = new Mock<IBlobStorageRepository>();
iblobStorageRepositoryMoq
    .Setup(mock => mock.Add(It.IsAny<ILogger>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
    .ThrowsAsync(new InvalidOperationException("Function Add threw an exception"));

//...