c# - 使用 XUnit 断言异常

标签 c# unit-testing xunit

我是 XUnit 和 Moq 的新手。我有一个将字符串作为参数的方法。如何使用 XUnit 处理异常。

[Fact]
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() {
    //arrange
    ProfileRepository profiles = new ProfileRepository();
    //act
    var result = profiles.GetSettingsForUserID("");
    //assert
    //The below statement is not working as expected.
    Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID(""));
}

待测方法

public IEnumerable<Setting> GetSettingsForUserID(string userid)
{            
    if (string.IsNullOrWhiteSpace(userid)) throw new ArgumentException("User Id Cannot be null");
    var s = profiles.Where(e => e.UserID == userid).SelectMany(e => e.Settings);
    return s;
}

最佳答案

Assert.Throws expression 将捕获异常并断言类型。但是,您在断言表达式之外调用被测方法,因此测试用例失败。

[Fact]
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException()
{
    //arrange
    ProfileRepository profiles = new ProfileRepository();
    // act & assert
    Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID(""));
}

如果一心想遵循 AAA,您可以将操作提取到它自己的变量中。

[Fact]
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException()
{
    //arrange
    ProfileRepository profiles = new ProfileRepository();
    //act
    Action act = () => profiles.GetSettingsForUserID("");
    //assert
    ArgumentException exception = Assert.Throws<ArgumentException>(act);
    //The thrown exception can be used for even more detailed assertions.
    Assert.Equal("expected error message here", exception.Message);
}

注意异常如何也可以用于更详细的断言

如果异步测试,Assert.ThrowsAsync与前面给出的示例类似,除了应等待断言,

public async Task Some_Async_Test() {

    //...

    //Act
    Func<Task> act = () => subject.SomeMethodAsync();

    //Assert
    var exception = await Assert.ThrowsAsync<InvalidOperationException>(act);

    //...
}

关于c# - 使用 XUnit 断言异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45017295/

相关文章:

javascript - 用于 bool 检查的 Razor 语法

unit-testing - Moq - 测试 Controller 方法是否抛出异常

debugging - 在 Visual Studio 2015 中调试期间缺少局部变量

testing - junit报表可视化工具

c# - 找到与请求匹配的多个操作

c# - WCF RESTFul 服务 - 404 端点未找到 2 个服务

c# - Linq to SQL、SQL Server 2008 和优化

java - 如何测试使用查找的 NetBeans 平台代码?

c# - 单元测试纯领域驱动类

unit-testing - 从TFS2010运行xUnit测试