Best approach to using the Arrange-Act-Assert pattern while waiting for an exception

I'm trying to follow the Arrange-Act-Assert pattern when writing a unit test, and I got to the point of being confused, which approach would be better. I am using xUnit, and my first approach to the problem is:

//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:

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

board.Add(key, value);

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

which is better suited?

Edit: This was reported at wp.me/p4f69l-3z

+4
source share
5 answers

Your first challenge .Addshould really be part of the organization. Think of it as a precondition / setting for an action. In addition, you can wrap the action in Actionto 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 , , :

int key = 1;
string value = "X";
board.Add(key, value);

Action addingSameKeySecondTime = () => board.Add(key, value);

addingSameKeySecondTime.ShouldThrow<ArgumentException>();
+4

, AAA . : Heleonix.Testing , JavaScript Jasmine/Jest Given/When/Then AAA.

+1

, . Assert.Throws / , . "" , :

[Test]
public void SomeMethod_NullSomething_ShouldThrow() {
    var something = MakeTarget();

    Assert.Throws<ArgumentNullException>(() => something.SomeMethod(null));
}
0

... , , . , add ( NUnit):

// Arrange
int key = 1;
var eventFired = false;
board.Added += (boardItem) => {
    eventFired = boardItem.key == key;
};

// Act
board.Add(key, "X");

// Assert
Assert.That(eventFired, Is.True);

, :

// Arrange
int key = 1;    
var exceptionRaised = false;
board.Add(key, "X");

// Act
try {
    board.Add(key, "X");
}
catch(InvalidOperationException ex) {
    exceptionRaised = true;
}

// Assert
Assert.That(exceptionRaised, Is.True);

, Assert.Throws , AAA. , AAA , , .

0

// Arrange
int key = 1;
string value = "X";
board.Add(key, value);

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

, ASP.NET MVC (, https://aspnetwebstack.codeplex.com/SourceControl/latest#test/Common/PrefixContainerTest.cs)

0

Source: https://habr.com/ru/post/1543475/


All Articles