visit
string testString = "hello";
string expectedOutput = testString.ToUpper();
Assert.Equal(expectedOutput, "HELLO");
string testString = "hello";
string expectedOutput = testString.ToUpper();
expectedOutput.Should().Be("HELLO");
public class ShoppingListGenerator
{
public static List<Item> GenerateItems()
{
return new List<Item>
{
new Item
{
Name = "Apple",
Quantity = 5
},
new Item
{
Name = "Banana",
Quantity = 1
},
new Item
{
Name = "Orange",
Quantity = 3
}
};
}
}
public class ShoppingListGeneratorShould
{
[Fact]
public void MultipleAssertions()
{
var testShoppingList = ShoppingListGenerator.GenerateItems();
testShoppingList.Should().NotBeNullOrEmpty();
testShoppingList.Should().Contain(new Item { Name = "Cheese", Quantity = 2 });
testShoppingList.Should().HaveCount(10);
testShoppingList.Should().OnlyHaveUniqueItems();
}
}
This approach is fine, but looking at our code, we can see that this test would fail on the assertion that our list will fail on the. Contain()
method, since we don't have an item in our list that contains Cheese. This test would also fail on our. HaveCount()
method, since we have only 3 items in our list, not 10.
We were correct! But in this example, not only has our test failed against our .Contains()
method, but it has stopped running our test!
using AssertionScopes;
using FluentAssertions;
using FluentAssertions.Execution;
using System;
using Xunit;
namespace Tests
{
public class ShoppingListGeneratorShould
{
[Fact]
public void MultipleAssertions()
{
var testShoppingList = ShoppingListGenerator.GenerateItems();
using (new AssertionScope())
{
testShoppingList.Should().NotBeNullOrEmpty();
testShoppingList.Should().Contain(new Item { Name = "Cheese", Quantity = 2 });
testShoppingList.Should().HaveCount(10);
testShoppingList.Should().OnlyHaveUniqueItems();
}
}
}
}
Our test has failed, but here we now get both exceptions thrown back to us!
Message:
Expected testShoppingList {AssertionScopes.Item
{
Name = "Apple"
Quantity = 5
}, AssertionScopes.Item
{
Name = "Banana"
Quantity = 1
}, AssertionScopes.Item
{
Name = "Orange"
Quantity = 3
}} to contain
AssertionScopes.Item
{
Name = "Cheese"
Quantity = 2
}.
Expected testShoppingList to contain 10 item(s), but found 3.
Also published on: