Search code examples
c#unit-testingxunit.netarrange-act-assert

Best approach towards applying the Arrange-Act-Assert pattern when expecting exception


I'm trying to follow the Arrange-Act-Assert pattern when writing unit test and I got to a point where I'm confused on which approach will be better. I'm using xUnit and my first approach to the problem was:

//Arrange
int key = 1;
string value = "X";

//Act
board.Add(key, value);
var result = Assert.Throws<ArgumentException>(() => board.Add(key, value));

//Assert
Assert.IsType<ArgumentException>(result);

and my second approach is:

int key = 1;
string value = "X";

board.Add(key, value);

Assert.Throws<ArgumentException>(() => board.Add(key, value));

which is a better approach?

Edit: Blogged about this on wp.me/p4f69l-3z


Solution

  • Your first .Add call should be really part of arrange. Treat it as precondition/setup for act. Other than that you can wrap act in Action to make it read better:

    //Arrange
    int key = 1;
    string value = "X";
    board.Add(key, value);
    
    //Act
    Action addingSameKeySecondTime = () => board.Add(key, value);
    
    //Assert
    Assert.Throws<ArgumentException>(addingSameKeySecondTime)
    

    FluentAssertions library mentioned in comments makes such asserts even more sentence-alike:

    int key = 1;
    string value = "X";
    board.Add(key, value);
    
    Action addingSameKeySecondTime = () => board.Add(key, value);
    
    addingSameKeySecondTime.ShouldThrow<ArgumentException>();