Assert an Exception using XUnit

前端 未结 3 1307
天涯浪人
天涯浪人 2020-12-08 00:03

I am a newbie to XUnit and Moq. I have a method which takes string as an argument.How to handle an exception using XUnit.

[Fact]
public void ProfileRepositor         


        
相关标签:
3条回答
  • 2020-12-08 00:21

    If you do want to be rigid about AAA then you can use Record.Exception from xUnit to capture the Exception in your Act stage.

    You can then make assertions based on the captured exception in the Assert stage.

    An example of this can be seen in xUnits tests.

    [Fact]
    public void Exception()
    {
        Action testCode = () => { throw new InvalidOperationException(); };
    
        var ex = Record.Exception(testCode);
    
        Assert.NotNull(ex);
        Assert.IsType<InvalidOperationException>(ex);
    }
    

    It's up to you what path you want to follow, and both paths are fully supported by what xUnit provides.

    0 讨论(0)
  • 2020-12-08 00:23

    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 it's 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);
    
        //...
    }
    
    0 讨论(0)
  • 2020-12-08 00:23

    You could consider something like this if you want to stick to AAA:

    // Act 
    Task act() => handler.Handle(request);
    
    // Assert
    await Assert.ThrowsAsync<MyExpectedException>(act);
    
    0 讨论(0)
提交回复
热议问题