zoukankan      html  css  js  c++  java
  • Assert an Exception using XUnit

    Assert an Exception using XUnit

    回答1

    The Assert.Throws expression will catch the exception and assert the type. You are however calling the method under test outside of the assert expression and thus failing the test case.

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

    If bent on following AAA you can extract the action into its own variable.

    [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);
    }
    

    Note how the exception can also be used for more detailed assertions

    If testing asynchronously, Assert.ThrowsAsync follows similarly to the previously given example, except that the assertion should be awaited,

    public async Task Some_Async_Test() {
    
        //...
    
        //Act
        Func<Task> act = () => subject.SomeMethodAsync();
    
        //Assert
        var exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
    
        //...
    }
    

    回答2

  • 相关阅读:
    beta冲刺1
    凡事预则立-于Beta冲刺前
    SDN第二次作业
    事后诸葛亮(团队)
    SDN第一次上机作业
    冲刺总结随笔
    Alpha第三天
    Alpha第二天
    Alpha冲刺博客集
    项目需求分析(团队)
  • 原文地址:https://www.cnblogs.com/chucklu/p/15573732.html
Copyright © 2011-2022 走看看