From d53e8d996fcfb9141a89ebf8230115aebe5263fd Mon Sep 17 00:00:00 2001 From: ITaluone <44049228+ITaluone@users.noreply.github.com> Date: Tue, 5 Apr 2022 12:41:57 +0200 Subject: [PATCH 01/48] Delete unused Guard to improve code coverage (#1871) --- Src/FluentAssertions/Common/Guard.cs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Src/FluentAssertions/Common/Guard.cs b/Src/FluentAssertions/Common/Guard.cs index fdfb97520b..c6e2e4c15b 100644 --- a/Src/FluentAssertions/Common/Guard.cs +++ b/Src/FluentAssertions/Common/Guard.cs @@ -55,14 +55,6 @@ public static void ThrowIfArgumentContainsNull(IEnumerable values, string } } - public static void ThrowIfArgumentContainsNull(IEnumerable values, string paramName, string message) - { - if (values.Any(t => t is null)) - { - throw new ArgumentNullException(paramName, message); - } - } - public static void ThrowIfArgumentIsEmpty(IEnumerable values, string paramName, string message) { if (!values.Any()) From 5493e44d9811d964f0e8156b883f2dd7ec1ccabf Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger | alu-one Date: Wed, 30 Mar 2022 13:15:55 +0200 Subject: [PATCH 02/48] Fix codestyle issue `IDE0019` --- .../Equivalency/MultiDimensionalArrayEquivalencyStep.cs | 3 +-- .../Equivalency/Steps/DataSetEquivalencyStep.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs index 963b092868..15b6692b64 100644 --- a/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/MultiDimensionalArrayEquivalencyStep.cs @@ -13,8 +13,7 @@ internal class MultiDimensionalArrayEquivalencyStep : IEquivalencyStep { public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator) { - Array expectationAsArray = comparands.Expectation as Array; - if (expectationAsArray is null || expectationAsArray?.Rank == 1) + if (comparands.Expectation is not Array expectationAsArray || expectationAsArray?.Rank == 1) { return EquivalencyResult.ContinueWithNext; } diff --git a/Src/FluentAssertions/Equivalency/Steps/DataSetEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/DataSetEquivalencyStep.cs index 209b5c815f..3cdde14384 100644 --- a/Src/FluentAssertions/Equivalency/Steps/DataSetEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/DataSetEquivalencyStep.cs @@ -11,9 +11,8 @@ public class DataSetEquivalencyStep : EquivalencyStep protected override EquivalencyResult OnHandle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator) { var subject = comparands.Subject as DataSet; - var expectation = comparands.Expectation as DataSet; - if (expectation is null) + if (comparands.Expectation is not DataSet expectation) { if (subject is not null) { From 8d9a38350f33d9e8cd8900185fc7589710197b62 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger | alu-one Date: Wed, 30 Mar 2022 13:32:30 +0200 Subject: [PATCH 03/48] Fix codestyle issue `IDE0055` --- .../Matching/MappedPathMatchingRule.cs | 2 +- ...elfReferenceEquivalencyAssertionOptions.cs | 2 +- .../CollectionSpecs.cs | 34 ++++++++++++------- .../MemberMatchingSpecs.cs | 8 ++--- .../NestedPropertiesSpecs.cs | 15 +++++--- Tests/UWP.Specs/Properties/AssemblyInfo.cs | 4 +-- 6 files changed, 40 insertions(+), 25 deletions(-) diff --git a/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs b/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs index d710ac0e98..b7b45812b7 100644 --- a/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs +++ b/Src/FluentAssertions/Equivalency/Matching/MappedPathMatchingRule.cs @@ -40,7 +40,7 @@ public IMember Match(IMember expectedMember, object subject, INode parent, IEqui { path = path.WithCollectionAsRoot(); } - + if (path.IsEquivalentTo(expectedMember.PathAndName)) { var member = MemberFactory.Find(subject, subjectPath.MemberName, expectedMember.Type, parent); diff --git a/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs b/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs index ac095d0df7..8fa4a6cfa7 100644 --- a/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs +++ b/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs @@ -811,7 +811,7 @@ private void RemoveSelectionRule() { selectionRules.RemoveAll(selectionRule => selectionRule is T); } - + protected TSelf AddSelectionRule(IMemberSelectionRule selectionRule) { selectionRules.Add(selectionRule); diff --git a/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs index d9346d4fa4..6e228e27d1 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs @@ -350,12 +350,14 @@ public void var logbookEntry = new LogbookEntryProjection { - Logbook = logbook, LogbookRelations = new[] { new LogbookRelation { Logbook = logbook } } + Logbook = logbook, + LogbookRelations = new[] { new LogbookRelation { Logbook = logbook } } }; var equivalentLogbookEntry = new LogbookEntryProjection { - Logbook = logbook, LogbookRelations = new[] { new LogbookRelation { Logbook = logbook } } + Logbook = logbook, + LogbookRelations = new[] { new LogbookRelation { Logbook = logbook } } }; // Act @@ -748,7 +750,9 @@ public void When_all_subject_items_are_equivalent_to_expectation_object_it_shoul // Act Action action = () => subject.Should().AllBeEquivalentTo(new { - Name = "someDto", Age = 1, Birthdate = default(DateTime) + Name = "someDto", + Age = 1, + Birthdate = default(DateTime) }); // Assert @@ -768,9 +772,11 @@ public void When_all_subject_items_are_equivalent_to_expectation_object_it_shoul // Act Action action = () => subject.Should().AllBeEquivalentTo(new - { - Name = "someDto", Age = 1, Birthdate = default(DateTime) - }) + { + Name = "someDto", + Age = 1, + Birthdate = default(DateTime) + }) .And.HaveCount(3); // Assert @@ -1108,12 +1114,14 @@ public void When_nested_objects_are_excluded_from_collections_it_should_use_simp // Arrange var actual = new MyObject { - MyString = "identical string", Child = new ClassIdentifiedById { Id = 1, MyChildString = "identical string" } + MyString = "identical string", + Child = new ClassIdentifiedById { Id = 1, MyChildString = "identical string" } }; var expectation = new MyObject { - MyString = "identical string", Child = new ClassIdentifiedById { Id = 1, MyChildString = "DIFFERENT STRING" } + MyString = "identical string", + Child = new ClassIdentifiedById { Id = 1, MyChildString = "DIFFERENT STRING" } }; IList actualList = new List { actual }; @@ -1478,7 +1486,7 @@ public void When_the_length_of_the_first_dimension_differs_between_the_arrays_it public void When_the_number_of_dimensions_of_the_arrays_are_not_the_same_it_should_throw() { // Arrange - var actual = new[,,] + var actual = new[, ,] { { { 1 }, @@ -1721,7 +1729,9 @@ public void // Act Action act = () => result.Should().BeEquivalentTo(new Dictionary { - ["A"] = 0, ["B"] = 0, ["C"] = null + ["A"] = 0, + ["B"] = 0, + ["C"] = null }); // Assert @@ -2114,8 +2124,8 @@ public static IEnumerable ArrayTestData() }; return from x in arrays - from y in arrays - select new object[] { x, y }; + from y in arrays + select new object[] { x, y }; } [Fact] diff --git a/Tests/FluentAssertions.Equivalency.Specs/MemberMatchingSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/MemberMatchingSpecs.cs index 3f313839ef..e35b6dcd14 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/MemberMatchingSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/MemberMatchingSpecs.cs @@ -440,7 +440,7 @@ public void Exclusion_of_missing_members_works_with_mapping() var expectation = new { - Property2 = 2, + Property2 = 2, Ignore = 3 }; @@ -463,7 +463,7 @@ public void Mapping_works_with_exclusion_of_missing_members() var expectation = new { - Property2 = 2, + Property2 = 2, Ignore = 3 }; @@ -484,13 +484,13 @@ public void Can_map_members_of_a_root_collection() EntityId = 1, Name = "Test" }; - + var dto = new EntityDto { Id = 1, Name = "Test" }; - + var entityCol = new[] { entity }; var dtoCol = new[] { dto }; diff --git a/Tests/FluentAssertions.Equivalency.Specs/NestedPropertiesSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/NestedPropertiesSpecs.cs index 0ac1c5b3b1..90527e353f 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/NestedPropertiesSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/NestedPropertiesSpecs.cs @@ -13,12 +13,14 @@ public void When_all_the_properties_of_the_nested_objects_are_equal_it_should_su // Arrange var subject = new Root { - Text = "Root", Level = new Level1 { Text = "Level1", Level = new Level2 { Text = "Level2" } } + Text = "Root", + Level = new Level1 { Text = "Level1", Level = new Level2 { Text = "Level2" } } }; var expected = new RootDto { - Text = "Root", Level = new Level1Dto { Text = "Level1", Level = new Level2Dto { Text = "Level2" } } + Text = "Root", + Level = new Level1Dto { Text = "Level1", Level = new Level2Dto { Text = "Level2" } } }; // Act @@ -53,7 +55,8 @@ public void { Property = new ClassWithValueSemanticsOnSingleProperty { - Key = "123", NestedProperty = "Should be ignored" + Key = "123", + NestedProperty = "Should be ignored" } }; @@ -61,7 +64,8 @@ public void { Property = new ClassWithValueSemanticsOnSingleProperty { - Key = "123", NestedProperty = "Should be ignored as well" + Key = "123", + NestedProperty = "Should be ignored as well" } }; @@ -249,7 +253,8 @@ public void When_deeply_nested_properties_do_not_have_all_equal_values_it_should // Arrange var root = new Root { - Text = "Root", Level = new Level1 { Text = "Level1", Level = new Level2 { Text = "Level2" } } + Text = "Root", + Level = new Level1 { Text = "Level1", Level = new Level2 { Text = "Level2" } } }; var rootDto = new RootDto diff --git a/Tests/UWP.Specs/Properties/AssemblyInfo.cs b/Tests/UWP.Specs/Properties/AssemblyInfo.cs index f7cdff3769..a430f052f9 100644 --- a/Tests/UWP.Specs/Properties/AssemblyInfo.cs +++ b/Tests/UWP.Specs/Properties/AssemblyInfo.cs @@ -10,8 +10,8 @@ [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyMetadata("TargetPlatform","UAP")] +[assembly: AssemblyMetadata("TargetPlatform", "UAP")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file +[assembly: ComVisible(false)] From b456f5bc56816de76f70914fc0aa014b5c24680f Mon Sep 17 00:00:00 2001 From: ITaluone <44049228+ITaluone@users.noreply.github.com> Date: Thu, 7 Apr 2022 06:01:50 +0200 Subject: [PATCH 04/48] Update documentation for event monitoring at .netstandard2.0 (#1879) --- docs/_pages/eventmonitoring.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/_pages/eventmonitoring.md b/docs/_pages/eventmonitoring.md index 315c29b5de..06c462633b 100644 --- a/docs/_pages/eventmonitoring.md +++ b/docs/_pages/eventmonitoring.md @@ -89,3 +89,7 @@ metadata.Should().BeEquivalentTo(new[] } }); ``` + +## Limitations + +This feature is not available in .NET Standard 2.0, because [`System.Reflection.Emit.DynamicMethod`](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.emit.dynamicmethod) is required to generate event handlers dynamically. From f5f65ea654255c6e32e46f1c72f47a79ebef781d Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger | alu-one Date: Wed, 6 Apr 2022 11:38:01 +0200 Subject: [PATCH 05/48] Fix codestyle issue `IDE0052` --- .../UsersOfGetClosedGenericInterfaces.cs | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs b/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs index 0d087c06fd..b5d632b059 100644 --- a/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs +++ b/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs @@ -24,14 +24,13 @@ public class UsersOfGetClosedGenericInterfaces private GenericEnumerableEquivalencyStep enumerableStep; private IEquivalencyValidationContext context; - private IEquivalencyAssertionOptions config; private class Context : IEquivalencyValidationContext { public INode CurrentNode { get; } public Reason Reason { get; } public Tracer Tracer { get; } - public IEquivalencyAssertionOptions Options { get; } + public IEquivalencyAssertionOptions Options { get; internal set; } public bool IsCyclicReference(object expectation) => throw new NotImplementedException(); public IEquivalencyValidationContext AsNestedMember(IMember expectationMember) => throw new NotImplementedException(); @@ -148,25 +147,27 @@ public void GlobalSetup() break; default: - { - if (DataType == typeof(TimeSpan)) - values[i] = faker.Date.Future() - faker.Date.Future(); - else if (DataType == typeof(Guid)) - values[i] = faker.Random.Guid(); - else if (DataType == typeof(Dictionary)) - values[i] = new Dictionary() { { faker.Random.Int(), faker.Random.Int() } }; - else if (DataType == typeof(IEnumerable)) - values[i] = new int[] { faker.Random.Int(), faker.Random.Int() }; - else - throw new Exception("Unable to populate data of type " + DataType); - - break; - } + { + if (DataType == typeof(TimeSpan)) + values[i] = faker.Date.Future() - faker.Date.Future(); + else if (DataType == typeof(Guid)) + values[i] = faker.Random.Guid(); + else if (DataType == typeof(Dictionary)) + values[i] = new Dictionary() { { faker.Random.Int(), faker.Random.Int() } }; + else if (DataType == typeof(IEnumerable)) + values[i] = new int[] { faker.Random.Int(), faker.Random.Int() }; + else + throw new Exception("Unable to populate data of type " + DataType); + + break; + } } } - context = new Context(); - config = new Config(); + context = new Context() + { + Options = new Config() + }; } [Benchmark] From a2fd3eb8ce7bf373c69f267c5f465819746490ab Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger | alu-one Date: Thu, 7 Apr 2022 07:08:29 +0200 Subject: [PATCH 06/48] Fix codestyle issue `SA1601` https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1601.md --- .../GenericCollectionAssertionOfStringSpecs.AllSatisfy.cs | 3 +++ .../Collections/GenericCollectionAssertionOfStringSpecs.cs | 3 +++ 2 files changed, 6 insertions(+) diff --git a/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.AllSatisfy.cs b/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.AllSatisfy.cs index b688dcb148..ffe55530f6 100644 --- a/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.AllSatisfy.cs +++ b/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.AllSatisfy.cs @@ -4,6 +4,9 @@ namespace FluentAssertions.Specs.Collections { + /// + /// This part contains tests that address AllSatisfy + /// public partial class GenericCollectionAssertionOfStringSpecs { public class AllSatisfy diff --git a/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.cs b/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.cs index 72e447b12a..ccce32cf14 100644 --- a/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.cs +++ b/Tests/FluentAssertions.Specs/Collections/GenericCollectionAssertionOfStringSpecs.cs @@ -9,6 +9,9 @@ namespace FluentAssertions.Specs.Collections { + /// + /// This part of the class contains assertions of general generic string collections + /// public partial class GenericCollectionAssertionOfStringSpecs { [Fact] From db4562b2441dfe77c710cd9989a9cfb41593cbf5 Mon Sep 17 00:00:00 2001 From: IT-VBFK <49762557+IT-VBFK@users.noreply.github.com> Date: Sat, 9 Apr 2022 18:59:25 +0200 Subject: [PATCH 07/48] Add missing tests (according to coveralls) for Data* objects (#1882) --- .../DataColumnSpecs.cs | 22 +++++ .../DataRelationSpecs.cs | 96 +++++++++++++++++++ .../DataRowSpecs.cs | 38 ++++++++ .../DataSetSpecs.cs | 22 +++++ .../DataTableSpecs.cs | 22 +++++ 5 files changed, 200 insertions(+) diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataColumnSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataColumnSpecs.cs index f4c3e0025f..ec25190ebc 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataColumnSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataColumnSpecs.cs @@ -703,5 +703,27 @@ public void When_ExtendedProperties_do_not_match_and_property_is_excluded_it_sho dataColumn1.Should().BeEquivalentTo(dataColumn2, options => options.Excluding(dataColumn => dataColumn.ExtendedProperties)); } + + [Fact] + public void Data_column_is_not_equivalent_to_another_type() + { + // Arrange + var subject = new + { + DataColumn = "foobar" + }; + + var expected = new + { + DataColumn = new DataColumn() + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected*System.Data.DataColumn*found System.String*"); + } } } diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataRelationSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataRelationSpecs.cs index 71c79a7f1e..17435edb74 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataRelationSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataRelationSpecs.cs @@ -254,5 +254,101 @@ public void When_ChildColumns_do_not_match_and_property_is_excluded_it_should_su .ExcludingRelated((DataRelation dataRelation) => dataRelation.ParentKeyConstraint) .ExcludingRelated((DataRelation dataRelation) => dataRelation.ChildKeyConstraint)); } + + [Fact] + public void Data_relation_is_not_equivalent_to_another_type() + { + // Arrange + var dataSet = new DataSet(); + var table = new DataTable(); + var col1 = new DataColumn(); + var col2 = new DataColumn(); + + table.Columns.Add(col1); + table.Columns.Add(col2); + + dataSet.Tables.Add(table); + + var subject = new + { + DataRelation = "foobar" + }; + + var expected = new + { + DataRelation = new DataRelation("bar", col1, col2) + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected*System.Data.DataRelation*found System.String*"); + } + + [Fact] + public void Null_is_not_equivalent_to_a_data_relation() + { + // Arrange + var dataSet = new DataSet(); + var table = new DataTable(); + var col1 = new DataColumn(); + var col2 = new DataColumn(); + + table.Columns.Add(col1); + table.Columns.Add(col2); + + dataSet.Tables.Add(table); + + var subject = new + { + DataRelation = (DataRelation)null + }; + + var expected = new + { + DataRelation = new DataRelation("bar", col1, col2) + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected *value to be non-null, but found*"); + } + + [Fact] + public void Data_relation_is_not_equivalent_to_null() + { + // Arrange + var dataSet = new DataSet(); + var table = new DataTable(); + var col1 = new DataColumn(); + var col2 = new DataColumn(); + + table.Columns.Add(col1); + table.Columns.Add(col2); + + dataSet.Tables.Add(table); + + var subject = new + { + DataRelation = new DataRelation("bar", col1, col2) + }; + + var expected = new + { + DataRelation = (DataRelation)null + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected *to be null, but found*"); + } } } diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs index a8b2e6a98c..a7c26d3188 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs @@ -335,6 +335,44 @@ public void When_data_row_data_does_not_match_but_the_column_is_excluded_then_eq dataRow1.Should().BeEquivalentTo(dataRow2, config => config.ExcludingColumn(dataSet2.TypedDataTable1.DateTimeColumn)); } + [Fact] + public void Data_row_is_not_equivalent_to_another_type() + { + // Arrange + var table = new DataTable(); + var dataRow = table.NewRow(); + var subject = new + { + DataRow = "foobar" + }; + + var expected = new + { + DataRow = dataRow + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected*System.Data.DataRow*found System.String*"); + } + + [Fact] + public void Any_type_is_not_equivalent_to_data_row_colletion() + { + // Arrange + var o = new object(); + + // Act + Action act = () => o.Should().BeEquivalentTo((DataRowCollection)null); + + // Assert + act.Should().Throw() + .WithMessage("Expected* to be of type DataRowCollection, but found*"); + } + [Fact] public void When_data_row_has_column_then_asserting_that_it_has_that_column_should_succeed() { diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs index 12bbbd0504..dd8c0ade56 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs @@ -615,6 +615,28 @@ public void When_data_set_tables_contain_different_data_equivalence_test_should_ action.Should().Throw().WithMessage("Expected dataSet1[TypedDataTable2].Rows[0] to have RowState value of *Modified*, but found *Unchanged* instead*"); } + [Fact] + public void Data_set_is_not_equivalent_to_another_type() + { + // Arrange + var subject = new + { + DataSet = "foobar" + }; + + var expected = new + { + DataSet = new DataSet() + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected*System.Data.DataSet*found System.String*"); + } + [Fact] public void When_data_set_table_count_has_expected_value_equivalence_test_should_succeed() { diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs index 025528d40b..89d5689125 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs @@ -721,6 +721,28 @@ public void When_data_table_data_matches_in_different_order_and_the_row_match_mo dataTable1.Should().BeEquivalentTo(dataTable2, options => options.UsingRowMatchMode(RowMatchMode.PrimaryKey)); } + [Fact] + public void Data_table_is_not_equivalent_to_another_type() + { + // Arrange + var subject = new + { + DataTable = "foobar" + }; + + var expected = new + { + DataTable = new DataTable() + }; + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected*System.Data.DataTable*found System.String*"); + } + [Fact] public void When_data_table_has_expected_row_count_it_should_succeed() { From 192f48ca8d0941e3108a0b7506393856c974afef Mon Sep 17 00:00:00 2001 From: IT-VBFK <49762557+IT-VBFK@users.noreply.github.com> Date: Fri, 15 Apr 2022 10:20:02 +0200 Subject: [PATCH 08/48] Add `BeDefined` and `NotBeDefined` to `EnumAssertions` (#1888) Add methods `BeDefined` and `NotBeDefined` to `EnumAssertions` --- .../Primitives/EnumAssertions.cs | 52 ++++++++++++ .../FluentAssertions/net47.verified.txt | 2 + .../FluentAssertions/net6.0.verified.txt | 2 + .../netcoreapp2.1.verified.txt | 2 + .../netcoreapp3.0.verified.txt | 2 + .../netstandard2.0.verified.txt | 2 + .../netstandard2.1.verified.txt | 2 + .../Primitives/EnumAssertionSpecs.cs | 79 +++++++++++++++++++ docs/_pages/enums.md | 8 ++ docs/_pages/releases.md | 5 ++ 10 files changed, 156 insertions(+) diff --git a/Src/FluentAssertions/Primitives/EnumAssertions.cs b/Src/FluentAssertions/Primitives/EnumAssertions.cs index 77a6ee052e..c6974a806b 100644 --- a/Src/FluentAssertions/Primitives/EnumAssertions.cs +++ b/Src/FluentAssertions/Primitives/EnumAssertions.cs @@ -129,6 +129,58 @@ public AndConstraint Be(TEnum? expected, string because = "", param return new AndConstraint((TAssertions)this); } + /// + /// Asserts that the current value of is defined inside the enum. + /// + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public AndConstraint BeDefined(string because = "", params object[] becauseArgs) + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:the enum} to be defined in {0}{reason}, ", typeof(TEnum)) + .ForCondition(Subject is not null) + .FailWith("but found .") + .Then + .ForCondition(Enum.IsDefined(typeof(TEnum), Subject)) + .FailWith("but it is not.") + .Then + .ClearExpectation(); + + return new AndConstraint((TAssertions)this); + } + + /// + /// Asserts that the current value of is not defined inside the enum. + /// + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Did not expect {context:the enum} to be defined in {0}{reason}, ", typeof(TEnum)) + .ForCondition(Subject is not null) + .FailWith("but found .") + .Then + .ForCondition(!Enum.IsDefined(typeof(TEnum), Subject)) + .FailWith("but it is.") + .Then + .ClearExpectation(); + + return new AndConstraint((TAssertions)this); + } + /// /// Asserts that the current is exactly equal to the value. /// diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt index 6ff5858bab..4682ecdc00 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt @@ -1887,6 +1887,7 @@ namespace FluentAssertions.Primitives public TEnum? Subject { get; } public FluentAssertions.AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint BeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint BeOneOf(params TEnum[] validValues) { } public FluentAssertions.AndConstraint BeOneOf(System.Collections.Generic.IEnumerable validValues, string because = "", params object[] becauseArgs) { } public override bool Equals(object obj) { } @@ -1899,6 +1900,7 @@ namespace FluentAssertions.Primitives public FluentAssertions.AndConstraint Match(System.Linq.Expressions.Expression> predicate, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, System.Enum { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt index cf6defd2c8..9fa5350cd3 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt @@ -1944,6 +1944,7 @@ namespace FluentAssertions.Primitives public TEnum? Subject { get; } public FluentAssertions.AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint BeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint BeOneOf(params TEnum[] validValues) { } public FluentAssertions.AndConstraint BeOneOf(System.Collections.Generic.IEnumerable validValues, string because = "", params object[] becauseArgs) { } public override bool Equals(object obj) { } @@ -1956,6 +1957,7 @@ namespace FluentAssertions.Primitives public FluentAssertions.AndConstraint Match(System.Linq.Expressions.Expression> predicate, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, System.Enum { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt index 08f866a950..16751afb56 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt @@ -1887,6 +1887,7 @@ namespace FluentAssertions.Primitives public TEnum? Subject { get; } public FluentAssertions.AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint BeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint BeOneOf(params TEnum[] validValues) { } public FluentAssertions.AndConstraint BeOneOf(System.Collections.Generic.IEnumerable validValues, string because = "", params object[] becauseArgs) { } public override bool Equals(object obj) { } @@ -1899,6 +1900,7 @@ namespace FluentAssertions.Primitives public FluentAssertions.AndConstraint Match(System.Linq.Expressions.Expression> predicate, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, System.Enum { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt index fe3a364b04..f9e4753c6e 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt @@ -1887,6 +1887,7 @@ namespace FluentAssertions.Primitives public TEnum? Subject { get; } public FluentAssertions.AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint BeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint BeOneOf(params TEnum[] validValues) { } public FluentAssertions.AndConstraint BeOneOf(System.Collections.Generic.IEnumerable validValues, string because = "", params object[] becauseArgs) { } public override bool Equals(object obj) { } @@ -1899,6 +1900,7 @@ namespace FluentAssertions.Primitives public FluentAssertions.AndConstraint Match(System.Linq.Expressions.Expression> predicate, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, System.Enum { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt index e210dc45ac..ec7b7c008f 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt @@ -1839,6 +1839,7 @@ namespace FluentAssertions.Primitives public TEnum? Subject { get; } public FluentAssertions.AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint BeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint BeOneOf(params TEnum[] validValues) { } public FluentAssertions.AndConstraint BeOneOf(System.Collections.Generic.IEnumerable validValues, string because = "", params object[] becauseArgs) { } public override bool Equals(object obj) { } @@ -1851,6 +1852,7 @@ namespace FluentAssertions.Primitives public FluentAssertions.AndConstraint Match(System.Linq.Expressions.Expression> predicate, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, System.Enum { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt index e0c14517ca..25938a8a06 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt @@ -1887,6 +1887,7 @@ namespace FluentAssertions.Primitives public TEnum? Subject { get; } public FluentAssertions.AndConstraint Be(TEnum expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint Be(TEnum? expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint BeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint BeOneOf(params TEnum[] validValues) { } public FluentAssertions.AndConstraint BeOneOf(System.Collections.Generic.IEnumerable validValues, string because = "", params object[] becauseArgs) { } public override bool Equals(object obj) { } @@ -1899,6 +1900,7 @@ namespace FluentAssertions.Primitives public FluentAssertions.AndConstraint Match(System.Linq.Expressions.Expression> predicate, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(TEnum? unexpected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndConstraint NotBeDefined(string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveFlag(TEnum unexpectedFlag, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotHaveSameNameAs(T unexpected, string because = "", params object[] becauseArgs) where T : struct, System.Enum { } diff --git a/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs index 2ffaff3042..b38e6008d1 100644 --- a/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs @@ -791,5 +791,84 @@ public void An_enum_cannot_be_part_of_a_null_list() } #endregion + + #region Be defined / Not be defined + + [Fact] + public void A_valid_entry_of_an_enum_is_defined() + { + // Arrange + var dayOfWeek = (DayOfWeek)1; + + // Act / Assert + dayOfWeek.Should().BeDefined(); + } + + [Fact] + public void If_a_value_casted_to_an_enum_type_and_it_does_not_exist_in_the_enum_it_throws() + { + // Arrange + var dayOfWeek = (DayOfWeek)999; + + // Act + Action act = () => dayOfWeek.Should().BeDefined("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected *to be defined in*failure message*, but it is not*"); + } + + [Fact] + public void A_null_entry_of_an_enum_throws() + { + // Arrange + MyEnum? subject = null; + + // Act + Action act = () => subject.Should().BeDefined(); + + // Assert + act.Should().Throw() + .WithMessage("Expected *to be defined in*, but found ."); + } + + [Fact] + public void An_invalid_entry_of_an_enum_is_not_defined_passes() + { + // Arrange + var dayOfWeek = (DayOfWeek)999; + + // Act / Assert + dayOfWeek.Should().NotBeDefined(); + } + + [Fact] + public void A_valid_entry_of_an_enum_is_not_defined_fails() + { + // Arrange + var dayOfWeek = (DayOfWeek)1; + + // Act + Action act = () => dayOfWeek.Should().NotBeDefined(); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect*to be defined in*, but it is."); + } + + [Fact] + public void A_null_value_of_an_enum_is_not_defined_and_throws() + { + // Arrange + MyEnum? subject = null; + + // Act + Action act = () => subject.Should().NotBeDefined(); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect *to be defined in*, but found ."); + } + #endregion } } diff --git a/docs/_pages/enums.md b/docs/_pages/enums.md index 435ac01640..3f8881b404 100644 --- a/docs/_pages/enums.md +++ b/docs/_pages/enums.md @@ -42,3 +42,11 @@ Lastly, if you want to verify than an enum has a specific integral value, you ca MyEnum.One.Should().HaveValue(1); MyEnum.One.Should().NotHaveValue(2); ``` + +```csharp +var myEnum = (MyEnum)1; +myEnum.Should().BeDefined(); + +myEnum = (MyEnum)99; +myEnum.Should().NotBeDefined(); +``` \ No newline at end of file diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index 7b586dc4e3..de4a23955d 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -9,6 +9,11 @@ sidebar: ## Unreleased +### What's new +* Add `BeDefined` and `NotBeDefined` to assert on existence of an enum value - [#1888](https://github.com/fluentassertions/fluentassertions/pull/1888) + +## 6.6.0 + ### What's New * Annotated `[Not]MatchRegex(string)` with `[StringSyntax("Regex")]` which IDEs can use to colorize the regular expression argument - [#1816](https://github.com/fluentassertions/fluentassertions/pull/1816) * Added support for .NET6 `DateOnly` struct - [#1844](https://github.com/fluentassertions/fluentassertions/pull/1844) From 9e03620a904861a7c5aa66de00283a36155cc8e4 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Fri, 15 Apr 2022 10:14:39 +0200 Subject: [PATCH 09/48] Fix small typo --- Src/FluentAssertions/Execution/AssertionScope.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/FluentAssertions/Execution/AssertionScope.cs b/Src/FluentAssertions/Execution/AssertionScope.cs index ab7251a453..4d04e733fc 100644 --- a/Src/FluentAssertions/Execution/AssertionScope.cs +++ b/Src/FluentAssertions/Execution/AssertionScope.cs @@ -205,7 +205,7 @@ public Continuation ClearExpectation() { expectation = null; - // SMELL: Isn't this always going to return null? Or this method also called without FailWidth (which sets the success state to null) + // SMELL: Isn't this always going to return null? Or this method also called without FailWith (which sets the success state to null) return new Continuation(this, Succeeded); } From 37c8e6b3391b274277648e3859bd2272ab79b5c3 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Fri, 15 Apr 2022 09:55:07 +0200 Subject: [PATCH 10/48] Add guarding Should to range assertions --- Src/FluentAssertions/AssertionExtensions.cs | 16 ++++++++++++++++ .../FluentAssertions/net47.verified.txt | 8 ++++++++ .../FluentAssertions/net6.0.verified.txt | 8 ++++++++ .../FluentAssertions/netcoreapp2.1.verified.txt | 8 ++++++++ .../FluentAssertions/netcoreapp3.0.verified.txt | 8 ++++++++ .../FluentAssertions/netstandard2.0.verified.txt | 8 ++++++++ .../FluentAssertions/netstandard2.1.verified.txt | 8 ++++++++ .../AssertionExtensionsSpecs.cs | 7 +++++++ 8 files changed, 71 insertions(+) diff --git a/Src/FluentAssertions/AssertionExtensions.cs b/Src/FluentAssertions/AssertionExtensions.cs index aa0b65309a..9a571bc755 100644 --- a/Src/FluentAssertions/AssertionExtensions.cs +++ b/Src/FluentAssertions/AssertionExtensions.cs @@ -1028,6 +1028,22 @@ public static void Should(this TypeSelectorAssertions _) InvalidShouldCall(); } + /// + [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] + public static void Should(this DateTimeRangeAssertions _) + where TAssertions : DateTimeAssertions + { + InvalidShouldCall(); + } + + /// + [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] + public static void Should(this DateTimeOffsetRangeAssertions _) + where TAssertions : DateTimeOffsetAssertions + { + InvalidShouldCall(); + } + [DoesNotReturn] private static void InvalidShouldCall() { diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt index 4682ecdc00..d4fb219b01 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt @@ -118,6 +118,14 @@ namespace FluentAssertions where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeOffsetRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] public static void Should(this FluentAssertions.Primitives.GuidAssertions _) where TAssertions : FluentAssertions.Primitives.GuidAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt index 9fa5350cd3..b201492d06 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt @@ -126,6 +126,14 @@ namespace FluentAssertions where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeOffsetRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] public static void Should(this FluentAssertions.Primitives.GuidAssertions _) where TAssertions : FluentAssertions.Primitives.GuidAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt index 16751afb56..c61ca7e0cf 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt @@ -118,6 +118,14 @@ namespace FluentAssertions where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeOffsetRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] public static void Should(this FluentAssertions.Primitives.GuidAssertions _) where TAssertions : FluentAssertions.Primitives.GuidAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt index f9e4753c6e..0f09d0036a 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt @@ -118,6 +118,14 @@ namespace FluentAssertions where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeOffsetRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] public static void Should(this FluentAssertions.Primitives.GuidAssertions _) where TAssertions : FluentAssertions.Primitives.GuidAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt index ec7b7c008f..308199eac3 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt @@ -117,6 +117,14 @@ namespace FluentAssertions where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeOffsetRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] public static void Should(this FluentAssertions.Primitives.GuidAssertions _) where TAssertions : FluentAssertions.Primitives.GuidAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt index 25938a8a06..53648f12be 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt @@ -118,6 +118,14 @@ namespace FluentAssertions where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeOffsetRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeOffsetAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] + public static void Should(this FluentAssertions.Primitives.DateTimeRangeAssertions _) + where TAssertions : FluentAssertions.Primitives.DateTimeAssertions { } + [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + + "ly following \'And\'", true)] public static void Should(this FluentAssertions.Primitives.GuidAssertions _) where TAssertions : FluentAssertions.Primitives.GuidAssertions { } [System.Obsolete("You are asserting the \'AndConstraint\' itself. Remove the \'Should()\' method direct" + diff --git a/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs b/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs index e9f4bb26a5..288f92eb2f 100644 --- a/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs @@ -39,7 +39,9 @@ private static bool OverridesEquals(Type t) [InlineData(typeof(ReferenceTypeAssertions))] [InlineData(typeof(BooleanAssertions))] [InlineData(typeof(DateTimeAssertions))] + [InlineData(typeof(DateTimeRangeAssertions))] [InlineData(typeof(DateTimeOffsetAssertions))] + [InlineData(typeof(DateTimeOffsetRangeAssertions))] #if NET6_0_OR_GREATER [InlineData(typeof(DateOnlyAssertions))] [InlineData(typeof(TimeOnlyAssertions))] @@ -95,6 +97,11 @@ public void Should_methods_have_a_matching_overload_to_guard_against_chaining_an .Where(m => !IsGuardOverload(m)) .Select(t => GetMostParentType(t.ReturnType)) .Distinct() + .Concat(new[] + { + typeof(DateTimeRangeAssertions<>), + typeof(DateTimeOffsetRangeAssertions<>) + }) .ToList(); List fakeOverloads = shouldOverloads From 9987ff3b1a67447e59b6af4f1781ffa8d02cb290 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Fri, 15 Apr 2022 10:01:22 +0200 Subject: [PATCH 11/48] Verify that guarding Equals method throws --- .../ExtensibilitySpecs.cs | 2 +- .../AssertionExtensionsSpecs.cs | 37 ++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs index 1186557657..bbb84c2321 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/ExtensibilitySpecs.cs @@ -503,7 +503,7 @@ public void When_overriding_with_custom_assertion_it_should_be_chainable() } [Fact] - public void When_a_nullable_property_is_overriden_with_a_custom_assertion_it_should_use_it() + public void When_a_nullable_property_is_overridden_with_a_custom_assertion_it_should_use_it() { // Arrange var actual = new SimpleWithNullable diff --git a/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs b/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs index 288f92eb2f..b30c6052e5 100644 --- a/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/AssertionExtensionsSpecs.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using FluentAssertions.Common; using FluentAssertions.Numeric; using FluentAssertions.Primitives; using FluentAssertions.Specialized; @@ -13,7 +14,7 @@ namespace FluentAssertions.Specs public class AssertionExtensionsSpecs { [Fact] - public void Assertions_classes_have_overriden_equals() + public void Assertions_classes_override_equals() { // Arrange / Act var equalsOverloads = AllTypes.From(typeof(FluentAssertions.AssertionExtensions).Assembly) @@ -35,6 +36,40 @@ private static bool OverridesEquals(Type t) return equals is not null; } + public static object[][] ClassesWithGuardEquals() => new object[][] + { + new object[] { new ObjectAssertions(default) }, + new object[] { new BooleanAssertions(default) }, + new object[] { new DateTimeAssertions(default) }, + new object[] { new DateTimeRangeAssertions(default, default, default, default) }, + new object[] { new DateTimeOffsetAssertions(default) }, + new object[] { new DateTimeOffsetRangeAssertions(default, default, default, default) }, +#if NET6_0_OR_GREATER + new object[] { new DateOnlyAssertions(default) }, + new object[] { new TimeOnlyAssertions(default) }, +#endif + new object[] { new ExecutionTimeAssertions(new ExecutionTime(() => { }, () => new StopwatchTimer())) }, + new object[] { new GuidAssertions(default) }, + new object[] { new MethodInfoSelectorAssertions() }, + new object[] { new NumericAssertions>(default) }, + new object[] { new PropertyInfoSelectorAssertions() }, + new object[] { new SimpleTimeSpanAssertions(default) }, + new object[] { new TaskCompletionSourceAssertions(default) }, + new object[] { new TypeSelectorAssertions() }, + new object[] { new EnumAssertions>(default) } + }; + + [Theory] + [MemberData(nameof(ClassesWithGuardEquals))] + public void Guarding_equals_throws(object obj) + { + // Act + Action act = () => obj.Equals(null); + + // Assert + act.Should().ThrowExactly(); + } + [Theory] [InlineData(typeof(ReferenceTypeAssertions))] [InlineData(typeof(BooleanAssertions))] From d5ef320a9148c4d7165ea1d16b1e2c8671eec488 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Fri, 15 Apr 2022 14:51:43 +0200 Subject: [PATCH 12/48] Add missing test for matching `null` with wildcard string --- .../Primitives/StringAssertionSpecs.Match.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs index c69f57892f..6ae41f3094 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs @@ -81,6 +81,20 @@ public void When_a_string_is_matched_against_null_it_should_throw_with_a_clear_e .WithParameterName("wildcardPattern"); } + [Fact] + public void Null_does_not_match_to_any_string() + { + // Arrange + string subject = null; + + // Act + Action act = () => subject.Should().Match("*"); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match *, but found ."); + } + [Fact] public void When_a_string_is_matched_against_an_empty_string_it_should_throw_with_a_clear_explanation() { From 471fb8ea1dbb30f56fd170b768147661b4461872 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Sat, 16 Apr 2022 09:04:28 +0200 Subject: [PATCH 13/48] Remove an unreachable `null` check --- .../Primitives/StringWildcardMatchingValidator.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Src/FluentAssertions/Primitives/StringWildcardMatchingValidator.cs b/Src/FluentAssertions/Primitives/StringWildcardMatchingValidator.cs index 1430be8126..40bc16c682 100644 --- a/Src/FluentAssertions/Primitives/StringWildcardMatchingValidator.cs +++ b/Src/FluentAssertions/Primitives/StringWildcardMatchingValidator.cs @@ -49,11 +49,6 @@ private static string ConvertWildcardToRegEx(string wildcardExpression) private string CleanNewLines(string input) { - if (input is null) - { - return null; - } - return IgnoreNewLineDifferences ? input.RemoveNewLines() : input; } From 6ecd349909ec52d60e3d6c55d63ab667cb369285 Mon Sep 17 00:00:00 2001 From: Jonathan Gilbert Date: Sat, 16 Apr 2022 03:04:58 -0500 Subject: [PATCH 14/48] Restore basic assertions for collections in System.Data (#1812) --- Src/FluentAssertions/AssertionExtensions.cs | 31 + .../ReadOnlyNonGenericCollectionWrapper.cs | 75 +++ ...DataColumnCollectionAssertionExtensions.cs | 169 +++++ .../DataRowCollectionAssertionExtensions.cs | 164 +++++ .../DataTableCollectionAssertionExtensions.cs | 199 ++++++ .../FluentAssertions/net47.verified.txt | 26 + .../FluentAssertions/net6.0.verified.txt | 26 + .../netcoreapp2.1.verified.txt | 26 + .../netcoreapp3.0.verified.txt | 26 + .../netstandard2.0.verified.txt | 26 + .../netstandard2.1.verified.txt | 26 + .../DataColumnCollectionAssertionSpecs.cs | 441 +++++++++++++ .../Data/DataRowCollectionAssertionSpecs.cs | 608 ++++++++++++++++++ .../Data/DataTableCollectionAssertionSpecs.cs | 545 ++++++++++++++++ docs/_pages/data.md | 20 + docs/_pages/releases.md | 1 + 16 files changed, 2409 insertions(+) create mode 100644 Src/FluentAssertions/Common/ReadOnlyNonGenericCollectionWrapper.cs create mode 100644 Src/FluentAssertions/DataColumnCollectionAssertionExtensions.cs create mode 100644 Src/FluentAssertions/DataRowCollectionAssertionExtensions.cs create mode 100644 Src/FluentAssertions/DataTableCollectionAssertionExtensions.cs create mode 100644 Tests/FluentAssertions.Specs/Collections/Data/DataColumnCollectionAssertionSpecs.cs create mode 100644 Tests/FluentAssertions.Specs/Collections/Data/DataRowCollectionAssertionSpecs.cs create mode 100644 Tests/FluentAssertions.Specs/Collections/Data/DataTableCollectionAssertionSpecs.cs diff --git a/Src/FluentAssertions/AssertionExtensions.cs b/Src/FluentAssertions/AssertionExtensions.cs index aa0b65309a..6755fc0467 100644 --- a/Src/FluentAssertions/AssertionExtensions.cs +++ b/Src/FluentAssertions/AssertionExtensions.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Linq.Expressions; using System.Net.Http; using System.Reflection; @@ -385,6 +386,36 @@ public static StringCollectionAssertions Should(this IEnumerable @this) return new GenericDictionaryAssertions(actualValue); } + /// + /// Returns an assertions object that provides methods for asserting the state of a . + /// + [Pure] + public static GenericCollectionAssertions Should(this DataTableCollection actualValue) + { + return new GenericCollectionAssertions( + ReadOnlyNonGenericCollectionWrapper.Create(actualValue)); + } + + /// + /// Returns an assertions object that provides methods for asserting the state of a . + /// + [Pure] + public static GenericCollectionAssertions Should(this DataColumnCollection actualValue) + { + return new GenericCollectionAssertions( + ReadOnlyNonGenericCollectionWrapper.Create(actualValue)); + } + + /// + /// Returns an assertions object that provides methods for asserting the state of a . + /// + [Pure] + public static GenericCollectionAssertions Should(this DataRowCollection actualValue) + { + return new GenericCollectionAssertions( + ReadOnlyNonGenericCollectionWrapper.Create(actualValue)); + } + /// /// Returns a object that can be used to assert the /// current . diff --git a/Src/FluentAssertions/Common/ReadOnlyNonGenericCollectionWrapper.cs b/Src/FluentAssertions/Common/ReadOnlyNonGenericCollectionWrapper.cs new file mode 100644 index 0000000000..fc6fa22a81 --- /dev/null +++ b/Src/FluentAssertions/Common/ReadOnlyNonGenericCollectionWrapper.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; + +namespace FluentAssertions.Common +{ + internal static class ReadOnlyNonGenericCollectionWrapper + { + public static ReadOnlyNonGenericCollectionWrapper Create(DataTableCollection collection) + { + return + (collection != null) + ? new ReadOnlyNonGenericCollectionWrapper(collection) + : null; + } + + public static ReadOnlyNonGenericCollectionWrapper Create(DataColumnCollection collection) + { + return + (collection != null) + ? new ReadOnlyNonGenericCollectionWrapper(collection) + : null; + } + + public static ReadOnlyNonGenericCollectionWrapper Create(DataRowCollection collection) + { + return + (collection != null) + ? new ReadOnlyNonGenericCollectionWrapper(collection) + : null; + } + } + + internal class ReadOnlyNonGenericCollectionWrapper : ICollection + where TCollection : ICollection + { + public TCollection UnderlyingCollection { get; } + + public ReadOnlyNonGenericCollectionWrapper(TCollection collection) + { + Guard.ThrowIfArgumentIsNull(collection, nameof(collection)); + + UnderlyingCollection = collection; + } + + public int Count => UnderlyingCollection.Count; + + public bool IsReadOnly => true; + + public IEnumerator GetEnumerator() => UnderlyingCollection.Cast().GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => UnderlyingCollection.GetEnumerator(); + + public bool Contains(TItem item) => UnderlyingCollection.Cast().Contains(item); + + public void CopyTo(TItem[] array, int arrayIndex) => UnderlyingCollection.CopyTo(array, arrayIndex); + + /* + + Mutation is not supported, but these methods must be implemented to satisfy ICollection: + * Add + * Clear + * Remove + + */ + + public void Add(TItem item) => throw new NotSupportedException(); + + public void Clear() => throw new NotSupportedException(); + + public bool Remove(TItem item) => throw new NotSupportedException(); + } +} diff --git a/Src/FluentAssertions/DataColumnCollectionAssertionExtensions.cs b/Src/FluentAssertions/DataColumnCollectionAssertionExtensions.cs new file mode 100644 index 0000000000..8cc8362408 --- /dev/null +++ b/Src/FluentAssertions/DataColumnCollectionAssertionExtensions.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.Linq; + +using FluentAssertions.Collections; +using FluentAssertions.Common; +using FluentAssertions.Execution; + +namespace FluentAssertions +{ + public static class DataColumnCollectionAssertionExtensions + { + /// + /// Asserts that an object reference refers to the exact same object as another object reference. + /// + /// The expected object + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> BeSameAs( + this GenericCollectionAssertions assertion, DataColumnCollection expected, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + expected, nameof(expected), "Cannot verify same reference against a collection (use BeNull instead?)."); + + if (assertion.Subject is ReadOnlyNonGenericCollectionWrapper wrapper) + { + var actualSubject = wrapper.UnderlyingCollection; + + Execute.Assertion + .UsingLineBreaks + .ForCondition(ReferenceEquals(actualSubject, expected)) + .BecauseOf(because, becauseArgs) + .FailWith( + "Expected {context:column collection} to refer to {0}{reason}, but found {1} (different underlying object).", + expected, actualSubject); + } + else + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .FailWith( + "Invalid expectation: Expected {context:column collection} to refer to an instance of " + + "DataColumnCollection{reason}, but found {0}.", + assertion.Subject); + } + + return new AndConstraint>(assertion); + } + + /// + /// Asserts that an object reference refers to a different object than another object reference refers to. + /// + /// The unexpected object + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotBeSameAs( + this GenericCollectionAssertions assertion, DataColumnCollection unexpected, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + unexpected, nameof(unexpected), "Cannot verify same reference against a collection (use NotBeNull instead?)."); + + if (assertion.Subject is ReadOnlyNonGenericCollectionWrapper wrapper) + { + var actualSubject = wrapper.UnderlyingCollection; + + Execute.Assertion + .UsingLineBreaks + .ForCondition(!ReferenceEquals(actualSubject, unexpected)) + .BecauseOf(because, becauseArgs) + .FailWith("Did not expect {context:column collection} to refer to {0}{reason}.", unexpected); + } + else + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .FailWith( + "Invalid expectation: Expected {context:column collection} to refer to a different instance of " + + "DataColumnCollection{reason}, but found {0}.", + assertion.Subject); + } + + return new AndConstraint>(assertion); + } + + /// + /// Assert that the current collection has the same number of elements as . + /// + /// The other collection with the same expected number of elements + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> HaveSameCount( + this GenericCollectionAssertions assertion, DataColumnCollection otherCollection, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); + + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:collection} to have ") + .Given(() => assertion.Subject) + .ForCondition(subject => subject is not null) + .FailWith("the same count as {0}{reason}, but found .", otherCollection) + .Then + .Given((subject) => (actual: subject.Count(), expected: otherCollection.Count)) + .ForCondition(count => count.actual == count.expected) + .FailWith("{0} column(s){reason}, but found {1}.", count => count.expected, count => count.actual) + .Then + .ClearExpectation(); + + return new AndConstraint>(assertion); + } + + /// + /// Assert that the current collection of s does not have the same number of columns as + /// . + /// + /// The other with the unexpected number of + /// elements + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotHaveSameCount( + this GenericCollectionAssertions assertion, DataColumnCollection otherCollection, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); + + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:collection} to not have ") + .Given(() => assertion.Subject) + .ForCondition(subject => subject is not null) + .FailWith("the same count as {0}{reason}, but found .", otherCollection) + .Then + .Given((subject) => (actual: subject.Count(), expected: otherCollection.Count)) + .ForCondition(count => count.actual != count.expected) + .FailWith("{0} column(s){reason}, but found {1}.", count => count.expected, count => count.actual) + .Then + .ClearExpectation(); + + return new AndConstraint>(assertion); + } + } +} diff --git a/Src/FluentAssertions/DataRowCollectionAssertionExtensions.cs b/Src/FluentAssertions/DataRowCollectionAssertionExtensions.cs new file mode 100644 index 0000000000..ea5e745ff3 --- /dev/null +++ b/Src/FluentAssertions/DataRowCollectionAssertionExtensions.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; + +using FluentAssertions.Collections; +using FluentAssertions.Common; +using FluentAssertions.Data; +using FluentAssertions.Equivalency; +using FluentAssertions.Execution; + +namespace FluentAssertions +{ + public static class DataRowCollectionAssertionExtensions + { + /// + /// Asserts that an object reference refers to the exact same object as another object reference. + /// + /// The expected object + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> BeSameAs( + this GenericCollectionAssertions assertion, DataRowCollection expected, string because = "", + params object[] becauseArgs) + { + if (assertion.Subject is ReadOnlyNonGenericCollectionWrapper wrapper) + { + var actualSubject = wrapper.UnderlyingCollection; + + Execute.Assertion + .UsingLineBreaks + .ForCondition(ReferenceEquals(actualSubject, expected)) + .BecauseOf(because, becauseArgs) + .FailWith( + "Expected {context:row collection} to refer to {0}{reason}, but found {1} (different underlying object).", + expected, actualSubject); + } + else + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .FailWith( + "Invalid expectation: Expected {context:column collection} to refer to an instance of " + + "DataRowCollection{reason}, but found {0}.", + assertion.Subject); + } + + return new AndConstraint>(assertion); + } + + /// + /// Asserts that an object reference refers to a different object than another object reference refers to. + /// + /// The unexpected object + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotBeSameAs( + this GenericCollectionAssertions assertion, DataRowCollection unexpected, string because = "", + params object[] becauseArgs) + { + if (assertion.Subject is ReadOnlyNonGenericCollectionWrapper wrapper) + { + var actualSubject = wrapper.UnderlyingCollection; + + Execute.Assertion + .UsingLineBreaks + .ForCondition(!ReferenceEquals(actualSubject, unexpected)) + .BecauseOf(because, becauseArgs) + .FailWith("Did not expect {context:row collection} to refer to {0}{reason}.", unexpected); + } + else + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .FailWith( + "Invalid expectation: Expected {context:column collection} to refer to a different instance of " + + "DataRowCollection{reason}, but found {0}.", + assertion.Subject); + } + + return new AndConstraint>(assertion); + } + + /// + /// Assert that the current collection of s has the same number of rows as + /// . + /// + /// The other collection with the same expected number of elements + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> HaveSameCount( + this GenericCollectionAssertions assertion, DataRowCollection otherCollection, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); + + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:collection} to have ") + .Given(() => assertion.Subject) + .ForCondition(subject => subject is not null) + .FailWith("the same count as {0}{reason}, but found .", otherCollection) + .Then + .Given((subject) => (actual: subject.Count(), expected: otherCollection.Count)) + .ForCondition(count => count.actual == count.expected) + .FailWith("{0} row(s){reason}, but found {1}.", count => count.expected, count => count.actual) + .Then + .ClearExpectation(); + + return new AndConstraint>(assertion); + } + + /// + /// Assert that the current collection of s does not have the same number of rows as + /// . + /// + /// The other with the unexpected number of elements + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotHaveSameCount( + this GenericCollectionAssertions assertion, DataRowCollection otherCollection, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); + + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:collection} to not have ") + .Given(() => assertion.Subject) + .ForCondition(subject => subject is not null) + .FailWith("the same count as {0}{reason}, but found .", otherCollection) + .Then + .Given((subject) => (actual: subject.Count(), expected: otherCollection.Count)) + .ForCondition(count => count.actual != count.expected) + .FailWith("{0} row(s){reason}, but found {1}.", count => count.expected, count => count.actual) + .Then + .ClearExpectation(); + + return new AndConstraint>(assertion); + } + } +} diff --git a/Src/FluentAssertions/DataTableCollectionAssertionExtensions.cs b/Src/FluentAssertions/DataTableCollectionAssertionExtensions.cs new file mode 100644 index 0000000000..76cdf9ea64 --- /dev/null +++ b/Src/FluentAssertions/DataTableCollectionAssertionExtensions.cs @@ -0,0 +1,199 @@ +using System; +using System.Data; +using System.Linq; + +using FluentAssertions.Collections; +using FluentAssertions.Common; +using FluentAssertions.Execution; + +namespace FluentAssertions +{ + public static class DataTableCollectionAssertionExtensions + { + /// + /// Asserts that an object reference refers to the exact same object as another object reference. + /// + /// The expected object + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> BeSameAs( + this GenericCollectionAssertions assertion, DataTableCollection expected, string because = "", + params object[] becauseArgs) + { + if (assertion.Subject is ReadOnlyNonGenericCollectionWrapper wrapper) + { + var actualSubject = wrapper.UnderlyingCollection; + + Execute.Assertion + .UsingLineBreaks + .ForCondition(ReferenceEquals(actualSubject, expected)) + .BecauseOf(because, becauseArgs) + .FailWith( + "Expected {context:table collection} to refer to {0}{reason}, but found {1} (different underlying object).", + expected, actualSubject); + } + else + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .FailWith( + "Invalid expectation: Expected {context:column collection} to refer to an instance of " + + "DataTableCollection{reason}, but found {0}.", + assertion.Subject); + } + + return new AndConstraint>(assertion); + } + + /// + /// Asserts that an object reference refers to a different object than another object reference refers to. + /// + /// The unexpected object + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotBeSameAs( + this GenericCollectionAssertions assertion, DataTableCollection unexpected, string because = "", + params object[] becauseArgs) + { + if (assertion.Subject is ReadOnlyNonGenericCollectionWrapper wrapper) + { + var actualSubject = wrapper.UnderlyingCollection; + + Execute.Assertion + .UsingLineBreaks + .ForCondition(!ReferenceEquals(actualSubject, unexpected)) + .BecauseOf(because, becauseArgs) + .FailWith("Did not expect {context:table collection} to refer to {0}{reason}.", unexpected); + } + else + { + Execute.Assertion + .BecauseOf(because, becauseArgs) + .FailWith( + "Invalid expectation: Expected {context:column collection} to refer to a different instance of " + + "DataTableCollection{reason}, but found {0}.", + assertion.Subject); + } + + return new AndConstraint>(assertion); + } + + /// + /// Assert that the current collection of s has the same number of tables as + /// . + /// + /// The other with the same expected number of tables + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> HaveSameCount( + this GenericCollectionAssertions assertion, DataSet otherDataSet, string because = "", + params object[] becauseArgs) + { + return assertion.HaveSameCount(otherDataSet.Tables, because, becauseArgs); + } + + /// + /// Assert that the current collection of s does not have the same number of tables as + /// . + /// + /// The other with the unexpected number of tables + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotHaveSameCount( + this GenericCollectionAssertions assertion, DataSet otherDataSet, string because = "", + params object[] becauseArgs) + { + return assertion.NotHaveSameCount(otherDataSet.Tables, because, becauseArgs); + } + + /// + /// Assert that the current collection of s has the same number of tables as + /// . + /// + /// The other with the same expected number of tables + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> HaveSameCount( + this GenericCollectionAssertions assertion, DataTableCollection otherCollection, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); + + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:collection} to have ") + .Given(() => assertion.Subject) + .ForCondition(subject => subject is not null) + .FailWith("the same count as {0}{reason}, but found .", otherCollection) + .Then + .Given((subject) => (actual: subject.Count(), expected: otherCollection.Count)) + .ForCondition(count => count.actual == count.expected) + .FailWith("{0} table(s){reason}, but found {1}.", count => count.expected, count => count.actual) + .Then + .ClearExpectation(); + + return new AndConstraint>(assertion); + } + + /// + /// Assert that the current collection of s does not have the same number of tables as + /// . + /// + /// The other with the unexpected number of tables + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public static AndConstraint> NotHaveSameCount( + this GenericCollectionAssertions assertion, DataTableCollection otherCollection, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull( + otherCollection, nameof(otherCollection), "Cannot verify count against a collection."); + + Execute.Assertion + .BecauseOf(because, becauseArgs) + .WithExpectation("Expected {context:collection} to not have ") + .Given(() => assertion.Subject) + .ForCondition(subject => subject is not null) + .FailWith("the same count as {0}{reason}, but found .", otherCollection) + .Then + .Given((subject) => (actual: subject.Count(), expected: otherCollection.Count)) + .ForCondition(count => count.actual != count.expected) + .FailWith("{0} table(s){reason}, but found {1}.", count => count.expected, count => count.actual) + .Then + .ClearExpectation(); + + return new AndConstraint>(assertion); + } + } +} diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt index 4682ecdc00..3ac19edafa 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt @@ -58,6 +58,9 @@ namespace FluentAssertions public static FluentAssertions.Specialized.ActionAssertions Should(this System.Action action) { } public static FluentAssertions.Collections.StringCollectionAssertions Should(this System.Collections.Generic.IEnumerable @this) { } public static FluentAssertions.Data.DataColumnAssertions Should(this System.Data.DataColumn actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataColumnCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataRowCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataTableCollection actualValue) { } public static FluentAssertions.Primitives.DateTimeAssertions Should(this System.DateTime actualValue) { } public static FluentAssertions.Primitives.NullableDateTimeAssertions Should(this System.DateTime? actualValue) { } public static FluentAssertions.Primitives.DateTimeOffsetAssertions Should(this System.DateTimeOffset actualValue) { } @@ -187,11 +190,25 @@ namespace FluentAssertions { public CustomAssertionAttribute() { } } + public static class DataColumnCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataRowAssertionExtensions { public static FluentAssertions.Data.DataRowAssertions Should(this TDataRow actualValue) where TDataRow : System.Data.DataRow { } } + public static class DataRowCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataSetAssertionExtensions { public static FluentAssertions.Data.DataSetAssertions Should(this TDataSet actualValue) @@ -202,6 +219,15 @@ namespace FluentAssertions public static FluentAssertions.Data.DataTableAssertions Should(this TDataTable actualValue) where TDataTable : System.Data.DataTable { } } + public static class DataTableCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class EnumAssertionsExtensions { public static FluentAssertions.Primitives.EnumAssertions Should(this TEnum @enum) diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt index 9fa5350cd3..36cdeff676 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt @@ -58,6 +58,9 @@ namespace FluentAssertions public static FluentAssertions.Specialized.ActionAssertions Should(this System.Action action) { } public static FluentAssertions.Collections.StringCollectionAssertions Should(this System.Collections.Generic.IEnumerable @this) { } public static FluentAssertions.Data.DataColumnAssertions Should(this System.Data.DataColumn actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataColumnCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataRowCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataTableCollection actualValue) { } public static FluentAssertions.Primitives.DateOnlyAssertions Should(this System.DateOnly actualValue) { } public static FluentAssertions.Primitives.NullableDateOnlyAssertions Should(this System.DateOnly? actualValue) { } public static FluentAssertions.Primitives.DateTimeAssertions Should(this System.DateTime actualValue) { } @@ -199,11 +202,25 @@ namespace FluentAssertions { public CustomAssertionAttribute() { } } + public static class DataColumnCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataRowAssertionExtensions { public static FluentAssertions.Data.DataRowAssertions Should(this TDataRow actualValue) where TDataRow : System.Data.DataRow { } } + public static class DataRowCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataSetAssertionExtensions { public static FluentAssertions.Data.DataSetAssertions Should(this TDataSet actualValue) @@ -214,6 +231,15 @@ namespace FluentAssertions public static FluentAssertions.Data.DataTableAssertions Should(this TDataTable actualValue) where TDataTable : System.Data.DataTable { } } + public static class DataTableCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class EnumAssertionsExtensions { public static FluentAssertions.Primitives.EnumAssertions Should(this TEnum @enum) diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt index 16751afb56..7de57cf1c1 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt @@ -58,6 +58,9 @@ namespace FluentAssertions public static FluentAssertions.Specialized.ActionAssertions Should(this System.Action action) { } public static FluentAssertions.Collections.StringCollectionAssertions Should(this System.Collections.Generic.IEnumerable @this) { } public static FluentAssertions.Data.DataColumnAssertions Should(this System.Data.DataColumn actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataColumnCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataRowCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataTableCollection actualValue) { } public static FluentAssertions.Primitives.DateTimeAssertions Should(this System.DateTime actualValue) { } public static FluentAssertions.Primitives.NullableDateTimeAssertions Should(this System.DateTime? actualValue) { } public static FluentAssertions.Primitives.DateTimeOffsetAssertions Should(this System.DateTimeOffset actualValue) { } @@ -187,11 +190,25 @@ namespace FluentAssertions { public CustomAssertionAttribute() { } } + public static class DataColumnCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataRowAssertionExtensions { public static FluentAssertions.Data.DataRowAssertions Should(this TDataRow actualValue) where TDataRow : System.Data.DataRow { } } + public static class DataRowCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataSetAssertionExtensions { public static FluentAssertions.Data.DataSetAssertions Should(this TDataSet actualValue) @@ -202,6 +219,15 @@ namespace FluentAssertions public static FluentAssertions.Data.DataTableAssertions Should(this TDataTable actualValue) where TDataTable : System.Data.DataTable { } } + public static class DataTableCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class EnumAssertionsExtensions { public static FluentAssertions.Primitives.EnumAssertions Should(this TEnum @enum) diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt index f9e4753c6e..9cff0a8291 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt @@ -58,6 +58,9 @@ namespace FluentAssertions public static FluentAssertions.Specialized.ActionAssertions Should(this System.Action action) { } public static FluentAssertions.Collections.StringCollectionAssertions Should(this System.Collections.Generic.IEnumerable @this) { } public static FluentAssertions.Data.DataColumnAssertions Should(this System.Data.DataColumn actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataColumnCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataRowCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataTableCollection actualValue) { } public static FluentAssertions.Primitives.DateTimeAssertions Should(this System.DateTime actualValue) { } public static FluentAssertions.Primitives.NullableDateTimeAssertions Should(this System.DateTime? actualValue) { } public static FluentAssertions.Primitives.DateTimeOffsetAssertions Should(this System.DateTimeOffset actualValue) { } @@ -187,11 +190,25 @@ namespace FluentAssertions { public CustomAssertionAttribute() { } } + public static class DataColumnCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataRowAssertionExtensions { public static FluentAssertions.Data.DataRowAssertions Should(this TDataRow actualValue) where TDataRow : System.Data.DataRow { } } + public static class DataRowCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataSetAssertionExtensions { public static FluentAssertions.Data.DataSetAssertions Should(this TDataSet actualValue) @@ -202,6 +219,15 @@ namespace FluentAssertions public static FluentAssertions.Data.DataTableAssertions Should(this TDataTable actualValue) where TDataTable : System.Data.DataTable { } } + public static class DataTableCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class EnumAssertionsExtensions { public static FluentAssertions.Primitives.EnumAssertions Should(this TEnum @enum) diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt index ec7b7c008f..3391e7ae6c 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt @@ -57,6 +57,9 @@ namespace FluentAssertions public static FluentAssertions.Specialized.ActionAssertions Should(this System.Action action) { } public static FluentAssertions.Collections.StringCollectionAssertions Should(this System.Collections.Generic.IEnumerable @this) { } public static FluentAssertions.Data.DataColumnAssertions Should(this System.Data.DataColumn actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataColumnCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataRowCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataTableCollection actualValue) { } public static FluentAssertions.Primitives.DateTimeAssertions Should(this System.DateTime actualValue) { } public static FluentAssertions.Primitives.NullableDateTimeAssertions Should(this System.DateTime? actualValue) { } public static FluentAssertions.Primitives.DateTimeOffsetAssertions Should(this System.DateTimeOffset actualValue) { } @@ -186,11 +189,25 @@ namespace FluentAssertions { public CustomAssertionAttribute() { } } + public static class DataColumnCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataRowAssertionExtensions { public static FluentAssertions.Data.DataRowAssertions Should(this TDataRow actualValue) where TDataRow : System.Data.DataRow { } } + public static class DataRowCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataSetAssertionExtensions { public static FluentAssertions.Data.DataSetAssertions Should(this TDataSet actualValue) @@ -201,6 +218,15 @@ namespace FluentAssertions public static FluentAssertions.Data.DataTableAssertions Should(this TDataTable actualValue) where TDataTable : System.Data.DataTable { } } + public static class DataTableCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class EnumAssertionsExtensions { public static FluentAssertions.Primitives.EnumAssertions Should(this TEnum @enum) diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt index 25938a8a06..e118ff6c79 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt @@ -58,6 +58,9 @@ namespace FluentAssertions public static FluentAssertions.Specialized.ActionAssertions Should(this System.Action action) { } public static FluentAssertions.Collections.StringCollectionAssertions Should(this System.Collections.Generic.IEnumerable @this) { } public static FluentAssertions.Data.DataColumnAssertions Should(this System.Data.DataColumn actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataColumnCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataRowCollection actualValue) { } + public static FluentAssertions.Collections.GenericCollectionAssertions Should(this System.Data.DataTableCollection actualValue) { } public static FluentAssertions.Primitives.DateTimeAssertions Should(this System.DateTime actualValue) { } public static FluentAssertions.Primitives.NullableDateTimeAssertions Should(this System.DateTime? actualValue) { } public static FluentAssertions.Primitives.DateTimeOffsetAssertions Should(this System.DateTimeOffset actualValue) { } @@ -187,11 +190,25 @@ namespace FluentAssertions { public CustomAssertionAttribute() { } } + public static class DataColumnCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataColumnCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataRowAssertionExtensions { public static FluentAssertions.Data.DataRowAssertions Should(this TDataRow actualValue) where TDataRow : System.Data.DataRow { } } + public static class DataRowCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataRowCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class DataSetAssertionExtensions { public static FluentAssertions.Data.DataSetAssertions Should(this TDataSet actualValue) @@ -202,6 +219,15 @@ namespace FluentAssertions public static FluentAssertions.Data.DataTableAssertions Should(this TDataTable actualValue) where TDataTable : System.Data.DataTable { } } + public static class DataTableCollectionAssertionExtensions + { + public static FluentAssertions.AndConstraint> BeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection expected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> HaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotBeSameAs(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection unexpected, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataSet otherDataSet, string because = "", params object[] becauseArgs) { } + public static FluentAssertions.AndConstraint> NotHaveSameCount(this FluentAssertions.Collections.GenericCollectionAssertions assertion, System.Data.DataTableCollection otherCollection, string because = "", params object[] becauseArgs) { } + } public static class EnumAssertionsExtensions { public static FluentAssertions.Primitives.EnumAssertions Should(this TEnum @enum) diff --git a/Tests/FluentAssertions.Specs/Collections/Data/DataColumnCollectionAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Collections/Data/DataColumnCollectionAssertionSpecs.cs new file mode 100644 index 0000000000..1fd9b4f1c9 --- /dev/null +++ b/Tests/FluentAssertions.Specs/Collections/Data/DataColumnCollectionAssertionSpecs.cs @@ -0,0 +1,441 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using FluentAssertions.Execution; + +using Xunit; +using Xunit.Sdk; + +namespace FluentAssertions.Specs.Collections.Data +{ + public static class DataColumnCollectionAssertionSpecs + { + public class BeSameAs + { + [Fact] + public void When_references_are_the_same_it_should_succeed() + { + // Arrange + var dataTable = new DataTable("Test"); + + var columnCollection1 = dataTable.Columns; + var columnCollection2 = columnCollection1; + + // Act & Assert + columnCollection1.Should().BeSameAs(columnCollection2); + } + + [Fact] + public void When_references_are_different_it_should_fail() + { + // Arrange + var dataTable1 = new DataTable("Test1"); + var dataTable2 = new DataTable("Test2"); + + var columnCollection1 = dataTable1.Columns; + var columnCollection2 = dataTable2.Columns; + + // Act + Action action = + () => columnCollection1.Should().BeSameAs(columnCollection2); + + // Assert + action.Should().Throw().WithMessage( + "Expected columnCollection1 to refer to *, but found * (different underlying object)."); + } + + [Fact] + public void When_generic_collection_is_tested_against_typed_collection_it_should_fail() + { + // Arrange + var dataTable = new DataTable("Test"); + + var columnCollection = dataTable.Columns; + + var genericCollection = columnCollection.Cast(); + + // Act + Action action = + () => genericCollection.Should().BeSameAs(columnCollection, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Invalid expectation: Expected genericCollection to refer to an instance of DataColumnCollection " + + "because we care, but found *."); + } + } + + public class NotBeSameAs + { + [Fact] + public void When_references_are_the_same_it_should_fail() + { + // Arrange + var dataTable = new DataTable("Test"); + + var columnCollection1 = dataTable.Columns; + var columnCollection2 = columnCollection1; + + // Act + Action action = + () => columnCollection1.Should().NotBeSameAs(columnCollection2); + + // Assert + action.Should().Throw().WithMessage("Did not expect columnCollection1 to refer to *."); + } + + [Fact] + public void When_references_are_different_it_should_succeed() + { + // Arrange + var dataTable1 = new DataTable("Test1"); + var dataTable2 = new DataTable("Test2"); + + var columnCollection1 = dataTable1.Columns; + var columnCollection2 = dataTable2.Columns; + + // Act & Assert + columnCollection1.Should().NotBeSameAs(columnCollection2); + } + + [Fact] + public void When_generic_collection_is_tested_against_typed_collection_it_should_fail() + { + // Arrange + var dataTable = new DataTable("Test"); + + var columnCollection = dataTable.Columns; + + var genericCollection = columnCollection.Cast(); + + // Act + Action action = + () => genericCollection.Should().NotBeSameAs(columnCollection, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Invalid expectation: Expected genericCollection to refer to a different instance of " + + "DataColumnCollection because we care, but found *."); + } + } + + public class HaveSameCount + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataColumnCollection); + + var expectation = new DataTable().Columns; + + // Act + Action action = + () => subject.Should().HaveSameCount(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to have the same count as * because we care, but found .*"); + } + + [Fact] + public void When_expectation_is_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add(new DataColumn("Column0")); + dataTable.Columns.Add(new DataColumn("Column1")); + dataTable.Columns.Add(new DataColumn("Column2")); + + var nullReference = default(DataColumnCollection); + + // Act + Action action = + () => dataTable.Columns.Should().HaveSameCount(nullReference); + + // Assert + action.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } + + public class DataColumnCollectionAssertions + { + [Fact] + public void When_two_collections_have_the_same_number_of_columns_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column11")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + // Act & Assert + firstDataTable.Columns.Should().HaveSameCount(secondDataTable.Columns); + } + + [Fact] + public void When_two_collections_do_not_have_the_same_number_of_columns_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + // Act + Action action = + () => firstDataTable.Columns.Should().HaveSameCount(secondDataTable.Columns); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataTable.Columns to have 2 column(s), but found 3."); + } + } + + public class GenericCollectionAssertions + { + [Fact] + public void When_collection_is_compared_with_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add(new DataColumn("Column0")); + dataTable.Columns.Add(new DataColumn("Column1")); + dataTable.Columns.Add(new DataColumn("Column2")); + + List nullDataColumns = null; + + // Act + Action action = + () => nullDataColumns.Should().HaveSameCount(dataTable.Columns, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected nullDataColumns to have the same count as * because we care, but found ."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_same_number_of_columns_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column11")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + var genericDataColumnCollection = firstDataTable.Columns.Cast(); + + // Act & Assert + genericDataColumnCollection.Should().HaveSameCount(secondDataTable.Columns); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_different_number_of_columns_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + var genericDataColumnCollection = firstDataTable.Columns.Cast(); + + // Act + Action action = + () => genericDataColumnCollection.Should().HaveSameCount(secondDataTable.Columns, + because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected genericDataColumnCollection to have 2 column(s) because we care, but found 3."); + } + } + } + + public class NotHaveSameCount + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataColumnCollection); + + var expectation = new DataTable().Columns; + + // Act + Action action = + () => subject.Should().NotHaveSameCount(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to not have the same count as * because we care, but found .*"); + } + + [Fact] + public void When_expectation_is_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add(new DataColumn("Column0")); + dataTable.Columns.Add(new DataColumn("Column1")); + dataTable.Columns.Add(new DataColumn("Column2")); + + var nullReference = default(DataColumnCollection); + + // Act + Action action = + () => dataTable.Columns.Should().NotHaveSameCount(nullReference); + + // Assert + action.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } + + public class DataColumnCollectionAssertions + { + [Fact] + public void When_two_collections_have_different_number_of_columns_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + // Act & Assert + firstDataTable.Columns.Should().NotHaveSameCount(secondDataTable.Columns); + } + + [Fact] + public void When_two_collections_have_the_same_number_of_columns_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column11")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + // Act + Action action = + () => firstDataTable.Columns.Should().NotHaveSameCount(secondDataTable.Columns, + because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataTable.Columns to not have 3 column(s) because we care, but found 3."); + } + } + + public class GenericCollectionAssertions + { + [Fact] + public void When_collection_is_compared_with_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add(new DataColumn("Column0")); + dataTable.Columns.Add(new DataColumn("Column1")); + dataTable.Columns.Add(new DataColumn("Column2")); + + List nullDataColumns = null; + + // Act + Action action = + () => nullDataColumns.Should().NotHaveSameCount(dataTable.Columns, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected nullDataColumns to not have the same count as * because we care, but found ."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_same_number_of_columns_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column11")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + var genericDataColumnCollection = firstDataTable.Columns.Cast(); + + // Act + Action action = + () => genericDataColumnCollection.Should().NotHaveSameCount(secondDataTable.Columns, + because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected genericDataColumnCollection to not have 3 column(s) because we care, but found 3."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_different_number_of_columns_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Columns.Add(new DataColumn("Column0")); + firstDataTable.Columns.Add(new DataColumn("Column1")); + firstDataTable.Columns.Add(new DataColumn("Column2")); + + secondDataTable.Columns.Add(new DataColumn("Column10")); + secondDataTable.Columns.Add(new DataColumn("Column12")); + + var genericDataColumnCollection = firstDataTable.Columns.Cast(); + + // Act & Assert + genericDataColumnCollection.Should().NotHaveSameCount(secondDataTable.Columns); + } + } + } + } +} diff --git a/Tests/FluentAssertions.Specs/Collections/Data/DataRowCollectionAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Collections/Data/DataRowCollectionAssertionSpecs.cs new file mode 100644 index 0000000000..fdcde5ea45 --- /dev/null +++ b/Tests/FluentAssertions.Specs/Collections/Data/DataRowCollectionAssertionSpecs.cs @@ -0,0 +1,608 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using FluentAssertions.Execution; + +using Xunit; +using Xunit.Sdk; + +namespace FluentAssertions.Specs.Collections.Data +{ + public static class DataRowCollectionAssertionSpecs + { + public class BeSameAs + { + [Fact] + public void When_references_are_the_same_it_should_succeed() + { + // Arrange + var dataTable = new DataTable("Test"); + + var rowCollection1 = dataTable.Rows; + var rowCollection2 = rowCollection1; + + // Act & Assert + rowCollection1.Should().BeSameAs(rowCollection2); + } + + [Fact] + public void When_references_are_different_it_should_fail() + { + // Arrange + var dataTable1 = new DataTable("Test1"); + var dataTable2 = new DataTable("Test2"); + + var rowCollection1 = dataTable1.Rows; + var rowCollection2 = dataTable2.Rows; + + // Act + Action action = + () => rowCollection1.Should().BeSameAs(rowCollection2); + + // Assert + action.Should().Throw().WithMessage( + "Expected rowCollection1 to refer to *, but found * (different underlying object)."); + } + + [Fact] + public void When_generic_collection_is_tested_against_typed_collection_it_should_fail() + { + // Arrange + var dataTable = new DataTable("Test"); + + var rowCollection = dataTable.Rows; + + var genericCollection = rowCollection.Cast(); + + // Act + Action action = + () => genericCollection.Should().BeSameAs(rowCollection, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Invalid expectation: Expected genericCollection to refer to an instance of DataRowCollection " + + "because we care, but found *."); + } + } + + public class NotBeSameAs + { + [Fact] + public void When_references_are_the_same_object_it_should_fail() + { + // Arrange + var dataTable = new DataTable("Test"); + + var rowCollection1 = dataTable.Rows; + var rowCollection2 = rowCollection1; + + // Act + Action action = + () => rowCollection1.Should().NotBeSameAs(rowCollection2); + + // Assert + action.Should().Throw().WithMessage("Did not expect rowCollection1 to refer to *."); + } + + [Fact] + public void When_references_are_different_it_should_succeed() + { + // Arrange + var dataTable1 = new DataTable("Test1"); + var dataTable2 = new DataTable("Test2"); + + var rowCollection1 = dataTable1.Rows; + var rowCollection2 = dataTable2.Rows; + + // Act & Assert + rowCollection1.Should().NotBeSameAs(rowCollection2); + } + + [Fact] + public void When_generic_collection_is_tested_against_typed_collection_it_should_fail() + { + // Arrange + var dataTable = new DataTable("Test"); + + var rowCollection = dataTable.Rows; + + var genericCollection = rowCollection.Cast(); + + // Act + Action action = + () => genericCollection.Should().NotBeSameAs(rowCollection, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Invalid expectation: Expected genericCollection to refer to a different instance of " + + "DataRowCollection because we care, but found *."); + } + } + + public class HaveSameCount + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataRowCollection); + + var expectation = new DataTable().Rows; + + // Act + Action action = + () => subject.Should().HaveSameCount(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to have the same count as * because we care, but found .*"); + } + + [Fact] + public void When_expectation_is_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + var nullReference = default(DataRowCollection); + + // Act + Action action = + () => dataTable.Rows.Should().HaveSameCount(nullReference); + + // Assert + action.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } + + public class DataRowCollectionAssertions + { + [Fact] + public void When_two_collections_have_the_same_number_of_rows_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + // Act & Assert + firstDataTable.Rows.Should().HaveSameCount(secondDataTable.Rows); + } + + [Fact] + public void When_two_collections_do_not_have_the_same_number_of_rows_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + // Act + Action action = + () => firstDataTable.Rows.Should().HaveSameCount(secondDataTable.Rows); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataTable.Rows to have 2 row(s), but found 3."); + } + } + + public class GenericCollectionAssertions + { + [Fact] + public void When_collection_is_compared_with_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + List nullDataRows = null; + + // Act + Action action = + () => nullDataRows.Should().HaveSameCount(dataTable.Rows, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected nullDataRows to have the same count as * because we care, but found ."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_same_number_of_rows_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + var genericDataRowCollection = firstDataTable.Rows.Cast(); + + // Act & Assert + genericDataRowCollection.Should().HaveSameCount(secondDataTable.Rows); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_different_number_of_rows_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + var genericDataRowCollection = firstDataTable.Rows.Cast(); + + // Act + Action action = + () => genericDataRowCollection.Should().HaveSameCount(secondDataTable.Rows, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected genericDataRowCollection to have 2 row(s) because we care, but found 3."); + } + } + } + + public class NotHaveSameCount + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataRowCollection); + + var expectation = new DataTable().Rows; + + // Act + Action action = + () => subject.Should().NotHaveSameCount(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to not have the same count as * because we care, but found .*"); + } + + [Fact] + public void When_expectation_is_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + var nullReference = default(DataRowCollection); + + // Act + Action action = + () => dataTable.Rows.Should().NotHaveSameCount(nullReference); + + // Assert + action.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } + + public class DataRowCollectionAssertions + { + [Fact] + public void When_two_collections_have_different_number_of_rows_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + // Act & Assert + firstDataTable.Rows.Should().NotHaveSameCount(secondDataTable.Rows); + } + + [Fact] + public void When_two_collections_have_the_same_number_rows_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + // Act + Action action = + () => firstDataTable.Rows.Should().NotHaveSameCount(secondDataTable.Rows, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataTable.Rows to not have 3 row(s) because we care, but found 3."); + } + } + + public class GenericCollectionAssertions + { + [Fact] + public void When_collection_is_compared_with_null_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Rows.Add(); + dataTable.Rows.Add(); + dataTable.Rows.Add(); + + List nullDataRows = null; + + // Act + Action action = + () => nullDataRows.Should().NotHaveSameCount(dataTable.Rows, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected nullDataRows to not have the same count as * because we care, but found ."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_same_number_of_rows_it_should_fail() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + var genericDataRowCollection = firstDataTable.Rows.Cast(); + + // Act + Action action = + () => genericDataRowCollection.Should().NotHaveSameCount(secondDataTable.Rows, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected genericDataRowCollection to not have 3 row(s) because we care, but found 3."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_different_number_of_rows_it_should_succeed() + { + // Arrange + var firstDataTable = new DataTable(); + var secondDataTable = new DataTable(); + + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + firstDataTable.Rows.Add(); + + secondDataTable.Rows.Add(); + secondDataTable.Rows.Add(); + + var genericDataRowCollection = firstDataTable.Rows.Cast(); + + // Act & Assert + genericDataRowCollection.Should().NotHaveSameCount(secondDataTable.Rows); + } + } + } + + // These tests are present to ensure that we can trust DataRow equivalency in the context of ContainEquivalentOf. + public class ContainEquivalentOf + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataRowCollection); + + var expectation = new DataTable().Rows; + + // Act + Action action = + () => subject.Should().ContainEquivalentOf(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to contain equivalent of * because we care, but found .*"); + } + + [Fact] + public void When_collection_contains_equivalent_row_it_should_succeed() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add("RowID", typeof(Guid)); + dataTable.Columns.Add("Description", typeof(string)); + dataTable.Columns.Add("Number", typeof(int)); + dataTable.Columns.Add("Flag", typeof(bool)); + dataTable.Columns.Add("Timestamp", typeof(DateTime)); + + dataTable.Rows.Add(new Guid("6f460c1a-755d-d8e4-ad67-65d5f519dbc8"), "1851925803", 2137491580, true, new DateTime(638898932425580731)); + dataTable.Rows.Add(new Guid("8286d046-9740-a3e4-95cf-ff46699c73c4"), "607156385", 1321446349, true, new DateTime(641752306337096884)); + dataTable.Rows.Add(new Guid("95c69371-b924-6fe3-7c38-98b7dd200bc1"), "1509870614", 505401118, true, new DateTime(623130841631129390)); + + var subjectTable = new DataTable(); + + subjectTable.Columns.Add("RowID", typeof(Guid)); + subjectTable.Columns.Add("Description", typeof(string)); + subjectTable.Columns.Add("Number", typeof(int)); + subjectTable.Columns.Add("Flag", typeof(bool)); + subjectTable.Columns.Add("Timestamp", typeof(DateTime)); + + subjectTable.Rows.Add(new Guid("95c69371-b924-6fe3-7c38-98b7dd200bc1"), "1509870614", 505401118, true, new DateTime(623130841631129390)); + + var subjectRow = subjectTable.Rows[0]; + + // Act & Assert + dataTable.Rows.Should().ContainEquivalentOf(subjectRow); + } + + [Fact] + public void When_collection_does_not_contain_equivalent_row_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add("RowID", typeof(Guid)); + dataTable.Columns.Add("Description", typeof(string)); + dataTable.Columns.Add("Number", typeof(int)); + dataTable.Columns.Add("Flag", typeof(bool)); + dataTable.Columns.Add("Timestamp", typeof(DateTime)); + + dataTable.Rows.Add(new Guid("8286d046-9740-a3e4-95cf-ff46699c73c4"), "607156385", 1321446349, true, new DateTime(641752306337096884)); + dataTable.Rows.Add(new Guid("95c69371-b924-6fe3-7c38-98b7dd200bc1"), "1509870614", 505401118, true, new DateTime(623130841631129390)); + dataTable.Rows.Add(new Guid("a905569d-db07-3ae3-63a0-322750a4a3bd"), "265101196", 1836839534, true, new DateTime(625984215542645543)); + + var subjectTable = new DataTable(); + + subjectTable.Columns.Add("RowID", typeof(Guid)); + subjectTable.Columns.Add("Description", typeof(string)); + subjectTable.Columns.Add("Number", typeof(int)); + subjectTable.Columns.Add("Flag", typeof(bool)); + subjectTable.Columns.Add("Timestamp", typeof(DateTime)); + + subjectTable.Rows.Add(new Guid("bc4519c8-fdeb-06e2-4a08-cc98c4273aba"), "1167815425", 1020794303, true, new DateTime(628837589454161696)); + + var subjectRow = subjectTable.Rows[0]; + + // Act + Action action = + () => dataTable.Rows.Should().ContainEquivalentOf(subjectRow, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected dataTable.Rows * to contain equivalent of System.Data.DataRow* because we care.*"); + } + } + + // These tests are present to ensure that we can trust DataRow equivalency in the context of NotContainEquivalentOf. + public class NotContainEquivalentOf + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataRowCollection); + + var expectation = new DataTable().Rows; + + // Act + Action action = + () => subject.Should().NotContainEquivalentOf(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * not to contain equivalent of * because we care, but collection is .*"); + } + + [Fact] + public void When_collection_contains_equivalent_row_it_should_fail() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add("RowID", typeof(Guid)); + dataTable.Columns.Add("Description", typeof(string)); + dataTable.Columns.Add("Number", typeof(int)); + dataTable.Columns.Add("Flag", typeof(bool)); + dataTable.Columns.Add("Timestamp", typeof(DateTime)); + + dataTable.Rows.Add(new Guid("8286d046-9740-a3e4-95cf-ff46699c73c4"), "607156385", 1321446349, true, new DateTime(641752306337096884)); + dataTable.Rows.Add(new Guid("95c69371-b924-6fe3-7c38-98b7dd200bc1"), "1509870614", 505401118, true, new DateTime(623130841631129390)); + dataTable.Rows.Add(new Guid("a905569d-db07-3ae3-63a0-322750a4a3bd"), "265101196", 1836839534, true, new DateTime(625984215542645543)); + + var subjectTable = new DataTable(); + + subjectTable.Columns.Add("RowID", typeof(Guid)); + subjectTable.Columns.Add("Description", typeof(string)); + subjectTable.Columns.Add("Number", typeof(int)); + subjectTable.Columns.Add("Flag", typeof(bool)); + subjectTable.Columns.Add("Timestamp", typeof(DateTime)); + + subjectTable.Rows.Add(new Guid("95c69371-b924-6fe3-7c38-98b7dd200bc1"), "1509870614", 505401118, true, new DateTime(623130841631129390)); + + var subjectRow = subjectTable.Rows[0]; + + // Act + Action action = + () => dataTable.Rows.Should().NotContainEquivalentOf(subjectRow, because: "we {0}", "care"); + + // Assert + action.Should().Throw() + .WithMessage("Expected dataTable.Rows * not to contain equivalent of System.Data.DataRow* because we " + + "care, but found one at index 1.*"); + } + + [Fact] + public void When_collection_does_not_contain_equivalent_row_it_should_succeed() + { + // Arrange + var dataTable = new DataTable(); + + dataTable.Columns.Add("RowID", typeof(Guid)); + dataTable.Columns.Add("Description", typeof(string)); + dataTable.Columns.Add("Number", typeof(int)); + dataTable.Columns.Add("Flag", typeof(bool)); + dataTable.Columns.Add("Timestamp", typeof(DateTime)); + + dataTable.Rows.Add(new Guid("8286d046-9740-a3e4-95cf-ff46699c73c4"), "607156385", 1321446349, true, new DateTime(641752306337096884)); + dataTable.Rows.Add(new Guid("95c69371-b924-6fe3-7c38-98b7dd200bc1"), "1509870614", 505401118, true, new DateTime(623130841631129390)); + dataTable.Rows.Add(new Guid("a905569d-db07-3ae3-63a0-322750a4a3bd"), "265101196", 1836839534, true, new DateTime(625984215542645543)); + + var subjectTable = new DataTable(); + + subjectTable.Columns.Add("RowID", typeof(Guid)); + subjectTable.Columns.Add("Description", typeof(string)); + subjectTable.Columns.Add("Number", typeof(int)); + subjectTable.Columns.Add("Flag", typeof(bool)); + subjectTable.Columns.Add("Timestamp", typeof(DateTime)); + + subjectTable.Rows.Add(new Guid("bc4519c8-fdeb-06e2-4a08-cc98c4273aba"), "1167815425", 1020794303, true, new DateTime(628837589454161696)); + + var subjectRow = subjectTable.Rows[0]; + + // Act & Assert + dataTable.Rows.Should().NotContainEquivalentOf(subjectRow); + } + } + } +} diff --git a/Tests/FluentAssertions.Specs/Collections/Data/DataTableCollectionAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Collections/Data/DataTableCollectionAssertionSpecs.cs new file mode 100644 index 0000000000..de934009e0 --- /dev/null +++ b/Tests/FluentAssertions.Specs/Collections/Data/DataTableCollectionAssertionSpecs.cs @@ -0,0 +1,545 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using FluentAssertions.Execution; + +using Xunit; +using Xunit.Sdk; + +namespace FluentAssertions.Specs.Collections.Data +{ + public static class DataTableCollectionAssertionSpecs + { + public class BeSameAs + { + [Fact] + public void When_references_are_the_same_it_should_succeed() + { + // Arrange + var dataSet = new DataSet(); + + dataSet.Tables.Add(new DataTable("Table1")); + + var tableCollection1 = dataSet.Tables; + var tableCollection2 = tableCollection1; + + // Act & Assert + tableCollection1.Should().BeSameAs(tableCollection2); + } + + [Fact] + public void When_references_are_different_it_should_fail() + { + // Arrange + var dataSet1 = new DataSet(); + var dataSet2 = new DataSet(); + + dataSet1.Tables.Add(new DataTable("Table1")); + dataSet2.Tables.Add(new DataTable("Table1")); + + var tableCollection1 = dataSet1.Tables; + var tableCollection2 = dataSet2.Tables; + + // Act + Action action = + () => tableCollection1.Should().BeSameAs(tableCollection2); + + // Assert + action.Should().Throw().WithMessage( + "Expected tableCollection1 to refer to *, but found * (different underlying object)."); + } + + [Fact] + public void When_generic_collection_is_tested_against_typed_collection_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + var tableCollection = dataSet.Tables; + + var genericCollection = tableCollection.Cast(); + + // Act + Action action = + () => genericCollection.Should().BeSameAs(tableCollection, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Invalid expectation: Expected genericCollection to refer to an instance of DataTableCollection " + + "because we care, but found *."); + } + } + + public class NotBeSameAs + { + [Fact] + public void When_references_are_the_same_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + dataSet.Tables.Add(new DataTable("Table1")); + + var tableCollection1 = dataSet.Tables; + var tableCollection2 = tableCollection1; + + // Act + Action action = + () => tableCollection1.Should().NotBeSameAs(tableCollection2); + + // Assert + action.Should().Throw().WithMessage( + "Did not expect tableCollection1 to refer to *."); + } + + [Fact] + public void When_references_are_different_it_should_succeed() + { + // Arrange + var dataSet1 = new DataSet(); + var dataSet2 = new DataSet(); + + dataSet1.Tables.Add(new DataTable("Table1")); + dataSet2.Tables.Add(new DataTable("Table1")); + + var tableCollection1 = dataSet1.Tables; + var tableCollection2 = dataSet2.Tables; + + // Act & Assert + tableCollection1.Should().NotBeSameAs(tableCollection2); + } + + [Fact] + public void When_generic_collection_is_tested_against_typed_collection_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + var tableCollection = dataSet.Tables; + + var genericCollection = tableCollection.Cast(); + + // Act + Action action = + () => genericCollection.Should().NotBeSameAs(tableCollection, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Invalid expectation: Expected genericCollection to refer to a different instance of " + + "DataTableCollection because we care, but found *."); + } + } + + public class HaveSameCount + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataTableCollection); + + var expectation = new DataSet().Tables; + + // Act + Action action = + () => subject.Should().HaveSameCount(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to have the same count as * because we care, but found .*"); + } + + [Fact] + public void When_expectation_is_null_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + var nullReference = default(DataTableCollection); + + // Act + Action action = + () => dataSet.Tables.Should().HaveSameCount(nullReference); + + // Assert + action.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } + + public class DataSetAssertions + { + [Fact] + public void When_collections_have_the_same_number_of_tables_it_should_succeed() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table11")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Ensure that the table schema isn't important for the count comparison. + secondDataSet.Tables[0].Columns.Add("Column1", typeof(int)); + + // Act & Assert + firstDataSet.Tables.Should().HaveSameCount(secondDataSet, because: "we {0}", "care"); + } + + [Fact] + public void When_collections_do_not_have_the_same_number_of_tables_it_should_fail() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Act + Action action = + () => firstDataSet.Tables.Should().HaveSameCount(secondDataSet, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataSet.Tables to have 2 table(s) because we care, but found 3."); + } + } + + public class DataTableCollectionAssertions + { + [Fact] + public void When_collections_have_the_same_number_of_tables_it_should_succeed() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table11")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Ensure that the table schema isn't important for the count comparison. + secondDataSet.Tables[0].Columns.Add("Column1", typeof(int)); + + // Act & Assert + firstDataSet.Tables.Should().HaveSameCount(secondDataSet.Tables); + } + + [Fact] + public void When_collections_do_not_have_the_same_number_of_tables_it_should_fail() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Act + Action action = + () => firstDataSet.Tables.Should().HaveSameCount(secondDataSet.Tables); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataSet.Tables to have 2 table(s), but found 3."); + } + } + + public class GenericCollectionAssertions + { + [Fact] + public void When_collection_is_compared_with_null_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + dataSet.Tables.Add(new DataTable("Table0")); + dataSet.Tables.Add(new DataTable("Table1")); + dataSet.Tables.Add(new DataTable("Table2")); + + List nullDataTables = null; + + // Act + Action action = + () => nullDataTables.Should().HaveSameCount(dataSet.Tables, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected nullDataTables to have the same count as * because we care, but found ."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_same_number_of_tables_it_should_succeed() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table11")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Ensure that the table schema isn't important for the count comparison. + secondDataSet.Tables[0].Columns.Add("Column1", typeof(int)); + + var genericDataTableCollection = firstDataSet.Tables.Cast(); + + // Act & Assert + genericDataTableCollection.Should().HaveSameCount(secondDataSet.Tables); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_different_number_of_tables_it_should_fail() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + var genericDataTableCollection = firstDataSet.Tables.Cast(); + + // Act + Action action = + () => genericDataTableCollection.Should().HaveSameCount(secondDataSet.Tables, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected genericDataTableCollection to have 2 table(s) because we care, but found 3."); + } + } + } + + public class NotHaveSameCount + { + [Fact] + public void When_subject_is_null_it_should_fail() + { + // Arrange + var subject = default(DataTableCollection); + + var expectation = new DataSet().Tables; + + // Act + Action action = + () => subject.Should().NotHaveSameCount(expectation, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected * to not have the same count as * because we care, but found .*"); + } + + [Fact] + public void When_expectation_is_null_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + dataSet.Tables.Add(new DataTable("Table0")); + dataSet.Tables.Add(new DataTable("Table1")); + dataSet.Tables.Add(new DataTable("Table2")); + + var nullReference = default(DataTableCollection); + + // Act + Action action = + () => dataSet.Tables.Should().NotHaveSameCount(nullReference); + + // Assert + action.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } + + public class DataTableCollectionAssertions + { + [Fact] + public void When_two_collections_have_different_number_of_tables_it_should_succeed() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Act & Assert + firstDataSet.Tables.Should().NotHaveSameCount(secondDataSet.Tables); + } + + [Fact] + public void When_two_collections_have_the_same_number_of_tables_it_should_fail() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table11")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Act + Action action = + () => firstDataSet.Tables.Should().NotHaveSameCount(secondDataSet.Tables, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataSet.Tables to not have 3 table(s) because we care, but found 3."); + } + } + + public class DataSetAssertions + { + [Fact] + public void When_two_collections_have_different_number_of_tables_it_should_succeed() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Act & Assert + firstDataSet.Tables.Should().NotHaveSameCount(secondDataSet, because: "we {0}", "care"); + } + + [Fact] + public void When_two_collections_have_the_same_number_of_tables_it_should_fail() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table11")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + // Act + Action action = + () => firstDataSet.Tables.Should().NotHaveSameCount(secondDataSet, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected firstDataSet.Tables to not have 3 table(s) because we care, but found 3."); + } + } + + public class GenericCollectionAssertions + { + [Fact] + public void When_collection_is_compared_with_null_it_should_fail() + { + // Arrange + var dataSet = new DataSet(); + + dataSet.Tables.Add(new DataTable("Table0")); + dataSet.Tables.Add(new DataTable("Table1")); + dataSet.Tables.Add(new DataTable("Table2")); + + List nullDataTables = null; + + // Act + Action action = + () => nullDataTables.Should().NotHaveSameCount(dataSet.Tables, because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected nullDataTables to not have the same count as * because we care, but found ."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_same_number_of_tables_it_should_fail() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table11")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + var genericDataTableCollection = firstDataSet.Tables.Cast(); + + // Act + Action action = + () => genericDataTableCollection.Should().NotHaveSameCount(secondDataSet.Tables, + because: "we {0}", "care"); + + // Assert + action.Should().Throw().WithMessage( + "Expected genericDataTableCollection to not have 3 table(s) because we care, but found 3."); + } + + [Fact] + public void When_collection_is_compared_with_typed_collection_with_different_number_of_tables_it_should_succeed() + { + // Arrange + var firstDataSet = new DataSet(); + var secondDataSet = new DataSet(); + + firstDataSet.Tables.Add(new DataTable("Table0")); + firstDataSet.Tables.Add(new DataTable("Table1")); + firstDataSet.Tables.Add(new DataTable("Table2")); + + secondDataSet.Tables.Add(new DataTable("Table10")); + secondDataSet.Tables.Add(new DataTable("Table12")); + + var genericDataTableCollection = firstDataSet.Tables.Cast(); + + // Act & Assert + genericDataTableCollection.Should().NotHaveSameCount(secondDataSet.Tables); + } + } + } + } +} diff --git a/docs/_pages/data.md b/docs/_pages/data.md index 0815c27632..3d7fb7c94c 100644 --- a/docs/_pages/data.md +++ b/docs/_pages/data.md @@ -82,6 +82,26 @@ When checking the equivalency of two `DataRow` objects, by default the `RowState In addition, if both the subject and the expectation are in the `DataRowState.Modified` state, then the `DataRowVersion.Original` values are also compared, separately from the `DataRowVersion.Current` values. This can be disabled using the `.ExcludingOriginalData()` equivalency assertion option. +## Collections + +Each `DataSet` has a `DataTableCollection` called `Tables`, and each `DataTable` has a `DataColumnCollection` called `Columns` and a `DataRowCollection` called `Rows`. Some assertions can be performed on these collection types. + +The following assertions are in common to all three collection types: + +* `.Should().BeEmpty()`: Succeeds if the collection contains no items (tables, columns, rows). +* `.Should().NotBeEmpty()`: Succeeds if the collection contains at least one item (table, column, row). +* `.Should().ContainEquivalentOf(x)`: Succeeds if the collection contains an item (table, column, row) that is equivalent to the supplied item. +* `.Should().NotContainEquivalentOf(x)`: Succeeds if the item does not contain any item (table, column, row) that is equivalent to the supplied item. +* `.Should().HaveSameCount(x)`: Succeeds if the collection contains the same number of items as the supplied collection of the same type. +* `.Should().NotHaveSameCount(x)`: Succeeds if the collection does not contain the same number of items as the supplied collection of the same type. +* `.Should().HaveCount(x)`: Succeeds if the collection contains exactly the specified number of items. +* `.Should().HaveCount(predicate)`: Succeeds if the predicate returns true for the number of items in the collection. +* `.Should().NotHaveCount(x)`: Succeeds if the collection contains a different number of items than the supplied count. +* `.Should().HaveCountGreaterThan(x)`: Succeeds if the collection contains more items than the supplied count. +* `.Should().HaveCountGreaterThanOrEqualTo(x)`: Succeeds if the collection contains at least as many items as the supplied count. +* `.Should().HaveCountLessThan(x)`: Succeeds if the collection contains fewer items than the supplied count. +* `.Should().HaveCountLessThanOrEqualTo(x)`: Succeeds if the collection contains at most as many items as the supplied count. + ## Equivalency Assertion Options When checking equivalency, the operation can be fine-tuned by configuring the options provided to an optional configuration callback in the `.BeEquivalentTo` method. diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index de4a23955d..9c28ca607b 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -27,6 +27,7 @@ sidebar: * Ensure `ExcludingMissingMembers` doesn't undo usage of `WithMapping` in `BeEquivalentTo` - [#1838](https://github.com/fluentassertions/fluentassertions/pull/1838) * Better handling of NaN in various numeric assertions - [#1822](https://github.com/fluentassertions/fluentassertions/pull/1822) & [#1867](https://github.com/fluentassertions/fluentassertions/pull/1867) * `WithMapping` in `BeEquivalentTo` now also works when the root is a collection - [#1858](https://github.com/fluentassertions/fluentassertions/pull/1858) +* Assertions on the collection types in System.Data (`DataSet.Tables`, `DataTable.Columns`, `DataTable.Rows`) have been restored - [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) ### Fixes (Extensibility) From e87aa943e7521f45609a0bc89b2aa279e3797bed Mon Sep 17 00:00:00 2001 From: Jonathan Gilbert Date: Sat, 16 Apr 2022 03:08:45 -0500 Subject: [PATCH 15/48] Add the ability to exclude non-browsable members from equivalency tests (#1827) --- ...llectionMemberAssertionOptionsDecorator.cs | 4 + Src/FluentAssertions/Equivalency/Field.cs | 15 + .../IEquivalencyAssertionOptions.cs | 14 + Src/FluentAssertions/Equivalency/IMember.cs | 8 + .../Matching/MustMatchByNameRule.cs | 7 + Src/FluentAssertions/Equivalency/Property.cs | 15 + .../ExcludeNonBrowsableMembersRule.cs | 16 + ...elfReferenceEquivalencyAssertionOptions.cs | 51 ++ .../StructuralEqualityEquivalencyStep.cs | 5 + .../FluentAssertions/net47.verified.txt | 7 + .../FluentAssertions/net6.0.verified.txt | 7 + .../netcoreapp2.1.verified.txt | 7 + .../netcoreapp3.0.verified.txt | 7 + .../netstandard2.0.verified.txt | 7 + .../netstandard2.1.verified.txt | 7 + Tests/Benchmarks/CheckIfMemberIsBrowsable.cs | 28 ++ Tests/Benchmarks/Program.cs | 2 +- .../UsersOfGetClosedGenericInterfaces.cs | 4 + .../SelectionRulesSpecs.cs | 448 ++++++++++++++++++ docs/_pages/objectgraphs.md | 21 + docs/_pages/releases.md | 3 +- 21 files changed, 681 insertions(+), 2 deletions(-) create mode 100644 Src/FluentAssertions/Equivalency/Selection/ExcludeNonBrowsableMembersRule.cs create mode 100644 Tests/Benchmarks/CheckIfMemberIsBrowsable.cs diff --git a/Src/FluentAssertions/Equivalency/Execution/CollectionMemberAssertionOptionsDecorator.cs b/Src/FluentAssertions/Equivalency/Execution/CollectionMemberAssertionOptionsDecorator.cs index 86c06cf999..86ec59e34a 100644 --- a/Src/FluentAssertions/Equivalency/Execution/CollectionMemberAssertionOptionsDecorator.cs +++ b/Src/FluentAssertions/Equivalency/Execution/CollectionMemberAssertionOptionsDecorator.cs @@ -61,6 +61,10 @@ public IEnumerable UserEquivalencySteps public MemberVisibility IncludedFields => inner.IncludedFields; + public bool IgnoreNonBrowsableOnSubject => inner.IgnoreNonBrowsableOnSubject; + + public bool ExcludeNonBrowsableOnExpectation => inner.ExcludeNonBrowsableOnExpectation; + public bool CompareRecordsByValue => inner.CompareRecordsByValue; public EqualityStrategy GetEqualityStrategy(Type type) diff --git a/Src/FluentAssertions/Equivalency/Field.cs b/Src/FluentAssertions/Equivalency/Field.cs index 04b06c32da..9c1720b9c6 100644 --- a/Src/FluentAssertions/Equivalency/Field.cs +++ b/Src/FluentAssertions/Equivalency/Field.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Reflection; using FluentAssertions.Common; @@ -10,6 +11,7 @@ namespace FluentAssertions.Equivalency public class Field : Node, IMember { private readonly FieldInfo fieldInfo; + private bool? isBrowsable; public Field(FieldInfo fieldInfo, INode parent) : this(fieldInfo.ReflectedType, fieldInfo, parent) @@ -42,5 +44,18 @@ public object GetValue(object obj) public CSharpAccessModifier GetterAccessibility => fieldInfo.GetCSharpAccessModifier(); public CSharpAccessModifier SetterAccessibility => fieldInfo.GetCSharpAccessModifier(); + + public bool IsBrowsable + { + get + { + if (isBrowsable == null) + { + isBrowsable = fieldInfo.GetCustomAttribute() is not { State: EditorBrowsableState.Never }; + } + + return isBrowsable.Value; + } + } } } diff --git a/Src/FluentAssertions/Equivalency/IEquivalencyAssertionOptions.cs b/Src/FluentAssertions/Equivalency/IEquivalencyAssertionOptions.cs index bcc5a61199..6c0ff7279e 100644 --- a/Src/FluentAssertions/Equivalency/IEquivalencyAssertionOptions.cs +++ b/Src/FluentAssertions/Equivalency/IEquivalencyAssertionOptions.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.ComponentModel; + using FluentAssertions.Equivalency.Tracing; namespace FluentAssertions.Equivalency @@ -71,6 +73,18 @@ public interface IEquivalencyAssertionOptions /// MemberVisibility IncludedFields { get; } + /// + /// Gets a value indicating whether members on the subject marked with [] + /// and should be treated as though they don't exist. + /// + bool IgnoreNonBrowsableOnSubject { get; } + + /// + /// Gets a value indicating whether members on the expectation marked with [] + /// and should be excluded. + /// + bool ExcludeNonBrowsableOnExpectation { get; } + /// /// Gets a value indicating whether records should be compared by value instead of their members /// diff --git a/Src/FluentAssertions/Equivalency/IMember.cs b/Src/FluentAssertions/Equivalency/IMember.cs index f14c39ab95..91f4acc169 100644 --- a/Src/FluentAssertions/Equivalency/IMember.cs +++ b/Src/FluentAssertions/Equivalency/IMember.cs @@ -1,4 +1,6 @@ using System; +using System.ComponentModel; + using FluentAssertions.Common; namespace FluentAssertions.Equivalency @@ -32,5 +34,11 @@ public interface IMember : INode /// Gets the access modifier for the setter of this member. /// CSharpAccessModifier SetterAccessibility { get; } + + /// + /// Gets a value indicating whether the member is browsable in the source code editor. This is controlled with + /// . + /// + bool IsBrowsable { get; } } } diff --git a/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs b/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs index e386b51d07..64ee48c4ea 100644 --- a/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs +++ b/Src/FluentAssertions/Equivalency/Matching/MustMatchByNameRule.cs @@ -36,6 +36,13 @@ public IMember Match(IMember expectedMember, object subject, INode parent, IEqui $"Expectation has {expectedMember.Description} that the other object does not have."); } + if (config.IgnoreNonBrowsableOnSubject && !subjectMember.IsBrowsable) + { + Execute.Assertion.FailWith( + $"Expectation has {expectedMember.Description} that is non-browsable in the other object, and non-browsable " + + $"members on the subject are ignored with the current configuration"); + } + return subjectMember; } diff --git a/Src/FluentAssertions/Equivalency/Property.cs b/Src/FluentAssertions/Equivalency/Property.cs index f53eeab7a0..de3741bb9a 100644 --- a/Src/FluentAssertions/Equivalency/Property.cs +++ b/Src/FluentAssertions/Equivalency/Property.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Reflection; using FluentAssertions.Common; @@ -11,6 +12,7 @@ namespace FluentAssertions.Equivalency public class Property : Node, IMember { private readonly PropertyInfo propertyInfo; + private bool? isBrowsable; public Property(PropertyInfo propertyInfo, INode parent) : this(propertyInfo.ReflectedType, propertyInfo, parent) @@ -43,5 +45,18 @@ public object GetValue(object obj) public CSharpAccessModifier GetterAccessibility => propertyInfo.GetGetMethod(nonPublic: true).GetCSharpAccessModifier(); public CSharpAccessModifier SetterAccessibility => propertyInfo.GetSetMethod(nonPublic: true).GetCSharpAccessModifier(); + + public bool IsBrowsable + { + get + { + if (isBrowsable == null) + { + isBrowsable = propertyInfo.GetCustomAttribute() is not { State: EditorBrowsableState.Never }; + } + + return isBrowsable.Value; + } + } } } diff --git a/Src/FluentAssertions/Equivalency/Selection/ExcludeNonBrowsableMembersRule.cs b/Src/FluentAssertions/Equivalency/Selection/ExcludeNonBrowsableMembersRule.cs new file mode 100644 index 0000000000..c5ee5f3f83 --- /dev/null +++ b/Src/FluentAssertions/Equivalency/Selection/ExcludeNonBrowsableMembersRule.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace FluentAssertions.Equivalency.Selection +{ + internal class ExcludeNonBrowsableMembersRule : IMemberSelectionRule + { + public bool IncludesMembers => false; + + public IEnumerable SelectMembers(INode currentNode, IEnumerable selectedMembers, MemberSelectionContext context) + { + return selectedMembers.Where(member => member.IsBrowsable).ToList(); + } + } +} diff --git a/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs b/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs index 8fa4a6cfa7..ca8d9dbe0a 100644 --- a/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs +++ b/Src/FluentAssertions/Equivalency/SelfReferenceEquivalencyAssertionOptions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; @@ -56,6 +57,8 @@ public abstract class SelfReferenceEquivalencyAssertionOptions : IEquival private MemberVisibility includedProperties; private MemberVisibility includedFields; + private bool ignoreNonBrowsableOnSubject; + private bool excludeNonBrowsableOnExpectation; private bool compareRecordsByValue; @@ -80,6 +83,8 @@ protected SelfReferenceEquivalencyAssertionOptions(IEquivalencyAssertionOptions useRuntimeTyping = defaults.UseRuntimeTyping; includedProperties = defaults.IncludedProperties; includedFields = defaults.IncludedFields; + ignoreNonBrowsableOnSubject = defaults.IgnoreNonBrowsableOnSubject; + excludeNonBrowsableOnExpectation = defaults.ExcludeNonBrowsableOnExpectation; compareRecordsByValue = defaults.CompareRecordsByValue; ConversionSelector = defaults.ConversionSelector.Clone(); @@ -115,6 +120,11 @@ IEnumerable IEquivalencyAssertionOptions.SelectionRules yield return new AllFieldsSelectionRule(); } + if (excludeNonBrowsableOnExpectation) + { + yield return new ExcludeNonBrowsableMembersRule(); + } + foreach (IMemberSelectionRule rule in selectionRules) { yield return rule; @@ -162,6 +172,10 @@ IEnumerable IEquivalencyAssertionOptions.SelectionRules MemberVisibility IEquivalencyAssertionOptions.IncludedFields => includedFields; + bool IEquivalencyAssertionOptions.IgnoreNonBrowsableOnSubject => ignoreNonBrowsableOnSubject; + + bool IEquivalencyAssertionOptions.ExcludeNonBrowsableOnExpectation => excludeNonBrowsableOnExpectation; + public bool CompareRecordsByValue => compareRecordsByValue; EqualityStrategy IEquivalencyAssertionOptions.GetEqualityStrategy(Type requestedType) @@ -312,6 +326,29 @@ public TSelf ExcludingProperties() return (TSelf)this; } + /// + /// Instructs the comparison to exclude non-browsable members in the expectation (members set to + /// ). It is not required that they be marked non-browsable in the subject. Use + /// to ignore non-browsable members in the subject. + /// + /// + public TSelf ExcludingNonBrowsableMembers() + { + excludeNonBrowsableOnExpectation = true; + return (TSelf)this; + } + + /// + /// Instructs the comparison to treat non-browsable members in the subject as though they do not exist. If you need to + /// ignore non-browsable members in the expectation, use . + /// + /// + public TSelf IgnoringNonBrowsableMembersOnSubject() + { + ignoreNonBrowsableOnSubject = true; + return (TSelf)this; + } + /// /// Instructs the comparison to respect the expectation's runtime type. /// @@ -698,6 +735,11 @@ public override string ToString() .Append(useRuntimeTyping ? "runtime" : "declared") .AppendLine(" types and members"); + if (ignoreNonBrowsableOnSubject) + { + builder.AppendLine("- Do not consider members marked non-browsable on the subject"); + } + if (isRecursive) { if (allowInfiniteRecursion) @@ -737,6 +779,15 @@ public override string ToString() builder.AppendLine($"- Compare {type} by its members"); } + if (excludeNonBrowsableOnExpectation) + { + builder.AppendLine("- Exclude non-browsable members"); + } + else + { + builder.AppendLine("- Include non-browsable members"); + } + foreach (IMemberSelectionRule rule in selectionRules) { builder.Append("- ").AppendLine(rule.ToString()); diff --git a/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs b/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs index 845f8a2633..382b686d73 100644 --- a/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs +++ b/Src/FluentAssertions/Equivalency/Steps/StructuralEqualityEquivalencyStep.cs @@ -82,6 +82,11 @@ public class StructuralEqualityEquivalencyStep : IEquivalencyStep where match is not null select match; + if (config.IgnoreNonBrowsableOnSubject) + { + query = query.Where(member => member.IsBrowsable); + } + return query.FirstOrDefault(); } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt index 3ac19edafa..269dc70b7c 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt @@ -829,6 +829,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; set; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -849,6 +850,8 @@ namespace FluentAssertions.Equivalency FluentAssertions.Equivalency.ConversionSelector ConversionSelector { get; } FluentAssertions.Equivalency.CyclicReferenceHandling CyclicReferenceHandling { get; } FluentAssertions.Equivalency.EnumEquivalencyHandling EnumEquivalencyHandling { get; } + bool ExcludeNonBrowsableOnExpectation { get; } + bool IgnoreNonBrowsableOnSubject { get; } FluentAssertions.Equivalency.MemberVisibility IncludedFields { get; } FluentAssertions.Equivalency.MemberVisibility IncludedProperties { get; } bool IsRecursive { get; } @@ -884,6 +887,7 @@ namespace FluentAssertions.Equivalency { System.Type DeclaringType { get; } FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + bool IsBrowsable { get; } System.Type ReflectedType { get; } FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } object GetValue(object obj); @@ -987,6 +991,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -1015,8 +1020,10 @@ namespace FluentAssertions.Equivalency public TSelf ExcludingFields() { } public TSelf ExcludingMissingMembers() { } public TSelf ExcludingNestedObjects() { } + public TSelf ExcludingNonBrowsableMembers() { } public TSelf ExcludingProperties() { } public TSelf IgnoringCyclicReferences() { } + public TSelf IgnoringNonBrowsableMembersOnSubject() { } public TSelf Including(System.Linq.Expressions.Expression> predicate) { } public TSelf IncludingAllDeclaredProperties() { } public TSelf IncludingAllRuntimeProperties() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt index 36cdeff676..e0af6e27e0 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt @@ -841,6 +841,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; set; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -861,6 +862,8 @@ namespace FluentAssertions.Equivalency FluentAssertions.Equivalency.ConversionSelector ConversionSelector { get; } FluentAssertions.Equivalency.CyclicReferenceHandling CyclicReferenceHandling { get; } FluentAssertions.Equivalency.EnumEquivalencyHandling EnumEquivalencyHandling { get; } + bool ExcludeNonBrowsableOnExpectation { get; } + bool IgnoreNonBrowsableOnSubject { get; } FluentAssertions.Equivalency.MemberVisibility IncludedFields { get; } FluentAssertions.Equivalency.MemberVisibility IncludedProperties { get; } bool IsRecursive { get; } @@ -896,6 +899,7 @@ namespace FluentAssertions.Equivalency { System.Type DeclaringType { get; } FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + bool IsBrowsable { get; } System.Type ReflectedType { get; } FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } object GetValue(object obj); @@ -999,6 +1003,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -1027,8 +1032,10 @@ namespace FluentAssertions.Equivalency public TSelf ExcludingFields() { } public TSelf ExcludingMissingMembers() { } public TSelf ExcludingNestedObjects() { } + public TSelf ExcludingNonBrowsableMembers() { } public TSelf ExcludingProperties() { } public TSelf IgnoringCyclicReferences() { } + public TSelf IgnoringNonBrowsableMembersOnSubject() { } public TSelf Including(System.Linq.Expressions.Expression> predicate) { } public TSelf IncludingAllDeclaredProperties() { } public TSelf IncludingAllRuntimeProperties() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt index 7de57cf1c1..bf5918f8da 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt @@ -829,6 +829,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; set; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -849,6 +850,8 @@ namespace FluentAssertions.Equivalency FluentAssertions.Equivalency.ConversionSelector ConversionSelector { get; } FluentAssertions.Equivalency.CyclicReferenceHandling CyclicReferenceHandling { get; } FluentAssertions.Equivalency.EnumEquivalencyHandling EnumEquivalencyHandling { get; } + bool ExcludeNonBrowsableOnExpectation { get; } + bool IgnoreNonBrowsableOnSubject { get; } FluentAssertions.Equivalency.MemberVisibility IncludedFields { get; } FluentAssertions.Equivalency.MemberVisibility IncludedProperties { get; } bool IsRecursive { get; } @@ -884,6 +887,7 @@ namespace FluentAssertions.Equivalency { System.Type DeclaringType { get; } FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + bool IsBrowsable { get; } System.Type ReflectedType { get; } FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } object GetValue(object obj); @@ -987,6 +991,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -1015,8 +1020,10 @@ namespace FluentAssertions.Equivalency public TSelf ExcludingFields() { } public TSelf ExcludingMissingMembers() { } public TSelf ExcludingNestedObjects() { } + public TSelf ExcludingNonBrowsableMembers() { } public TSelf ExcludingProperties() { } public TSelf IgnoringCyclicReferences() { } + public TSelf IgnoringNonBrowsableMembersOnSubject() { } public TSelf Including(System.Linq.Expressions.Expression> predicate) { } public TSelf IncludingAllDeclaredProperties() { } public TSelf IncludingAllRuntimeProperties() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt index 9cff0a8291..002d020a8e 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt @@ -829,6 +829,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; set; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -849,6 +850,8 @@ namespace FluentAssertions.Equivalency FluentAssertions.Equivalency.ConversionSelector ConversionSelector { get; } FluentAssertions.Equivalency.CyclicReferenceHandling CyclicReferenceHandling { get; } FluentAssertions.Equivalency.EnumEquivalencyHandling EnumEquivalencyHandling { get; } + bool ExcludeNonBrowsableOnExpectation { get; } + bool IgnoreNonBrowsableOnSubject { get; } FluentAssertions.Equivalency.MemberVisibility IncludedFields { get; } FluentAssertions.Equivalency.MemberVisibility IncludedProperties { get; } bool IsRecursive { get; } @@ -884,6 +887,7 @@ namespace FluentAssertions.Equivalency { System.Type DeclaringType { get; } FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + bool IsBrowsable { get; } System.Type ReflectedType { get; } FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } object GetValue(object obj); @@ -987,6 +991,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -1015,8 +1020,10 @@ namespace FluentAssertions.Equivalency public TSelf ExcludingFields() { } public TSelf ExcludingMissingMembers() { } public TSelf ExcludingNestedObjects() { } + public TSelf ExcludingNonBrowsableMembers() { } public TSelf ExcludingProperties() { } public TSelf IgnoringCyclicReferences() { } + public TSelf IgnoringNonBrowsableMembersOnSubject() { } public TSelf Including(System.Linq.Expressions.Expression> predicate) { } public TSelf IncludingAllDeclaredProperties() { } public TSelf IncludingAllRuntimeProperties() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt index 3391e7ae6c..e17cfba5d5 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt @@ -822,6 +822,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; set; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -842,6 +843,8 @@ namespace FluentAssertions.Equivalency FluentAssertions.Equivalency.ConversionSelector ConversionSelector { get; } FluentAssertions.Equivalency.CyclicReferenceHandling CyclicReferenceHandling { get; } FluentAssertions.Equivalency.EnumEquivalencyHandling EnumEquivalencyHandling { get; } + bool ExcludeNonBrowsableOnExpectation { get; } + bool IgnoreNonBrowsableOnSubject { get; } FluentAssertions.Equivalency.MemberVisibility IncludedFields { get; } FluentAssertions.Equivalency.MemberVisibility IncludedProperties { get; } bool IsRecursive { get; } @@ -877,6 +880,7 @@ namespace FluentAssertions.Equivalency { System.Type DeclaringType { get; } FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + bool IsBrowsable { get; } System.Type ReflectedType { get; } FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } object GetValue(object obj); @@ -980,6 +984,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -1008,8 +1013,10 @@ namespace FluentAssertions.Equivalency public TSelf ExcludingFields() { } public TSelf ExcludingMissingMembers() { } public TSelf ExcludingNestedObjects() { } + public TSelf ExcludingNonBrowsableMembers() { } public TSelf ExcludingProperties() { } public TSelf IgnoringCyclicReferences() { } + public TSelf IgnoringNonBrowsableMembersOnSubject() { } public TSelf Including(System.Linq.Expressions.Expression> predicate) { } public TSelf IncludingAllDeclaredProperties() { } public TSelf IncludingAllRuntimeProperties() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt index e118ff6c79..3538b07fae 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt @@ -829,6 +829,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; set; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -849,6 +850,8 @@ namespace FluentAssertions.Equivalency FluentAssertions.Equivalency.ConversionSelector ConversionSelector { get; } FluentAssertions.Equivalency.CyclicReferenceHandling CyclicReferenceHandling { get; } FluentAssertions.Equivalency.EnumEquivalencyHandling EnumEquivalencyHandling { get; } + bool ExcludeNonBrowsableOnExpectation { get; } + bool IgnoreNonBrowsableOnSubject { get; } FluentAssertions.Equivalency.MemberVisibility IncludedFields { get; } FluentAssertions.Equivalency.MemberVisibility IncludedProperties { get; } bool IsRecursive { get; } @@ -884,6 +887,7 @@ namespace FluentAssertions.Equivalency { System.Type DeclaringType { get; } FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + bool IsBrowsable { get; } System.Type ReflectedType { get; } FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } object GetValue(object obj); @@ -987,6 +991,7 @@ namespace FluentAssertions.Equivalency public System.Type DeclaringType { get; } public override string Description { get; } public FluentAssertions.Common.CSharpAccessModifier GetterAccessibility { get; } + public bool IsBrowsable { get; } public System.Type ReflectedType { get; } public FluentAssertions.Common.CSharpAccessModifier SetterAccessibility { get; } public object GetValue(object obj) { } @@ -1015,8 +1020,10 @@ namespace FluentAssertions.Equivalency public TSelf ExcludingFields() { } public TSelf ExcludingMissingMembers() { } public TSelf ExcludingNestedObjects() { } + public TSelf ExcludingNonBrowsableMembers() { } public TSelf ExcludingProperties() { } public TSelf IgnoringCyclicReferences() { } + public TSelf IgnoringNonBrowsableMembersOnSubject() { } public TSelf Including(System.Linq.Expressions.Expression> predicate) { } public TSelf IncludingAllDeclaredProperties() { } public TSelf IncludingAllRuntimeProperties() { } diff --git a/Tests/Benchmarks/CheckIfMemberIsBrowsable.cs b/Tests/Benchmarks/CheckIfMemberIsBrowsable.cs new file mode 100644 index 0000000000..fc7948ee47 --- /dev/null +++ b/Tests/Benchmarks/CheckIfMemberIsBrowsable.cs @@ -0,0 +1,28 @@ +using System.ComponentModel; +using System.Reflection; + +using BenchmarkDotNet.Attributes; + +namespace Benchmarks +{ + [MemoryDiagnoser] + public class CheckIfMemberIsBrowsableBenchmarks + { + [Params(true, false)] + public bool IsBrowsable { get; set; } + + public int BrowsableField; + [EditorBrowsable(EditorBrowsableState.Never)] + public int NonBrowsableField; + + public FieldInfo SubjectField => typeof(CheckIfMemberIsBrowsableBenchmarks) + .GetField(IsBrowsable ? nameof(BrowsableField) : nameof(NonBrowsableField)); + + [Benchmark] + public void CheckIfMemberIsBrowsable() + { + bool _ = + SubjectField.GetCustomAttribute() is not { State: EditorBrowsableState.Never }; + } + } +} diff --git a/Tests/Benchmarks/Program.cs b/Tests/Benchmarks/Program.cs index 4f917d4cad..7409b520f4 100644 --- a/Tests/Benchmarks/Program.cs +++ b/Tests/Benchmarks/Program.cs @@ -22,7 +22,7 @@ public static void Main() var config = ManualConfig.CreateMinimumViable().AddExporter(exporter); - _ = BenchmarkRunner.Run(config); + _ = BenchmarkRunner.Run(config); } } } diff --git a/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs b/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs index b5d632b059..2d8c82b4c1 100644 --- a/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs +++ b/Tests/Benchmarks/UsersOfGetClosedGenericInterfaces.cs @@ -68,6 +68,10 @@ private class Config : IEquivalencyAssertionOptions public MemberVisibility IncludedFields => throw new NotImplementedException(); + public bool IgnoreNonBrowsableOnSubject => throw new NotImplementedException(); + + public bool ExcludeNonBrowsableOnExpectation => throw new NotImplementedException(); + public bool CompareRecordsByValue => throw new NotImplementedException(); public ITraceWriter TraceWriter => throw new NotImplementedException(); diff --git a/Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.cs index 84f742b874..7b87bd9631 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; @@ -1489,5 +1490,452 @@ public void Including_an_interface_property_through_inheritance_should_work() .Including(a => a.Value2) .RespectingRuntimeTypes()); } + + [Fact] + public void When_browsable_field_differs_excluding_non_browsable_members_should_not_affect_result() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { BrowsableField = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { BrowsableField = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void When_browsable_property_differs_excluding_non_browsable_members_should_not_affect_result() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { BrowsableProperty = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { BrowsableProperty = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void When_advanced_browsable_field_differs_excluding_non_browsable_members_should_not_affect_result() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { AdvancedBrowsableField = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { AdvancedBrowsableField = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void When_advanced_browsable_property_differs_excluding_non_browsable_members_should_not_affect_result() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { AdvancedBrowsableProperty = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { AdvancedBrowsableProperty = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void When_explicitly_browsable_field_differs_excluding_non_browsable_members_should_not_affect_result() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { ExplicitlyBrowsableField = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { ExplicitlyBrowsableField = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void When_explicitly_browsable_property_differs_excluding_non_browsable_members_should_not_affect_result() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { ExplicitlyBrowsableProperty = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { ExplicitlyBrowsableProperty = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void When_non_browsable_field_differs_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { NonBrowsableField = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { NonBrowsableField = 1 }; + + // Act & Assert + subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_non_browsable_property_differs_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = new ClassWithNonBrowsableMembers() { NonBrowsableProperty = 0 }; + var expectation = new ClassWithNonBrowsableMembers() { NonBrowsableProperty = 1 }; + + // Act & Assert + subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_property_is_non_browsable_only_in_subject_excluding_non_browsable_members_should_not_make_it_succeed() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { PropertyThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { PropertyThatMightBeNonBrowsable = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw().WithMessage("Expected property subject.PropertyThatMightBeNonBrowsable to be 1, but found 0.*"); + } + + [Fact] + public void When_property_is_non_browsable_only_in_subject_ignoring_non_browsable_members_on_subject_should_make_it_succeed() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { PropertyThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { PropertyThatMightBeNonBrowsable = 1 }; + + // Act & Assert + subject.Should().BeEquivalentTo( + expectation, + config => config.IgnoringNonBrowsableMembersOnSubject().ExcludingMissingMembers()); + } + + [Fact] + public void When_non_browsable_property_on_subject_is_ignored_but_is_present_on_expectation_it_should_fail() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { PropertyThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { PropertyThatMightBeNonBrowsable = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.IgnoringNonBrowsableMembersOnSubject()); + + // Assert + action.Should().Throw().WithMessage( + $"Expectation has * subject.*ThatMightBeNonBrowsable that is non-browsable in the other object, and non-browsable " + + $"members on the subject are ignored with the current configuration*"); + } + + [Fact] + public void When_property_is_non_browsable_only_in_expectation_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { PropertyThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { PropertyThatMightBeNonBrowsable = 1 }; + + // Act & Assert + subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_field_is_non_browsable_only_in_subject_excluding_non_browsable_members_should_not_make_it_succeed() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { FieldThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { FieldThatMightBeNonBrowsable = 1 }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + + // Assert + action.Should().Throw().WithMessage("Expected field subject.FieldThatMightBeNonBrowsable to be 1, but found 0.*"); + } + + [Fact] + public void When_field_is_non_browsable_only_in_subject_ignoring_non_browsable_members_on_subject_should_make_it_succeed() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { FieldThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { FieldThatMightBeNonBrowsable = 1 }; + + // Act & Assert + subject.Should().BeEquivalentTo( + expectation, + config => config.IgnoringNonBrowsableMembersOnSubject().ExcludingMissingMembers()); + } + + [Fact] + public void When_field_is_non_browsable_only_in_expectation_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = new ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable() { FieldThatMightBeNonBrowsable = 0 }; + var expectation = new ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable() { FieldThatMightBeNonBrowsable = 1 }; + + // Act & Assert + subject.Should().BeEquivalentTo(expectation, config => config.ExcludingNonBrowsableMembers()); + } + + public class NonBrowsableOnOneButMissingFromTheOther + { + [Fact] + public void When_property_is_missing_from_subject_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = + new + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + NonBrowsableField = 2, + /* NonBrowsableProperty missing */ + }; + + var expected = + new ClassWithNonBrowsableMembers + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + NonBrowsableField = 2, + NonBrowsableProperty = 2, + }; + + // Act & Assert + subject.Should().BeEquivalentTo(expected, opt => opt.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_field_is_missing_from_subject_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = + new + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + /* NonBrowsableField missing */ + NonBrowsableProperty = 2, + }; + + var expected = + new ClassWithNonBrowsableMembers + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + NonBrowsableField = 2, + NonBrowsableProperty = 2, + }; + + // Act & Assert + subject.Should().BeEquivalentTo(expected, opt => opt.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_property_is_missing_from_expectation_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = + new ClassWithNonBrowsableMembers + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + NonBrowsableField = 2, + NonBrowsableProperty = 2, + }; + + var expected = + new + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + NonBrowsableField = 2, + /* NonBrowsableProperty missing */ + }; + + // Act & Assert + subject.Should().BeEquivalentTo(expected, opt => opt.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_field_is_missing_from_expectation_excluding_non_browsable_members_should_make_it_succeed() + { + // Arrange + var subject = + new ClassWithNonBrowsableMembers + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + NonBrowsableField = 2, + NonBrowsableProperty = 2, + }; + + var expected = + new + { + BrowsableField = 1, + BrowsableProperty = 1, + ExplicitlyBrowsableField = 1, + ExplicitlyBrowsableProperty = 1, + AdvancedBrowsableField = 1, + AdvancedBrowsableProperty = 1, + /* NonBrowsableField missing */ + NonBrowsableProperty = 2, + }; + + // Act & Assert + subject.Should().BeEquivalentTo(expected, opt => opt.ExcludingNonBrowsableMembers()); + } + + [Fact] + public void When_non_browsable_members_are_excluded_it_should_still_be_possible_to_explicitly_include_non_browsable_field() + { + // Arrange + var subject = + new ClassWithNonBrowsableMembers() + { + NonBrowsableField = 1, + }; + + var expectation = + new ClassWithNonBrowsableMembers() + { + NonBrowsableField = 2, + }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo( + expectation, + opt => opt.IncludingFields().ExcludingNonBrowsableMembers().Including(e => e.NonBrowsableField)); + + // Assert + action.Should().Throw().WithMessage("Expected field subject.NonBrowsableField to be 2, but found 1.*"); + } + + [Fact] + public void When_non_browsable_members_are_excluded_it_should_still_be_possible_to_explicitly_include_non_browsable_property() + { + // Arrange + var subject = + new ClassWithNonBrowsableMembers() + { + NonBrowsableProperty = 1, + }; + + var expectation = + new ClassWithNonBrowsableMembers() + { + NonBrowsableProperty = 2, + }; + + // Act + Action action = + () => subject.Should().BeEquivalentTo( + expectation, + opt => opt.IncludingProperties().ExcludingNonBrowsableMembers().Including(e => e.NonBrowsableProperty)); + + // Assert + action.Should().Throw().WithMessage("Expected property subject.NonBrowsableProperty to be 2, but found 1.*"); + } + } + + private class ClassWithNonBrowsableMembers + { + public int BrowsableField = -1; + + public int BrowsableProperty { get; set; } + + [EditorBrowsable(EditorBrowsableState.Always)] + public int ExplicitlyBrowsableField = -1; + + [EditorBrowsable(EditorBrowsableState.Always)] + public int ExplicitlyBrowsableProperty { get; set; } + + [EditorBrowsable(EditorBrowsableState.Advanced)] + public int AdvancedBrowsableField = -1; + + [EditorBrowsable(EditorBrowsableState.Advanced)] + public int AdvancedBrowsableProperty { get; set; } + + [EditorBrowsable(EditorBrowsableState.Never)] + public int NonBrowsableField = -1; + + [EditorBrowsable(EditorBrowsableState.Never)] + public int NonBrowsableProperty { get; set; } + } + + private class ClassWhereMemberThatCouldBeNonBrowsableIsBrowsable + { + public int BrowsableField = -1; + + public int BrowsableProperty { get; set; } + + public int FieldThatMightBeNonBrowsable = -1; + + public int PropertyThatMightBeNonBrowsable { get; set; } + } + + private class ClassWhereMemberThatCouldBeNonBrowsableIsNonBrowsable + { + public int BrowsableField = -1; + + public int BrowsableProperty { get; set; } + + [EditorBrowsable(EditorBrowsableState.Never)] + public int FieldThatMightBeNonBrowsable = -1; + + [EditorBrowsable(EditorBrowsableState.Never)] + public int PropertyThatMightBeNonBrowsable { get; set; } + } } } diff --git a/docs/_pages/objectgraphs.md b/docs/_pages/objectgraphs.md index 505e186e59..a21abb76ed 100644 --- a/docs/_pages/objectgraphs.md +++ b/docs/_pages/objectgraphs.md @@ -216,6 +216,27 @@ orderDto.Should().BeEquivalentTo(order, options => options Notice that you can also map properties to fields and vice-versa. +### Hidden Members + +Sometimes types have members out of necessity, to satisfy a contract, but they aren't logically a part of the type. In this case, they are often marked with the attribute `[EditorBrowsable(EditorBrowsableState.Never)]`, so that the object can satisfy the contract but the members don't show up in IntelliSense when writing code that uses the type. + +If you want to compare objects that have such fields, but you want to exclude the non-browsable "hidden" members (for instance, their implementations often simply throw `NotImplementedException`), you can call `ExcludingNonBrowsableMembers` on the options object: + +```csharp +class DataType +{ + public int X { get; } + + [EditorBrowsable(EditorBrowsableState.Never)] + public int Y => throw new NotImplementedException(); +} + +DataType original, derived; + +derived.Should().BeEquivalentTo(original, options => options + .ExcludingNonBrowsableMembers()); +``` + ### Equivalency Comparison Behavior In addition to influencing the members that are including in the comparison, you can also override the actual assertion operation that is executed on a particular member. diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index 9c28ca607b..7a998d4515 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -21,6 +21,7 @@ sidebar: * Added `NotBe` for nullable boolean values - [#1865](https://github.com/fluentassertions/fluentassertions/pull/1865) * Added a new overload to `MatchRegex()` to assert on the number of regex matches - [#1869](https://github.com/fluentassertions/fluentassertions/pull/1869) * Added difference to numeric assertion failure messages - [#1859](https://github.com/fluentassertions/fluentassertions/pull/1859) +* Added the ability to exclude fields & properties marked as non-browsable in the code editor from structural equality comparisons - [#1807](https://github.com/fluentassertions/fluentassertions/pull/1807) & [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) ### Fixes * `EnumAssertions.Be` did not determine the caller name - [#1835](https://github.com/fluentassertions/fluentassertions/pull/1835) @@ -34,7 +35,7 @@ sidebar: ## 6.5.1 ### Fixes -* Fix regression introduced in 6.5.0 where `collection.Should().BeInAscendingOrder(x => x)` would fail - [#1802](https://github.com/fluentassertions/fluentassertions/pull/1802) +* Fixed regression introduced in 6.5.0 where `collection.Should().BeInAscendingOrder(x => x)` would fail - [#1802](https://github.com/fluentassertions/fluentassertions/pull/1802) ## 6.5.0 From e9d81a82809e1cb91c7a7ba309568a3aafcc99f5 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Sat, 16 Apr 2022 13:28:09 +0200 Subject: [PATCH 16/48] Fix release notes --- docs/_pages/releases.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index 7a998d4515..ff728d4bb2 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -11,6 +11,8 @@ sidebar: ### What's new * Add `BeDefined` and `NotBeDefined` to assert on existence of an enum value - [#1888](https://github.com/fluentassertions/fluentassertions/pull/1888) +* Added the ability to exclude fields & properties marked as non-browsable in the code editor from structural equality comparisons - [#1807](https://github.com/fluentassertions/fluentassertions/pull/1807) & [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) +* Assertions on the collection types in System.Data (`DataSet.Tables`, `DataTable.Columns`, `DataTable.Rows`) have been restored - [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) ## 6.6.0 @@ -21,14 +23,12 @@ sidebar: * Added `NotBe` for nullable boolean values - [#1865](https://github.com/fluentassertions/fluentassertions/pull/1865) * Added a new overload to `MatchRegex()` to assert on the number of regex matches - [#1869](https://github.com/fluentassertions/fluentassertions/pull/1869) * Added difference to numeric assertion failure messages - [#1859](https://github.com/fluentassertions/fluentassertions/pull/1859) -* Added the ability to exclude fields & properties marked as non-browsable in the code editor from structural equality comparisons - [#1807](https://github.com/fluentassertions/fluentassertions/pull/1807) & [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) ### Fixes * `EnumAssertions.Be` did not determine the caller name - [#1835](https://github.com/fluentassertions/fluentassertions/pull/1835) * Ensure `ExcludingMissingMembers` doesn't undo usage of `WithMapping` in `BeEquivalentTo` - [#1838](https://github.com/fluentassertions/fluentassertions/pull/1838) * Better handling of NaN in various numeric assertions - [#1822](https://github.com/fluentassertions/fluentassertions/pull/1822) & [#1867](https://github.com/fluentassertions/fluentassertions/pull/1867) * `WithMapping` in `BeEquivalentTo` now also works when the root is a collection - [#1858](https://github.com/fluentassertions/fluentassertions/pull/1858) -* Assertions on the collection types in System.Data (`DataSet.Tables`, `DataTable.Columns`, `DataTable.Rows`) have been restored - [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) ### Fixes (Extensibility) From b4bb85add7db5a1b1c3887ea240c6f7b5d718ded Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Mon, 18 Apr 2022 11:38:25 +0200 Subject: [PATCH 17/48] Seperate all DateTime assertions into nested classes --- .../Primitives/DateTimeAssertionSpecs.cs | 4473 +++++++++-------- 1 file changed, 2261 insertions(+), 2212 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs index 39595f1ead..3a5583ccde 100644 --- a/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs @@ -7,2238 +7,2287 @@ namespace FluentAssertions.Specs.Primitives { public class DateTimeAssertionSpecs { - #region (Not) Have Value - - [Fact] - public void Should_succeed_when_asserting_nullable_datetime_value_with_a_value_to_have_a_value() - { - // Arrange - DateTime? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => nullableDateTime.Should().HaveValue(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetime_value_without_a_value_to_have_a_value() - { - // Arrange - DateTime? nullableDateTime = null; - - // Act - Action action = () => nullableDateTime.Should().HaveValue(); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_datetime_value_without_a_value_to_not_have_a_value() - { - // Arrange - DateTime? nullableDateTime = null; - - // Act - Action action = () => - nullableDateTime.Should().NotHaveValue(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetime_value_with_a_value_to_not_have_a_value() - { - // Arrange - DateTime? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTime.Should().NotHaveValue(); - - // Assert - action.Should().Throw(); - } - - #endregion - - #region (Not) Be Null - - [Fact] - public void Should_succeed_when_asserting_nullable_datetime_value_with_a_value_to_not_be_null() - { - // Arrange - DateTime? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => nullableDateTime.Should().NotBeNull(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetime_value_without_a_value_to_not_be_null() - { - // Arrange - DateTime? nullableDateTime = null; - - // Act - Action action = () => nullableDateTime.Should().NotBeNull(); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_datetime_value_without_a_value_to_be_null() - { - // Arrange - DateTime? nullableDateTime = null; - - // Act - Action action = () => - nullableDateTime.Should().BeNull(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetime_value_with_a_value_to_be_null() - { - // Arrange - DateTime? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTime.Should().BeNull(); - - // Assert - action.Should().Throw(); - } - - #endregion - - #region (Not) Be - - [Fact] - public void Should_succeed_when_asserting_datetime_value_is_equal_to_the_same_value() - { - // Arrange - DateTime dateTime = new DateTime(2016, 06, 04); - DateTime sameDateTime = new DateTime(2016, 06, 04); - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_datetime_value_is_equal_to_the_same_nullable_value_be_should_succeed() - { - // Arrange - DateTime dateTime = 4.June(2016); - DateTime? sameDateTime = 4.June(2016); - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_both_values_are_at_their_minimum_then_it_should_succeed() - { - // Arrange - DateTime dateTime = DateTime.MinValue; - DateTime sameDateTime = DateTime.MinValue; - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_both_values_are_at_their_maximum_then_it_should_succeed() - { - // Arrange - DateTime dateTime = DateTime.MaxValue; - DateTime sameDateTime = DateTime.MaxValue; - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_datetime_value_is_equal_to_the_different_value() - { - // Arrange - var dateTime = new DateTime(2012, 03, 10); - var otherDateTime = new DateTime(2012, 03, 11); - - // Act - Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected dateTime to be <2012-03-11>*failure message, but found <2012-03-10>."); - } - - [Fact] - public void When_datetime_value_is_equal_to_the_different_nullable_value_be_should_failed() - { - // Arrange - DateTime dateTime = 10.March(2012); - DateTime? otherDateTime = 11.March(2012); - - // Act - Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected dateTime to be <2012-03-11>*failure message, but found <2012-03-10>."); - } - - [Fact] - public void Should_succeed_when_asserting_datetime_value_is_not_equal_to_a_different_value() - { - // Arrange - DateTime dateTime = new DateTime(2016, 06, 04); - DateTime otherDateTime = new DateTime(2016, 06, 05); - - // Act - Action act = () => dateTime.Should().NotBe(otherDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_datetime_value_is_not_equal_to_a_different_nullable_value_notbe_should_succeed() - { - // Arrange - DateTime dateTime = 4.June(2016); - DateTime? otherDateTime = 5.June(2016); - - // Act - Action act = () => dateTime.Should().NotBe(otherDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_datetime_value_is_not_equal_to_the_same_value() - { - // Arrange - var dateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Local); - var sameDateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Utc); - - // Act - Action act = - () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected dateTime not to be <2012-03-10 10:00:00> because we want to test the failure message, but it is."); - } - - [Fact] - public void When_datetime_value_is_not_equal_to_the_same_nullable_value_notbe_should_failed() - { - // Arrange - DateTime dateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Local); - DateTime? sameDateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Utc); - - // Act - Action act = - () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected dateTime not to be <2012-03-10 10:00:00> because we want to test the failure message, but it is."); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_numeric_value_equals_the_same_value() - { - // Arrange - DateTime? nullableDateTimeA = new DateTime(2016, 06, 04); - DateTime? nullableDateTimeB = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTimeA.Should().Be(nullableDateTimeB); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_a_nullable_date_time_is_equal_to_a_normal_date_time_but_the_kinds_differ_it_should_still_succeed() - { - // Arrange - DateTime? nullableDateTime = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Unspecified); - DateTime normalDateTime = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Utc); - - // Act - Action action = () => - nullableDateTime.Should().Be(normalDateTime); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_two_date_times_are_equal_but_the_kinds_differ_it_should_still_succeed() - { - // Arrange - DateTime dateTimeA = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Unspecified); - DateTime dateTimeB = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Utc); - - // Act - Action action = () => - dateTimeA.Should().Be(dateTimeB); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_numeric_null_value_equals_null() - { - // Arrange - DateTime? nullableDateTimeA = null; - DateTime? nullableDateTimeB = null; - - // Act - Action action = () => - nullableDateTimeA.Should().Be(nullableDateTimeB); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_numeric_value_equals_a_different_value() - { - // Arrange - DateTime? nullableDateTimeA = new DateTime(2016, 06, 04); - DateTime? nullableDateTimeB = new DateTime(2016, 06, 06); - - // Act - Action action = () => - nullableDateTimeA.Should().Be(nullableDateTimeB); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_datetime_null_value_is_equal_to_another_value() - { - // Arrange - DateTime? nullableDateTime = null; - - // Act - Action action = () => - nullableDateTime.Should().Be(new DateTime(2016, 06, 04), "because we want to test the failure {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected nullableDateTime to be <2016-06-04> because we want to test the failure message, but found ."); - } - - #endregion - - #region (Not) Be Close To - - [Fact] - public void When_asserting_that_time_is_close_to_a_negative_precision_it_should_throw() - { - // Arrange - var dateTime = DateTime.UtcNow; - var actual = new DateTime(dateTime.Ticks - 1); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, -1.Ticks()); - - // Assert - act.Should().Throw() - .WithMessage("* value of precision must be non-negative*"); - } - - [Fact] - public void When_a_datetime_is_close_to_a_later_datetime_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTime.UtcNow; - var actual = new DateTime(dateTime.Ticks - 1); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_datetime_is_close_to_an_earlier_datetime_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTime.UtcNow; - var actual = new DateTime(dateTime.Ticks + 1); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_datetime_is_close_to_a_MinValue_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTime.MinValue; - var actual = new DateTime(dateTime.Ticks + 1); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_datetime_is_close_to_a_MaxValue_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTime.MaxValue; - var actual = new DateTime(dateTime.Ticks - 1); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_that_time_is_not_close_to_a_negative_precision_it_should_throw() - { - // Arrange - var dateTime = DateTime.UtcNow; - var actual = new DateTime(dateTime.Ticks - 1); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, -1.Ticks()); - - // Assert - act.Should().Throw() - .WithMessage("* value of precision must be non-negative*"); - } - - [Fact] - public void When_a_datetime_is_close_to_a_later_datetime_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTime.UtcNow; - var actual = new DateTime(dateTime.Ticks - 1); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_datetime_is_close_to_an_earlier_datetime_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTime.UtcNow; - var actual = new DateTime(dateTime.Ticks + 1); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_datetime_is_close_to_a_MinValue_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTime.MinValue; - var actual = new DateTime(dateTime.Ticks + 1); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_datetime_is_close_to_a_MaxValue_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTime.MaxValue; - var actual = new DateTime(dateTime.Ticks - 1); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_a_later_datetime_it_should_succeed() - { - // Arrange - DateTime time = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 30, 980), DateTimeKind.Unspecified); - DateTime nearbyTime = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 31), DateTimeKind.Utc); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_a_later_datetime_it_should_throw() - { - // Arrange - DateTime time = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 30, 980), DateTimeKind.Unspecified); - DateTime nearbyTime = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 31), DateTimeKind.Utc); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:30.980>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_an_earlier_datetime_it_should_succeed() - { - // Arrange - DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 020); - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_an_earlier_datetime_it_should_throw() - { - // Arrange - DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 020); - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:31.020>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_an_earlier_datetime_by_a_20ms_timespan_it_should_throw() - { - // Arrange - DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 020); - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:31.020>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_another_value_that_is_later_by_more_than_20ms_it_should_throw() - { - // Arrange - DateTime time = 13.March(2012).At(12, 15, 30, 979); - DateTime nearbyTime = 13.March(2012).At(12, 15, 31); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected time to be within 20ms from <2012-03-13 12:15:31>, but found <2012-03-13 12:15:30.979>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_another_value_that_is_later_by_more_than_a_20ms_timespan_it_should_throw() - { - // Arrange - DateTime time = 13.March(2012).At(12, 15, 30, 979); - DateTime nearbyTime = 13.March(2012).At(12, 15, 31); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected time to be within 20ms from <2012-03-13 12:15:31>, but found <2012-03-13 12:15:30.979>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_another_value_that_is_later_by_more_than_20ms_it_should_succeed() - { - // Arrange - DateTime time = 13.March(2012).At(12, 15, 30, 979); - DateTime nearbyTime = 13.March(2012).At(12, 15, 31); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_throw() - { - // Arrange - DateTime time = 13.March(2012).At(12, 15, 31, 021); - DateTime nearbyTime = 13.March(2012).At(12, 15, 31); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected time to be within 20ms from <2012-03-13 12:15:31>, but found <2012-03-13 12:15:31.021>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_succeed() - { - // Arrange - DateTime time = 13.March(2012).At(12, 15, 31, 021); - DateTime nearbyTime = 13.March(2012).At(12, 15, 31); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_an_earlier_datetime_by_35ms_it_should_succeed() - { - // Arrange - DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 035); - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_an_earlier_datetime_by_35ms_it_should_throw() - { - // Arrange - DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 035); - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 35ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:31.035>."); - } - - [Fact] - public void When_asserting_subject_null_datetime_is_close_to_another_it_should_throw() - { - // Arrange - DateTime? time = null; - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Expected*, but found ."); - } - - [Fact] - public void When_asserting_subject_null_datetime_is_not_close_to_another_it_should_throw() - { - // Arrange - DateTime? time = null; - DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect*, but it was ."); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_the_minimum_datetime_it_should_succeed() - { - // Arrange - DateTime time = DateTime.MinValue + 50.Milliseconds(); - DateTime nearbyTime = DateTime.MinValue; - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_the_minimum_datetime_it_should_throw() - { - // Arrange - DateTime time = DateTime.MinValue + 50.Milliseconds(); - DateTime nearbyTime = DateTime.MinValue; - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 100ms from <0001-01-01 00:00:00.000>, but it was <00:00:00.050>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_close_to_the_maximum_datetime_it_should_succeed() - { - // Arrange - DateTime time = DateTime.MaxValue - 50.Milliseconds(); - DateTime nearbyTime = DateTime.MaxValue; - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_close_to_the_maximum_datetime_it_should_throw() - { - // Arrange - DateTime time = DateTime.MaxValue - 50.Milliseconds(); - DateTime nearbyTime = DateTime.MaxValue; - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 100ms from <9999-12-31 23:59:59.9999999>, but it was <9999-12-31 23:59:59.9499999>."); - } - - #endregion - - #region (Not) Be Before - [Fact] - public void When_asserting_a_point_of_time_is_before_a_later_point_it_should_succeed() - { - // Arrange - DateTime earlierDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04), DateTimeKind.Unspecified); - DateTime laterDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04, 0, 5, 0), DateTimeKind.Utc); - - // Act - Action act = () => earlierDate.Should().BeBefore(laterDate); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_point_of_time_is_not_before_another_it_should_throw() - { - // Arrange - DateTime earlierDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04), DateTimeKind.Unspecified); - DateTime laterDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04, 0, 5, 0), DateTimeKind.Utc); - - // Act - Action act = () => earlierDate.Should().NotBeBefore(laterDate); - - // Assert - act.Should().Throw() - .WithMessage("Expected earlierDate to be on or after <2016-06-04 00:05:00>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_is_before_earlier_expected_datetime_it_should_throw() - { - // Arrange - DateTime expected = new DateTime(2016, 06, 03); - DateTime subject = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().BeBefore(expected); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-03>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_is_not_before_earlier_expected_datetime_it_should_succeed() - { - // Arrange - DateTime expected = new DateTime(2016, 06, 03); - DateTime subject = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().NotBeBefore(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_before_the_same_datetime_it_should_throw() - { - // Arrange - DateTime expected = new DateTime(2016, 06, 04); - DateTime subject = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().BeBefore(expected); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-04>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_before_the_same_datetime_it_should_succeed() - { - // Arrange - DateTime expected = new DateTime(2016, 06, 04); - DateTime subject = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().NotBeBefore(expected); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Be On Or Before - [Fact] - public void When_asserting_subject_datetime_is_on_or_before_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 05); - - // Act - Action act = () => subject.Should().BeOnOrBefore(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_on_or_before_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 05); - - // Act - Action act = () => subject.Should().NotBeOnOrBefore(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be after <2016-06-05>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_on_or_before_the_same_date_as_the_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().BeOnOrBefore(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_on_or_before_the_same_date_as_the_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().NotBeOnOrBefore(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be after <2016-06-04>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 03); - - // Act - Action act = () => subject.Should().BeOnOrBefore(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be on or before <2016-06-03>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 03); - - // Act - Action act = () => subject.Should().NotBeOnOrBefore(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Be After - [Fact] - public void When_asserting_subject_datetime_is_after_earlier_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 03); - - // Act - Action act = () => subject.Should().BeAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_after_earlier_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 03); - - // Act - Action act = () => subject.Should().NotBeAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be on or before <2016-06-03>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_after_later_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 05); - - // Act - Action act = () => subject.Should().BeAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be after <2016-06-05>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_after_later_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 05); - - // Act - Action act = () => subject.Should().NotBeAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_after_the_same_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().BeAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be after <2016-06-04>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_after_the_same_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().NotBeAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Be On Or After - [Fact] - public void When_asserting_subject_datetime_is_on_or_after_earlier_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 03); - - // Act - Action act = () => subject.Should().BeOnOrAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_on_or_after_earlier_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 03); - - // Act - Action act = () => subject.Should().NotBeOnOrAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-03>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_on_or_after_the_same_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().BeOnOrAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_on_or_after_the_same_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 04); - - // Act - Action act = () => subject.Should().NotBeOnOrAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-04>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_on_or_after_later_expected_datetime_should_throw() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 05); - - // Act - Action act = () => subject.Should().BeOnOrAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be on or after <2016-06-05>, but found <2016-06-04>."); - } - - [Fact] - public void When_asserting_subject_datetime_is_not_on_or_after_later_expected_datetime_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2016, 06, 04); - DateTime expectation = new DateTime(2016, 06, 05); - - // Act - Action act = () => subject.Should().NotBeOnOrAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Have Year - [Fact] - public void When_asserting_subject_datetime_should_have_year_with_the_same_value_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 2009; - - // Act - Action act = () => subject.Should().HaveYear(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_year_with_the_same_value_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 2009; - - // Act - Action act = () => subject.Should().NotHaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the year part of subject to be 2009, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_year_with_a_different_value_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 2008; - - // Act - Action act = () => subject.Should().HaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the year part of subject to be 2008, but found 2009."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_year_with_a_different_value_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 2008; - - // Act - Action act = () => subject.Should().NotHaveYear(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_have_year_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 2008; - - // Act - Action act = () => subject.Should().HaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the year part of subject to be 2008, but found ."); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_not_have_year_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 2008; - - // Act - Action act = () => subject.Should().NotHaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the year part of subject to be 2008, but found a DateTime."); - } - #endregion - - #region (Not) Have Month - [Fact] - public void When_asserting_subject_datetime_should_have_month_with_the_same_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 12; - - // Act - Action act = () => subject.Should().HaveMonth(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_month_with_the_same_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 12; - - // Act - Action act = () => subject.Should().NotHaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the month part of subject to be 12, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_a_month_with_a_different_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 11; - - // Act - Action act = () => subject.Should().HaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the month part of subject to be 11, but found 12."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_a_month_with_a_different_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 11; - - // Act - Action act = () => subject.Should().NotHaveMonth(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_have_month_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 12; - - // Act - Action act = () => subject.Should().HaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the month part of subject to be 12, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_not_have_month_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 12; - - // Act - Action act = () => subject.Should().NotHaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the month part of subject to be 12, but found a DateTime."); - } - #endregion - - #region (Not) Have Day - [Fact] - public void When_asserting_subject_datetime_should_have_day_with_the_same_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 31; - - // Act - Action act = () => subject.Should().HaveDay(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_day_with_the_same_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 31; - - // Act - Action act = () => subject.Should().NotHaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the day part of subject to be 31, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_day_with_a_different_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 30; - - // Act - Action act = () => subject.Should().HaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the day part of subject to be 30, but found 31."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_day_with_a_different_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31); - int expectation = 30; - - // Act - Action act = () => subject.Should().NotHaveDay(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_have_day_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the day part of subject to be 22, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_not_have_day_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the day part of subject to be 22, but found a DateTime."); - } - #endregion - - #region (Not) Have Hour - [Fact] - public void When_asserting_subject_datetime_should_have_hour_with_the_same_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 23; - - // Act - Action act = () => subject.Should().HaveHour(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_hour_with_the_same_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 23; - - // Act - Action act = () => subject.Should().NotHaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the hour part of subject to be 23, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_hour_with_different_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the hour part of subject to be 22, but found 23."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_hour_with_different_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveHour(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_have_hour_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the hour part of subject to be 22, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_not_have_hour_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the hour part of subject to be 22, but found a DateTime."); - } - #endregion - - #region (Not) Have Minute - [Fact] - public void When_asserting_subject_datetime_should_have_minutes_with_the_same_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 59; - - // Act - Action act = () => subject.Should().HaveMinute(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_minutes_with_the_same_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 59; - - // Act - Action act = () => subject.Should().NotHaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the minute part of subject to be 59, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_minutes_with_different_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 58; - - // Act - Action act = () => subject.Should().HaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the minute part of subject to be 58, but found 59."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_minutes_with_different_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 58; - - // Act - Action act = () => subject.Should().NotHaveMinute(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_have_minute_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the minute part of subject to be 22, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_not_have_minute_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the minute part of subject to be 22, but found a DateTime."); - } - #endregion - - #region (Not) Have Second - [Fact] - public void When_asserting_subject_datetime_should_have_seconds_with_the_same_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 0; - - // Act - Action act = () => subject.Should().HaveSecond(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_seconds_with_the_same_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 0; - - // Act - Action act = () => subject.Should().NotHaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the seconds part of subject to be 0, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_seconds_with_different_value_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 1; - - // Act - Action act = () => subject.Should().HaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the seconds part of subject to be 1, but found 0."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_seconds_with_different_value_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); - int expectation = 1; - - // Act - Action act = () => subject.Should().NotHaveSecond(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_have_second_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the seconds part of subject to be 22, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_null_datetime_should_not_have_second_should_throw() - { - // Arrange - DateTime? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the seconds part of subject to be 22, but found a DateTime."); - } - #endregion - - #region BeIn Utc/Local - [Fact] - public void When_asserting_subject_datetime_represents_its_own_kind_it_should_succeed() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00, DateTimeKind.Local); - - // Act - Action act = () => subject.Should().BeIn(DateTimeKind.Local); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_represents_a_different_kind_it_should_throw() - { - // Arrange - DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00, DateTimeKind.Local); - - // Act - Action act = () => subject.Should().BeIn(DateTimeKind.Utc); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be in Utc, but found Local."); - } - - [Fact] - public void When_asserting_subject_null_datetime_represents_a_specific_kind_it_should_throw() - { - // Arrange - DateTime? subject = null; - - // Act - Action act = () => subject.Should().BeIn(DateTimeKind.Utc); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be in Utc, but found a DateTime."); - } - #endregion - - #region (Not) Be Same Date As - [Fact] - public void When_asserting_subject_datetime_should_be_same_date_as_another_with_the_same_date_it_should_succeed() - { - // Arrange - var subject = new DateTime(2009, 12, 31, 4, 5, 6); - - // Act - Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 31)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_be_same_date_as_another_with_the_same_date_it_should_throw() - { - // Arrange - var subject = new DateTime(2009, 12, 31, 4, 5, 6); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 31)); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); - } - - [Fact] - public void When_asserting_subject_datetime_should_be_same_as_another_with_same_date_but_different_time_it_should_succeed() - { - // Arrange - var subject = new DateTime(2009, 12, 31, 4, 5, 6); - - // Act - Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 31, 11, 15, 11)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_be_same_as_another_with_same_date_but_different_time_it_should_throw() - { - // Arrange - var subject = new DateTime(2009, 12, 31, 4, 5, 6); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 31, 11, 15, 11)); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); - } - - [Fact] - public void When_asserting_subject_null_datetime_to_be_same_date_as_another_datetime_it_should_throw() - { - // Arrange - DateTime? subject = null; - - // Act - Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 31)); - - // Assert - act.Should().Throw().WithMessage( - "Expected the date part of subject to be <2009-12-31>, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_null_datetime_to_not_be_same_date_as_another_datetime_it_should_throw() - { - // Arrange - DateTime? subject = null; - - // Act - Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 31)); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect the date part of subject to be <2009-12-31>, but found a DateTime."); - } - - [Fact] - public void When_asserting_subject_datetime_should_have_same_date_as_another_but_it_doesnt_it_should_throw() - { - // Arrange - var subject = new DateTime(2009, 12, 31); - - // Act - Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 30)); - - // Assert - act.Should().Throw().WithMessage( - "Expected the date part of subject to be <2009-12-30>, but found <2009-12-31>."); - } - - [Fact] - public void When_asserting_subject_datetime_should_not_have_same_date_as_another_but_it_doesnt_it_should_succeed() - { - // Arrange - var subject = new DateTime(2009, 12, 31); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 30)); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region Timespan Comparison - - [Fact] - public void When_date_is_not_more_than_the_required_one_day_before_another_it_should_throw() - { - // Arrange - var target = new DateTime(2009, 10, 2); - DateTime subject = target - 1.Days(); - - // Act - Action act = () => subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <2009-10-01> to be more than 1d before <2009-10-02> because we like that, but it is behind by 1d."); - } - - [Fact] - public void When_date_is_more_than_the_required_one_day_before_another_it_should_not_throw() - { - // Arrange - var target = new DateTime(2009, 10, 2); - DateTime subject = target - 25.Hours(); - - // Act / Assert - subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target); - } - - [Fact] - public void When_date_is_not_at_least_one_day_before_another_it_should_throw() - { - // Arrange - var target = new DateTime(2009, 10, 2); - DateTime subject = target - 23.Hours(); - - // Act - Action act = () => subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <2009-10-01 01:00:00> to be at least 1d before <2009-10-02> because we like that, but it is behind by 23h."); - } - - [Fact] - public void When_date_is_at_least_one_day_before_another_it_should_not_throw() - { - // Arrange - var target = new DateTime(2009, 10, 2); - DateTime subject = target - 24.Hours(); - - // Act / Assert - subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target); - } - - [Fact] - public void When_time_is_not_at_exactly_20_minutes_before_another_time_it_should_throw() - { - // Arrange - DateTime target = 1.January(0001).At(12, 55); - DateTime subject = 1.January(0001).At(12, 36); - - // Act - Action act = - () => subject.Should().BeExactly(TimeSpan.FromMinutes(20)).Before(target, "{0} minutes is enough", 20); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <12:36:00> to be exactly 20m before <12:55:00> because 20 minutes is enough, but it is behind by 19m."); - } - - [Fact] - public void When_time_is_exactly_90_seconds_before_another_time_it_should_not_throw() - { - // Arrange - DateTime target = 1.January(0001).At(12, 55); - DateTime subject = 1.January(0001).At(12, 53, 30); - - // Act / Assert - subject.Should().BeExactly(TimeSpan.FromSeconds(90)).Before(target); - } - - [Fact] - public void When_date_is_not_within_50_hours_before_another_date_it_should_throw() - { - // Arrange - var target = new DateTime(2010, 4, 10, 12, 0, 0); - DateTime subject = target - 50.Hours() - 1.Seconds(); - - // Act - Action act = - () => subject.Should().BeWithin(TimeSpan.FromHours(50)).Before(target, "{0} hours is enough", 50); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <2010-04-08 09:59:59> to be within 2d and 2h before <2010-04-10 12:00:00> because 50 hours is enough, but it is behind by 2d, 2h and 1s."); - } - - [Fact] - public void When_date_is_exactly_within_1d_before_another_date_it_should_not_throw() - { - // Arrange - var target = new DateTime(2010, 4, 10); - DateTime subject = target - 1.Days(); - - // Act / Assert - subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); - } - - [Fact] - public void When_date_is_within_1d_before_another_date_it_should_not_throw() - { - // Arrange - var target = new DateTime(2010, 4, 10); - DateTime subject = target - 23.Hours(); - - // Act / Assert - subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); - } - - [Fact] - public void When_a_utc_date_is_within_0s_before_itself_it_should_not_throw() - { - // Arrange - var date = DateTime.UtcNow; // local timezone differs from UTC - - // Act / Assert - date.Should().BeWithin(TimeSpan.Zero).Before(date); - } - - [Fact] - public void When_a_utc_date_is_within_0s_after_itself_it_should_not_throw() - { - // Arrange - var date = DateTime.UtcNow; // local timezone differs from UTC - - // Act / Assert - date.Should().BeWithin(TimeSpan.Zero).After(date); - } - - [Fact] - public void When_time_is_not_less_than_30s_after_another_time_it_should_throw() - { - // Arrange - var target = new DateTime(1, 1, 1, 12, 0, 30); - DateTime subject = target + 30.Seconds(); - - // Act - Action act = - () => subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target, "{0}s is the max", 30); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <12:01:00> to be less than 30s after <12:00:30> because 30s is the max, but it is ahead by 30s."); - } - - [Fact] - public void When_time_is_less_than_30s_after_another_time_it_should_not_throw() - { - // Arrange - var target = new DateTime(1, 1, 1, 12, 0, 30); - DateTime subject = target + 20.Seconds(); - - // Act / Assert - subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target); - } - - [Fact] - public void When_asserting_subject_be_more_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30); - var subject = 1.January(0001).At(0, 0, 15); - - // Act - Action action = () => subject.Should().BeMoreThan(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:15> to be more than 10s after <00:00:30>, but it is behind by 15s."); - } - - [Theory] - [InlineData(30, 20)] // edge case - [InlineData(30, 15)] - public void When_asserting_subject_be_at_least_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds); - var subject = 1.January(0001).At(0, 0, subjectSeconds); - - // Act - Action action = () => subject.Should().BeAtLeast(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be at least 10s after <00:00:30>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_exactly_10_seconds_after_target_but_subject_is_before_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30); - var subject = 1.January(0001).At(0, 0, 20); - - // Ac - Action action = () => subject.Should().BeExactly(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:20> to be exactly 10s after <00:00:30>, but it is behind by 10s."); - } - - [Theory] - [InlineData(30, 20)] // edge case - [InlineData(30, 25)] - public void When_asserting_subject_be_within_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds); - var subject = 1.January(0001).At(0, 0, subjectSeconds); - - // Act - Action action = () => subject.Should().BeWithin(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be within 10s after <00:00:30>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_less_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30); - var subject = 1.January(0001).At(0, 0, 25); - - // Act - Action action = () => subject.Should().BeLessThan(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:25> to be less than 10s after <00:00:30>, but it is behind by 5s."); - } - - [Fact] - public void When_asserting_subject_be_more_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30); - var subject = 1.January(0001).At(0, 0, 45); - - // Act - Action action = () => subject.Should().BeMoreThan(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:45> to be more than 10s before <00:00:30>, but it is ahead by 15s."); - } - - [Theory] - [InlineData(30, 40)] // edge case - [InlineData(30, 45)] - public void When_asserting_subject_be_at_least_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds); - var subject = 1.January(0001).At(0, 0, subjectSeconds); - - // Act - Action action = () => subject.Should().BeAtLeast(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be at least 10s before <00:00:30>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_exactly_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + public class HaveValue { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30); - var subject = 1.January(0001).At(0, 0, 40); - - // Act - Action action = () => subject.Should().BeExactly(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:40> to be exactly 10s before <00:00:30>, but it is ahead by 10s."); - } - - [Theory] - [InlineData(30, 40)] // edge case - [InlineData(30, 35)] - public void When_asserting_subject_be_within_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds); - var subject = 1.January(0001).At(0, 0, subjectSeconds); - - // Act - Action action = () => subject.Should().BeWithin(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be within 10s before <00:00:30>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } + [Fact] + public void Should_succeed_when_asserting_nullable_datetime_value_with_a_value_to_have_a_value() + { + // Arrange + DateTime? nullableDateTime = new DateTime(2016, 06, 04); - [Fact] - public void When_asserting_subject_be_less_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30); - var subject = 1.January(0001).At(0, 0, 45); + // Act + Action action = () => nullableDateTime.Should().HaveValue(); - // Act - Action action = () => subject.Should().BeLessThan(10.Seconds()).Before(expectation); + // Assert + action.Should().NotThrow(); + } - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:45> to be less than 10s before <00:00:30>, but it is ahead by 15s."); - } + [Fact] + public void Should_fail_when_asserting_nullable_datetime_value_without_a_value_to_have_a_value() + { + // Arrange + DateTime? nullableDateTime = null; - #endregion + // Act + Action action = () => nullableDateTime.Should().HaveValue(); - [Fact] - public void Should_support_chaining_constraints_with_and() - { - // Arrange - DateTime earlierDateTime = new DateTime(2016, 06, 03); - DateTime? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTime.Should() - .HaveValue() - .And - .BeAfter(earlierDateTime); - - // Assert - action.Should().NotThrow(); + // Assert + action.Should().Throw(); + } } - - #region Be One Of - - [Fact] - public void When_a_value_is_not_one_of_the_specified_values_it_should_throw() + public class NotHaveValue { - // Arrange - DateTime value = new DateTime(2016, 12, 30, 23, 58, 57); + [Fact] + public void Should_succeed_when_asserting_nullable_datetime_value_without_a_value_to_not_have_a_value() + { + // Arrange + DateTime? nullableDateTime = null; - // Act - Action action = () => value.Should().BeOneOf(value + 1.Days(), value + 1.Milliseconds()); + // Act + Action action = () => + nullableDateTime.Should().NotHaveValue(); - // Assert - action.Should().Throw() - .WithMessage("Expected value to be one of {<2016-12-31 23:58:57>, <2016-12-30 23:58:57.001>}, but found <2016-12-30 23:58:57>."); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() - { - // Arrange - DateTime value = new DateTime(2016, 12, 30, 23, 58, 57); + [Fact] + public void Should_fail_when_asserting_nullable_datetime_value_with_a_value_to_not_have_a_value() + { + // Arrange + DateTime? nullableDateTime = new DateTime(2016, 06, 04); - // Act - Action action = () => value.Should().BeOneOf(new[] { value + 1.Days(), value + 1.Milliseconds() }, "because it's true"); + // Act + Action action = () => + nullableDateTime.Should().NotHaveValue(); - // Assert - action.Should().Throw() - .WithMessage("Expected value to be one of {<2016-12-31 23:58:57>, <2016-12-30 23:58:57.001>} because it's true, but found <2016-12-30 23:58:57>."); + // Assert + action.Should().Throw(); + } } - [Fact] - public void When_a_value_is_one_of_the_specified_values_it_should_succeed() + public class NotBeNull { - // Arrange - DateTime value = new DateTime(2016, 12, 30, 23, 58, 57); - - // Act - Action action = () => value.Should().BeOneOf(new DateTime(2216, 1, 30, 0, 5, 7), new DateTime(2016, 12, 30, 23, 58, 57), new DateTime(2012, 3, 3)); + [Fact] + public void Should_succeed_when_asserting_nullable_datetime_value_with_a_value_to_not_be_null() + { + // Arrange + DateTime? nullableDateTime = new DateTime(2016, 06, 04); - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_a_null_value_is_not_one_of_the_specified_values_it_should_throw() - { - // Arrange - DateTime? value = null; + // Act + Action action = () => nullableDateTime.Should().NotBeNull(); - // Act - Action action = () => value.Should().BeOneOf(new DateTime(2216, 1, 30, 0, 5, 7), new DateTime(1116, 4, 10, 2, 45, 7)); + // Assert + action.Should().NotThrow(); + } - // Assert - action.Should().Throw() - .WithMessage("Expected value to be one of {<2216-01-30 00:05:07>, <1116-04-10 02:45:07>}, but found ."); + [Fact] + public void Should_fail_when_asserting_nullable_datetime_value_without_a_value_to_not_be_null() + { + // Arrange + DateTime? nullableDateTime = null; + + // Act + Action action = () => nullableDateTime.Should().NotBeNull(); + + // Assert + action.Should().Throw(); + } } - - [Fact] - public void When_a_value_is_one_of_the_specified_values_it_should_succeed_when_datetime_is_null() - { - // Arrange - DateTime? value = null; - - // Act - Action action = () => value.Should().BeOneOf(new DateTime(2216, 1, 30, 0, 5, 7), null); - - // Assert - action.Should().NotThrow(); + + public class BeNull + { + [Fact] + public void Should_succeed_when_asserting_nullable_datetime_value_without_a_value_to_be_null() + { + // Arrange + DateTime? nullableDateTime = null; + + // Act + Action action = () => + nullableDateTime.Should().BeNull(); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_nullable_datetime_value_with_a_value_to_be_null() + { + // Arrange + DateTime? nullableDateTime = new DateTime(2016, 06, 04); + + // Act + Action action = () => + nullableDateTime.Should().BeNull(); + + // Assert + action.Should().Throw(); + } + } + + public class Be + { + [Fact] + public void Should_succeed_when_asserting_datetime_value_is_equal_to_the_same_value() + { + // Arrange + DateTime dateTime = new DateTime(2016, 06, 04); + DateTime sameDateTime = new DateTime(2016, 06, 04); + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_datetime_value_is_equal_to_the_same_nullable_value_be_should_succeed() + { + // Arrange + DateTime dateTime = 4.June(2016); + DateTime? sameDateTime = 4.June(2016); + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_both_values_are_at_their_minimum_then_it_should_succeed() + { + // Arrange + DateTime dateTime = DateTime.MinValue; + DateTime sameDateTime = DateTime.MinValue; + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_both_values_are_at_their_maximum_then_it_should_succeed() + { + // Arrange + DateTime dateTime = DateTime.MaxValue; + DateTime sameDateTime = DateTime.MaxValue; + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_datetime_value_is_equal_to_the_different_value() + { + // Arrange + var dateTime = new DateTime(2012, 03, 10); + var otherDateTime = new DateTime(2012, 03, 11); + + // Act + Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected dateTime to be <2012-03-11>*failure message, but found <2012-03-10>."); + } + + [Fact] + public void When_datetime_value_is_equal_to_the_different_nullable_value_be_should_failed() + { + // Arrange + DateTime dateTime = 10.March(2012); + DateTime? otherDateTime = 11.March(2012); + + // Act + Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected dateTime to be <2012-03-11>*failure message, but found <2012-03-10>."); + } + + [Fact] + public void Should_succeed_when_asserting_nullable_numeric_value_equals_the_same_value() + { + // Arrange + DateTime? nullableDateTimeA = new DateTime(2016, 06, 04); + DateTime? nullableDateTimeB = new DateTime(2016, 06, 04); + + // Act + Action action = () => + nullableDateTimeA.Should().Be(nullableDateTimeB); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_a_nullable_date_time_is_equal_to_a_normal_date_time_but_the_kinds_differ_it_should_still_succeed() + { + // Arrange + DateTime? nullableDateTime = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Unspecified); + DateTime normalDateTime = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Utc); + + // Act + Action action = () => + nullableDateTime.Should().Be(normalDateTime); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_two_date_times_are_equal_but_the_kinds_differ_it_should_still_succeed() + { + // Arrange + DateTime dateTimeA = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Unspecified); + DateTime dateTimeB = new DateTime(2014, 4, 20, 9, 11, 0, DateTimeKind.Utc); + + // Act + Action action = () => + dateTimeA.Should().Be(dateTimeB); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void Should_succeed_when_asserting_nullable_numeric_null_value_equals_null() + { + // Arrange + DateTime? nullableDateTimeA = null; + DateTime? nullableDateTimeB = null; + + // Act + Action action = () => + nullableDateTimeA.Should().Be(nullableDateTimeB); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_nullable_numeric_value_equals_a_different_value() + { + // Arrange + DateTime? nullableDateTimeA = new DateTime(2016, 06, 04); + DateTime? nullableDateTimeB = new DateTime(2016, 06, 06); + + // Act + Action action = () => + nullableDateTimeA.Should().Be(nullableDateTimeB); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_datetime_null_value_is_equal_to_another_value() + { + // Arrange + DateTime? nullableDateTime = null; + + // Act + Action action = () => + nullableDateTime.Should().Be(new DateTime(2016, 06, 04), "because we want to test the failure {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected nullableDateTime to be <2016-06-04> because we want to test the failure message, but found ."); + } + } + + public class NotBe + { + [Fact] + public void Should_succeed_when_asserting_datetime_value_is_not_equal_to_a_different_value() + { + // Arrange + DateTime dateTime = new DateTime(2016, 06, 04); + DateTime otherDateTime = new DateTime(2016, 06, 05); + + // Act + Action act = () => dateTime.Should().NotBe(otherDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_datetime_value_is_not_equal_to_a_different_nullable_value_notbe_should_succeed() + { + // Arrange + DateTime dateTime = 4.June(2016); + DateTime? otherDateTime = 5.June(2016); + + // Act + Action act = () => dateTime.Should().NotBe(otherDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_datetime_value_is_not_equal_to_the_same_value() + { + // Arrange + var dateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Local); + var sameDateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Utc); + + // Act + Action act = + () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected dateTime not to be <2012-03-10 10:00:00> because we want to test the failure message, but it is."); + } + + [Fact] + public void When_datetime_value_is_not_equal_to_the_same_nullable_value_notbe_should_failed() + { + // Arrange + DateTime dateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Local); + DateTime? sameDateTime = DateTime.SpecifyKind(10.March(2012).At(10, 00), DateTimeKind.Utc); + + // Act + Action act = + () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected dateTime not to be <2012-03-10 10:00:00> because we want to test the failure message, but it is."); + } + } + + public class BeCloseTo + { + [Fact] + public void When_asserting_that_time_is_close_to_a_negative_precision_it_should_throw() + { + // Arrange + var dateTime = DateTime.UtcNow; + var actual = new DateTime(dateTime.Ticks - 1); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, -1.Ticks()); + + // Assert + act.Should().Throw() + .WithMessage("* value of precision must be non-negative*"); + } + + [Fact] + public void When_a_datetime_is_close_to_a_later_datetime_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTime.UtcNow; + var actual = new DateTime(dateTime.Ticks - 1); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_datetime_is_close_to_an_earlier_datetime_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTime.UtcNow; + var actual = new DateTime(dateTime.Ticks + 1); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_datetime_is_close_to_a_MinValue_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTime.MinValue; + var actual = new DateTime(dateTime.Ticks + 1); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_datetime_is_close_to_a_MaxValue_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTime.MaxValue; + var actual = new DateTime(dateTime.Ticks - 1); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_a_later_datetime_it_should_succeed() + { + // Arrange + DateTime time = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 30, 980), DateTimeKind.Unspecified); + DateTime nearbyTime = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 31), DateTimeKind.Utc); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_an_earlier_datetime_it_should_succeed() + { + // Arrange + DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 020); + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_another_value_that_is_later_by_more_than_20ms_it_should_throw() + { + // Arrange + DateTime time = 13.March(2012).At(12, 15, 30, 979); + DateTime nearbyTime = 13.March(2012).At(12, 15, 31); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected time to be within 20ms from <2012-03-13 12:15:31>, but found <2012-03-13 12:15:30.979>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_another_value_that_is_later_by_more_than_a_20ms_timespan_it_should_throw() + { + // Arrange + DateTime time = 13.March(2012).At(12, 15, 30, 979); + DateTime nearbyTime = 13.March(2012).At(12, 15, 31); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected time to be within 20ms from <2012-03-13 12:15:31>, but found <2012-03-13 12:15:30.979>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_throw() + { + // Arrange + DateTime time = 13.March(2012).At(12, 15, 31, 021); + DateTime nearbyTime = 13.March(2012).At(12, 15, 31); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected time to be within 20ms from <2012-03-13 12:15:31>, but found <2012-03-13 12:15:31.021>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_an_earlier_datetime_by_35ms_it_should_succeed() + { + // Arrange + DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 035); + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_is_close_to_another_it_should_throw() + { + // Arrange + DateTime? time = null; + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Expected*, but found ."); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_the_minimum_datetime_it_should_succeed() + { + // Arrange + DateTime time = DateTime.MinValue + 50.Milliseconds(); + DateTime nearbyTime = DateTime.MinValue; + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_close_to_the_maximum_datetime_it_should_succeed() + { + // Arrange + DateTime time = DateTime.MaxValue - 50.Milliseconds(); + DateTime nearbyTime = DateTime.MaxValue; + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + } + + public class NotBeCloseTo + { + [Fact] + public void When_asserting_that_time_is_not_close_to_a_negative_precision_it_should_throw() + { + // Arrange + var dateTime = DateTime.UtcNow; + var actual = new DateTime(dateTime.Ticks - 1); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, -1.Ticks()); + + // Assert + act.Should().Throw() + .WithMessage("* value of precision must be non-negative*"); + } + + [Fact] + public void When_a_datetime_is_close_to_a_later_datetime_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTime.UtcNow; + var actual = new DateTime(dateTime.Ticks - 1); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_datetime_is_close_to_an_earlier_datetime_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTime.UtcNow; + var actual = new DateTime(dateTime.Ticks + 1); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_datetime_is_close_to_a_MinValue_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTime.MinValue; + var actual = new DateTime(dateTime.Ticks + 1); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_datetime_is_close_to_a_MaxValue_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTime.MaxValue; + var actual = new DateTime(dateTime.Ticks - 1); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_a_later_datetime_it_should_throw() + { + // Arrange + DateTime time = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 30, 980), DateTimeKind.Unspecified); + DateTime nearbyTime = DateTime.SpecifyKind(new DateTime(2016, 06, 04).At(12, 15, 31), DateTimeKind.Utc); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:30.980>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_an_earlier_datetime_it_should_throw() + { + // Arrange + DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 020); + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:31.020>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_an_earlier_datetime_by_a_20ms_timespan_it_should_throw() + { + // Arrange + DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 020); + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:31.020>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_another_value_that_is_later_by_more_than_20ms_it_should_succeed() + { + // Arrange + DateTime time = 13.March(2012).At(12, 15, 30, 979); + DateTime nearbyTime = 13.March(2012).At(12, 15, 31); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_succeed() + { + // Arrange + DateTime time = 13.March(2012).At(12, 15, 31, 021); + DateTime nearbyTime = 13.March(2012).At(12, 15, 31); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_an_earlier_datetime_by_35ms_it_should_throw() + { + // Arrange + DateTime time = new DateTime(2016, 06, 04).At(12, 15, 31, 035); + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 35ms from <2016-06-04 12:15:31>, but it was <2016-06-04 12:15:31.035>."); + } + + [Fact] + public void When_asserting_subject_null_datetime_is_not_close_to_another_it_should_throw() + { + // Arrange + DateTime? time = null; + DateTime nearbyTime = new DateTime(2016, 06, 04).At(12, 15, 31); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect*, but it was ."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_the_minimum_datetime_it_should_throw() + { + // Arrange + DateTime time = DateTime.MinValue + 50.Milliseconds(); + DateTime nearbyTime = DateTime.MinValue; + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 100ms from <0001-01-01 00:00:00.000>, but it was <00:00:00.050>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_close_to_the_maximum_datetime_it_should_throw() + { + // Arrange + DateTime time = DateTime.MaxValue - 50.Milliseconds(); + DateTime nearbyTime = DateTime.MaxValue; + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 100ms from <9999-12-31 23:59:59.9999999>, but it was <9999-12-31 23:59:59.9499999>."); + } + } + + public class BeBefore + { + [Fact] + public void When_asserting_a_point_of_time_is_before_a_later_point_it_should_succeed() + { + // Arrange + DateTime earlierDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04), DateTimeKind.Unspecified); + DateTime laterDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04, 0, 5, 0), DateTimeKind.Utc); + + // Act + Action act = () => earlierDate.Should().BeBefore(laterDate); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_is_before_earlier_expected_datetime_it_should_throw() + { + // Arrange + DateTime expected = new DateTime(2016, 06, 03); + DateTime subject = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().BeBefore(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-03>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_before_the_same_datetime_it_should_throw() + { + // Arrange + DateTime expected = new DateTime(2016, 06, 04); + DateTime subject = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().BeBefore(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-04>, but found <2016-06-04>."); + } + } + public class NotBeBefore + { + [Fact] + public void When_asserting_a_point_of_time_is_not_before_another_it_should_throw() + { + // Arrange + DateTime earlierDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04), DateTimeKind.Unspecified); + DateTime laterDate = DateTime.SpecifyKind(new DateTime(2016, 06, 04, 0, 5, 0), DateTimeKind.Utc); + + // Act + Action act = () => earlierDate.Should().NotBeBefore(laterDate); + + // Assert + act.Should().Throw() + .WithMessage("Expected earlierDate to be on or after <2016-06-04 00:05:00>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_is_not_before_earlier_expected_datetime_it_should_succeed() + { + // Arrange + DateTime expected = new DateTime(2016, 06, 03); + DateTime subject = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().NotBeBefore(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_before_the_same_datetime_it_should_succeed() + { + // Arrange + DateTime expected = new DateTime(2016, 06, 04); + DateTime subject = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().NotBeBefore(expected); + + // Assert + act.Should().NotThrow(); + } + + } + public class BeOnOrBefore + { + [Fact] + public void When_asserting_subject_datetime_is_on_or_before_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 05); + + // Act + Action act = () => subject.Should().BeOnOrBefore(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_on_or_before_the_same_date_as_the_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().BeOnOrBefore(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 03); + + // Act + Action act = () => subject.Should().BeOnOrBefore(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be on or before <2016-06-03>, but found <2016-06-04>."); + } + } + public class NotBeOnOrBefore + { + [Fact] + public void When_asserting_subject_datetime_is_on_or_before_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 05); + + // Act + Action act = () => subject.Should().NotBeOnOrBefore(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be after <2016-06-05>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_on_or_before_the_same_date_as_the_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().NotBeOnOrBefore(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be after <2016-06-04>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 03); + + // Act + Action act = () => subject.Should().NotBeOnOrBefore(expectation); + + // Assert + act.Should().NotThrow(); + } + } + public class BeAfter + { + [Fact] + public void When_asserting_subject_datetime_is_after_earlier_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 03); + + // Act + Action act = () => subject.Should().BeAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_after_later_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 05); + + // Act + Action act = () => subject.Should().BeAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be after <2016-06-05>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_after_the_same_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().BeAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be after <2016-06-04>, but found <2016-06-04>."); + } + } + public class NotBeAfter + { + [Fact] + public void When_asserting_subject_datetime_is_not_after_earlier_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 03); + + // Act + Action act = () => subject.Should().NotBeAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be on or before <2016-06-03>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_after_later_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 05); + + // Act + Action act = () => subject.Should().NotBeAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_after_the_same_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().NotBeAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + } + + public class BeOnOrAfter + { + [Fact] + public void When_asserting_subject_datetime_is_on_or_after_earlier_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 03); + + // Act + Action act = () => subject.Should().BeOnOrAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_on_or_after_the_same_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().BeOnOrAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_is_on_or_after_later_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 05); + + // Act + Action act = () => subject.Should().BeOnOrAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be on or after <2016-06-05>, but found <2016-06-04>."); + } + } + + public class NotBeOnOrAfter + { + [Fact] + public void When_asserting_subject_datetime_is_not_on_or_after_earlier_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 03); + + // Act + Action act = () => subject.Should().NotBeOnOrAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-03>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_on_or_after_the_same_expected_datetime_should_throw() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 04); + + // Act + Action act = () => subject.Should().NotBeOnOrAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-04>, but found <2016-06-04>."); + } + + [Fact] + public void When_asserting_subject_datetime_is_not_on_or_after_later_expected_datetime_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2016, 06, 04); + DateTime expectation = new DateTime(2016, 06, 05); + + // Act + Action act = () => subject.Should().NotBeOnOrAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + } + + public class HaveYear + { + [Fact] + public void When_asserting_subject_datetime_should_have_year_with_the_same_value_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 2009; + + // Act + Action act = () => subject.Should().HaveYear(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_year_with_a_different_value_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 2008; + + // Act + Action act = () => subject.Should().HaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the year part of subject to be 2008, but found 2009."); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_have_year_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 2008; + + // Act + Action act = () => subject.Should().HaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the year part of subject to be 2008, but found ."); + } + } + + public class NotHaveYear + { + [Fact] + public void When_asserting_subject_datetime_should_not_have_year_with_the_same_value_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 2009; + + // Act + Action act = () => subject.Should().NotHaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the year part of subject to be 2009, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_year_with_a_different_value_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 2008; + + // Act + Action act = () => subject.Should().NotHaveYear(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_not_have_year_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 2008; + + // Act + Action act = () => subject.Should().NotHaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the year part of subject to be 2008, but found a DateTime."); + } + } + + public class HaveMonth + { + [Fact] + public void When_asserting_subject_datetime_should_have_month_with_the_same_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 12; + + // Act + Action act = () => subject.Should().HaveMonth(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_a_month_with_a_different_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 11; + + // Act + Action act = () => subject.Should().HaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the month part of subject to be 11, but found 12."); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_have_month_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 12; + + // Act + Action act = () => subject.Should().HaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the month part of subject to be 12, but found a DateTime."); + } + } + + public class NotHaveMonth + { + [Fact] + public void When_asserting_subject_datetime_should_not_have_month_with_the_same_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 12; + + // Act + Action act = () => subject.Should().NotHaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the month part of subject to be 12, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_a_month_with_a_different_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 11; + + // Act + Action act = () => subject.Should().NotHaveMonth(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_not_have_month_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 12; + + // Act + Action act = () => subject.Should().NotHaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the month part of subject to be 12, but found a DateTime."); + } + } + + public class HaveDay + { + [Fact] + public void When_asserting_subject_datetime_should_have_day_with_the_same_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 31; + + // Act + Action act = () => subject.Should().HaveDay(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_day_with_a_different_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 30; + + // Act + Action act = () => subject.Should().HaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the day part of subject to be 30, but found 31."); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_have_day_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the day part of subject to be 22, but found a DateTime."); + } + } + + public class BotHaveDay + { + [Fact] + public void When_asserting_subject_datetime_should_not_have_day_with_the_same_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 31; + + // Act + Action act = () => subject.Should().NotHaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the day part of subject to be 31, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_day_with_a_different_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31); + int expectation = 30; + + // Act + Action act = () => subject.Should().NotHaveDay(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_not_have_day_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the day part of subject to be 22, but found a DateTime."); + } + } + + public class HaveHour + { + [Fact] + public void When_asserting_subject_datetime_should_have_hour_with_the_same_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 23; + + // Act + Action act = () => subject.Should().HaveHour(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_hour_with_different_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the hour part of subject to be 22, but found 23."); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_have_hour_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the hour part of subject to be 22, but found a DateTime."); + } + } + + public class NotHaveHour + { + [Fact] + public void When_asserting_subject_datetime_should_not_have_hour_with_the_same_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 23; + + // Act + Action act = () => subject.Should().NotHaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the hour part of subject to be 23, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_hour_with_different_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveHour(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_not_have_hour_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the hour part of subject to be 22, but found a DateTime."); + } + } + + public class HaveMinute + { + [Fact] + public void When_asserting_subject_datetime_should_have_minutes_with_the_same_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 59; + + // Act + Action act = () => subject.Should().HaveMinute(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_minutes_with_different_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 58; + + // Act + Action act = () => subject.Should().HaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the minute part of subject to be 58, but found 59."); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_have_minute_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the minute part of subject to be 22, but found a DateTime."); + } + } + + public class NotHaveMinute + { + [Fact] + public void When_asserting_subject_datetime_should_not_have_minutes_with_the_same_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 59; + + // Act + Action act = () => subject.Should().NotHaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the minute part of subject to be 59, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_minutes_with_different_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 58; + + // Act + Action act = () => subject.Should().NotHaveMinute(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_not_have_minute_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the minute part of subject to be 22, but found a DateTime."); + } + } + + public class HaveSecond + { + [Fact] + public void When_asserting_subject_datetime_should_have_seconds_with_the_same_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 0; + + // Act + Action act = () => subject.Should().HaveSecond(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_seconds_with_different_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 1; + + // Act + Action act = () => subject.Should().HaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the seconds part of subject to be 1, but found 0."); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_have_second_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the seconds part of subject to be 22, but found a DateTime."); + } + } + + public class NotHaveSecond + { + [Fact] + public void When_asserting_subject_datetime_should_not_have_seconds_with_the_same_value_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 0; + + // Act + Action act = () => subject.Should().NotHaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the seconds part of subject to be 0, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_seconds_with_different_value_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00); + int expectation = 1; + + // Act + Action act = () => subject.Should().NotHaveSecond(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_should_not_have_second_should_throw() + { + // Arrange + DateTime? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the seconds part of subject to be 22, but found a DateTime."); + } + } + + public class BeInUtcOrLocal + { + [Fact] + public void When_asserting_subject_datetime_represents_its_own_kind_it_should_succeed() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00, DateTimeKind.Local); + + // Act + Action act = () => subject.Should().BeIn(DateTimeKind.Local); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_represents_a_different_kind_it_should_throw() + { + // Arrange + DateTime subject = new DateTime(2009, 12, 31, 23, 59, 00, DateTimeKind.Local); + + // Act + Action act = () => subject.Should().BeIn(DateTimeKind.Utc); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be in Utc, but found Local."); + } + + [Fact] + public void When_asserting_subject_null_datetime_represents_a_specific_kind_it_should_throw() + { + // Arrange + DateTime? subject = null; + + // Act + Action act = () => subject.Should().BeIn(DateTimeKind.Utc); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be in Utc, but found a DateTime."); + } + } + + public class BeSameDateAs + { + [Fact] + public void When_asserting_subject_datetime_should_be_same_date_as_another_with_the_same_date_it_should_succeed() + { + // Arrange + var subject = new DateTime(2009, 12, 31, 4, 5, 6); + + // Act + Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 31)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetime_should_be_same_as_another_with_same_date_but_different_time_it_should_succeed() + { + // Arrange + var subject = new DateTime(2009, 12, 31, 4, 5, 6); + + // Act + Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 31, 11, 15, 11)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetime_to_be_same_date_as_another_datetime_it_should_throw() + { + // Arrange + DateTime? subject = null; + + // Act + Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 31)); + + // Assert + act.Should().Throw().WithMessage( + "Expected the date part of subject to be <2009-12-31>, but found a DateTime."); + } + + [Fact] + public void When_asserting_subject_datetime_should_have_same_date_as_another_but_it_doesnt_it_should_throw() + { + // Arrange + var subject = new DateTime(2009, 12, 31); + + // Act + Action act = () => subject.Should().BeSameDateAs(new DateTime(2009, 12, 30)); + + // Assert + act.Should().Throw().WithMessage( + "Expected the date part of subject to be <2009-12-30>, but found <2009-12-31>."); + } + } + + public class NotBeSameDateAs + { + [Fact] + public void When_asserting_subject_datetime_should_not_be_same_date_as_another_with_the_same_date_it_should_throw() + { + // Arrange + var subject = new DateTime(2009, 12, 31, 4, 5, 6); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 31)); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_be_same_as_another_with_same_date_but_different_time_it_should_throw() + { + // Arrange + var subject = new DateTime(2009, 12, 31, 4, 5, 6); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 31, 11, 15, 11)); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); + } + + [Fact] + public void When_asserting_subject_null_datetime_to_not_be_same_date_as_another_datetime_it_should_throw() + { + // Arrange + DateTime? subject = null; + + // Act + Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 31)); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect the date part of subject to be <2009-12-31>, but found a DateTime."); + } + + [Fact] + public void When_asserting_subject_datetime_should_not_have_same_date_as_another_but_it_doesnt_it_should_succeed() + { + // Arrange + var subject = new DateTime(2009, 12, 31); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(new DateTime(2009, 12, 30)); + + // Assert + act.Should().NotThrow(); + } + } + + public class TimespanComparison + { + [Fact] + public void When_date_is_not_more_than_the_required_one_day_before_another_it_should_throw() + { + // Arrange + var target = new DateTime(2009, 10, 2); + DateTime subject = target - 1.Days(); + + // Act + Action act = () => subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <2009-10-01> to be more than 1d before <2009-10-02> because we like that, but it is behind by 1d."); + } + + [Fact] + public void When_date_is_more_than_the_required_one_day_before_another_it_should_not_throw() + { + // Arrange + var target = new DateTime(2009, 10, 2); + DateTime subject = target - 25.Hours(); + + // Act / Assert + subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target); + } + + [Fact] + public void When_date_is_not_at_least_one_day_before_another_it_should_throw() + { + // Arrange + var target = new DateTime(2009, 10, 2); + DateTime subject = target - 23.Hours(); + + // Act + Action act = () => subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <2009-10-01 01:00:00> to be at least 1d before <2009-10-02> because we like that, but it is behind by 23h."); + } + + [Fact] + public void When_date_is_at_least_one_day_before_another_it_should_not_throw() + { + // Arrange + var target = new DateTime(2009, 10, 2); + DateTime subject = target - 24.Hours(); + + // Act / Assert + subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target); + } + + [Fact] + public void When_time_is_not_at_exactly_20_minutes_before_another_time_it_should_throw() + { + // Arrange + DateTime target = 1.January(0001).At(12, 55); + DateTime subject = 1.January(0001).At(12, 36); + + // Act + Action act = + () => subject.Should().BeExactly(TimeSpan.FromMinutes(20)).Before(target, "{0} minutes is enough", 20); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <12:36:00> to be exactly 20m before <12:55:00> because 20 minutes is enough, but it is behind by 19m."); + } + + [Fact] + public void When_time_is_exactly_90_seconds_before_another_time_it_should_not_throw() + { + // Arrange + DateTime target = 1.January(0001).At(12, 55); + DateTime subject = 1.January(0001).At(12, 53, 30); + + // Act / Assert + subject.Should().BeExactly(TimeSpan.FromSeconds(90)).Before(target); + } + + [Fact] + public void When_date_is_not_within_50_hours_before_another_date_it_should_throw() + { + // Arrange + var target = new DateTime(2010, 4, 10, 12, 0, 0); + DateTime subject = target - 50.Hours() - 1.Seconds(); + + // Act + Action act = + () => subject.Should().BeWithin(TimeSpan.FromHours(50)).Before(target, "{0} hours is enough", 50); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <2010-04-08 09:59:59> to be within 2d and 2h before <2010-04-10 12:00:00> because 50 hours is enough, but it is behind by 2d, 2h and 1s."); + } + + [Fact] + public void When_date_is_exactly_within_1d_before_another_date_it_should_not_throw() + { + // Arrange + var target = new DateTime(2010, 4, 10); + DateTime subject = target - 1.Days(); + + // Act / Assert + subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); + } + + [Fact] + public void When_date_is_within_1d_before_another_date_it_should_not_throw() + { + // Arrange + var target = new DateTime(2010, 4, 10); + DateTime subject = target - 23.Hours(); + + // Act / Assert + subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); + } + + [Fact] + public void When_a_utc_date_is_within_0s_before_itself_it_should_not_throw() + { + // Arrange + var date = DateTime.UtcNow; // local timezone differs from UTC + + // Act / Assert + date.Should().BeWithin(TimeSpan.Zero).Before(date); + } + + [Fact] + public void When_a_utc_date_is_within_0s_after_itself_it_should_not_throw() + { + // Arrange + var date = DateTime.UtcNow; // local timezone differs from UTC + + // Act / Assert + date.Should().BeWithin(TimeSpan.Zero).After(date); + } + + [Fact] + public void When_time_is_not_less_than_30s_after_another_time_it_should_throw() + { + // Arrange + var target = new DateTime(1, 1, 1, 12, 0, 30); + DateTime subject = target + 30.Seconds(); + + // Act + Action act = + () => subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target, "{0}s is the max", 30); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <12:01:00> to be less than 30s after <12:00:30> because 30s is the max, but it is ahead by 30s."); + } + + [Fact] + public void When_time_is_less_than_30s_after_another_time_it_should_not_throw() + { + // Arrange + var target = new DateTime(1, 1, 1, 12, 0, 30); + DateTime subject = target + 20.Seconds(); + + // Act / Assert + subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target); + } + + [Fact] + public void When_asserting_subject_be_more_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30); + var subject = 1.January(0001).At(0, 0, 15); + + // Act + Action action = () => subject.Should().BeMoreThan(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:15> to be more than 10s after <00:00:30>, but it is behind by 15s."); + } + + [Theory] + [InlineData(30, 20)] // edge case + [InlineData(30, 15)] + public void When_asserting_subject_be_at_least_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds); + var subject = 1.January(0001).At(0, 0, subjectSeconds); + + // Act + Action action = () => subject.Should().BeAtLeast(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be at least 10s after <00:00:30>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_exactly_10_seconds_after_target_but_subject_is_before_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30); + var subject = 1.January(0001).At(0, 0, 20); + + // Ac + Action action = () => subject.Should().BeExactly(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:20> to be exactly 10s after <00:00:30>, but it is behind by 10s."); + } + + [Theory] + [InlineData(30, 20)] // edge case + [InlineData(30, 25)] + public void When_asserting_subject_be_within_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds); + var subject = 1.January(0001).At(0, 0, subjectSeconds); + + // Act + Action action = () => subject.Should().BeWithin(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be within 10s after <00:00:30>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_less_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30); + var subject = 1.January(0001).At(0, 0, 25); + + // Act + Action action = () => subject.Should().BeLessThan(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:25> to be less than 10s after <00:00:30>, but it is behind by 5s."); + } + + [Fact] + public void When_asserting_subject_be_more_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30); + var subject = 1.January(0001).At(0, 0, 45); + + // Act + Action action = () => subject.Should().BeMoreThan(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:45> to be more than 10s before <00:00:30>, but it is ahead by 15s."); + } + + [Theory] + [InlineData(30, 40)] // edge case + [InlineData(30, 45)] + public void When_asserting_subject_be_at_least_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds); + var subject = 1.January(0001).At(0, 0, subjectSeconds); + + // Act + Action action = () => subject.Should().BeAtLeast(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be at least 10s before <00:00:30>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_exactly_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30); + var subject = 1.January(0001).At(0, 0, 40); + + // Act + Action action = () => subject.Should().BeExactly(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:40> to be exactly 10s before <00:00:30>, but it is ahead by 10s."); + } + + [Theory] + [InlineData(30, 40)] // edge case + [InlineData(30, 35)] + public void When_asserting_subject_be_within_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds); + var subject = 1.January(0001).At(0, 0, subjectSeconds); + + // Act + Action action = () => subject.Should().BeWithin(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds}> to be within 10s before <00:00:30>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_less_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30); + var subject = 1.January(0001).At(0, 0, 45); + + // Act + Action action = () => subject.Should().BeLessThan(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:45> to be less than 10s before <00:00:30>, but it is ahead by 15s."); + } + } + + public class ChainingConstraint + { + [Fact] + public void Should_support_chaining_constraints_with_and() + { + // Arrange + DateTime earlierDateTime = new DateTime(2016, 06, 03); + DateTime? nullableDateTime = new DateTime(2016, 06, 04); + + // Act + Action action = () => + nullableDateTime.Should() + .HaveValue() + .And + .BeAfter(earlierDateTime); + + // Assert + action.Should().NotThrow(); + } + } + + public class BeOneOf + { + [Fact] + public void When_a_value_is_not_one_of_the_specified_values_it_should_throw() + { + // Arrange + DateTime value = new DateTime(2016, 12, 30, 23, 58, 57); + + // Act + Action action = () => value.Should().BeOneOf(value + 1.Days(), value + 1.Milliseconds()); + + // Assert + action.Should().Throw() + .WithMessage("Expected value to be one of {<2016-12-31 23:58:57>, <2016-12-30 23:58:57.001>}, but found <2016-12-30 23:58:57>."); + } + + [Fact] + public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() + { + // Arrange + DateTime value = new DateTime(2016, 12, 30, 23, 58, 57); + + // Act + Action action = () => value.Should().BeOneOf(new[] { value + 1.Days(), value + 1.Milliseconds() }, "because it's true"); + + // Assert + action.Should().Throw() + .WithMessage("Expected value to be one of {<2016-12-31 23:58:57>, <2016-12-30 23:58:57.001>} because it's true, but found <2016-12-30 23:58:57>."); + } + + [Fact] + public void When_a_value_is_one_of_the_specified_values_it_should_succeed() + { + // Arrange + DateTime value = new DateTime(2016, 12, 30, 23, 58, 57); + + // Act + Action action = () => value.Should().BeOneOf(new DateTime(2216, 1, 30, 0, 5, 7), new DateTime(2016, 12, 30, 23, 58, 57), new DateTime(2012, 3, 3)); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_a_null_value_is_not_one_of_the_specified_values_it_should_throw() + { + // Arrange + DateTime? value = null; + + // Act + Action action = () => value.Should().BeOneOf(new DateTime(2216, 1, 30, 0, 5, 7), new DateTime(1116, 4, 10, 2, 45, 7)); + + // Assert + action.Should().Throw() + .WithMessage("Expected value to be one of {<2216-01-30 00:05:07>, <1116-04-10 02:45:07>}, but found ."); + } + + [Fact] + public void When_a_value_is_one_of_the_specified_values_it_should_succeed_when_datetime_is_null() + { + // Arrange + DateTime? value = null; + + // Act + Action action = () => value.Should().BeOneOf(new DateTime(2216, 1, 30, 0, 5, 7), null); + + // Assert + action.Should().NotThrow(); + } } - - #endregion } } From 7845bb389607aee15c964ea67f9e6a9957bcb3be Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Mon, 18 Apr 2022 11:10:39 +0200 Subject: [PATCH 18/48] Seperate all enum assertions into nested classes --- .../Primitives/DateTimeAssertionSpecs.cs | 7 +- .../Primitives/EnumAssertionSpecs.cs | 1535 +++++++++-------- 2 files changed, 780 insertions(+), 762 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs index 3a5583ccde..6ea464c89d 100644 --- a/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs @@ -35,6 +35,7 @@ public void Should_fail_when_asserting_nullable_datetime_value_without_a_value_t action.Should().Throw(); } } + public class NotHaveValue { [Fact] @@ -828,6 +829,7 @@ public void When_asserting_subject_datetime_is_before_the_same_datetime_it_shoul .WithMessage("Expected subject to be before <2016-06-04>, but found <2016-06-04>."); } } + public class NotBeBefore { [Fact] @@ -872,8 +874,8 @@ public void When_asserting_subject_datetime_is_not_before_the_same_datetime_it_s // Assert act.Should().NotThrow(); } - } + public class BeOnOrBefore { [Fact] @@ -919,6 +921,7 @@ public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected .WithMessage("Expected subject to be on or before <2016-06-03>, but found <2016-06-04>."); } } + public class NotBeOnOrBefore { [Fact] @@ -965,6 +968,7 @@ public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected act.Should().NotThrow(); } } + public class BeAfter { [Fact] @@ -1011,6 +1015,7 @@ public void When_asserting_subject_datetime_is_after_the_same_expected_datetime_ .WithMessage("Expected subject to be after <2016-06-04>, but found <2016-06-04>."); } } + public class NotBeAfter { [Fact] diff --git a/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs index b38e6008d1..ba40334cf4 100644 --- a/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs @@ -20,80 +20,84 @@ public enum EnumLong : long public class EnumAssertionSpecs { - #region HaveFlag / NotHaveFlag - - [Fact] - public void When_enum_has_the_expected_flag_it_should_succeed() + public class HaveFlag { - // Arrange - TestEnum someObject = TestEnum.One | TestEnum.Two; + [Fact] + public void When_enum_has_the_expected_flag_it_should_succeed() + { + // Arrange + TestEnum someObject = TestEnum.One | TestEnum.Two; - // Act / Assert - someObject.Should().HaveFlag(TestEnum.One); - } + // Act / Assert + someObject.Should().HaveFlag(TestEnum.One); + } - [Fact] - public void When_null_enum_does_not_have_the_expected_flag_it_should_fail() - { - // Arrange - TestEnum? someObject = null; + [Fact] + public void When_null_enum_does_not_have_the_expected_flag_it_should_fail() + { + // Arrange + TestEnum? someObject = null; - // Act - Action act = () => someObject.Should().HaveFlag(TestEnum.Three); + // Act + Action act = () => someObject.Should().HaveFlag(TestEnum.Three); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_enum_does_not_have_specified_flag_it_should_fail_with_a_descriptive_message() - { - // Arrange - TestEnum someObject = TestEnum.One | TestEnum.Two; + [Fact] + public void When_enum_does_not_have_specified_flag_it_should_fail_with_a_descriptive_message() + { + // Arrange + TestEnum someObject = TestEnum.One | TestEnum.Two; - // Act - Action act = () => someObject.Should().HaveFlag(TestEnum.Three, "we want to test the failure {0}", "message"); + // Act + Action act = () => someObject.Should().HaveFlag(TestEnum.Three, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected*have flag TestEnum.Three {value: 4}*because we want to test the failure message*but found TestEnum.One|Two {value: 3}."); + // Assert + act.Should().Throw() + .WithMessage("Expected*have flag TestEnum.Three {value: 4}*because we want to test the failure message*but found TestEnum.One|Two {value: 3}."); + } } - [Fact] - public void When_enum_does_not_have_the_unexpected_flag_it_should_succeed() + public class NotHaveFlag { - // Arrange - TestEnum someObject = TestEnum.One | TestEnum.Two; + [Fact] + public void When_enum_does_not_have_the_unexpected_flag_it_should_succeed() + { + // Arrange + TestEnum someObject = TestEnum.One | TestEnum.Two; - // Act / Assert - someObject.Should().NotHaveFlag(TestEnum.Three); - } + // Act / Assert + someObject.Should().NotHaveFlag(TestEnum.Three); + } - [Fact] - public void When_enum_does_have_specified_flag_it_should_fail_with_a_descriptive_message() - { - // Arrange - TestEnum someObject = TestEnum.One | TestEnum.Two; + [Fact] + public void When_enum_does_have_specified_flag_it_should_fail_with_a_descriptive_message() + { + // Arrange + TestEnum someObject = TestEnum.One | TestEnum.Two; - // Act - Action act = () => someObject.Should().NotHaveFlag(TestEnum.Two, "we want to test the failure {0}", "message"); + // Act + Action act = () => someObject.Should().NotHaveFlag(TestEnum.Two, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected*someObject*to not have flag TestEnum.Two {value: 2}*because we want to test the failure message*"); - } + // Assert + act.Should().Throw() + .WithMessage("Expected*someObject*to not have flag TestEnum.Two {value: 2}*because we want to test the failure message*"); + } - [Fact] - public void When_null_enum_does_not_have_the_expected_flag_it_should_not_fail() - { - // Arrange - TestEnum? someObject = null; + [Fact] + public void When_null_enum_does_not_have_the_expected_flag_it_should_not_fail() + { + // Arrange + TestEnum? someObject = null; - // Act - Action act = () => someObject.Should().NotHaveFlag(TestEnum.Three); + // Act + Action act = () => someObject.Should().NotHaveFlag(TestEnum.Three); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } [Flags] @@ -113,346 +117,407 @@ public enum OtherEnum Second } - #endregion - - #region Be / NotBe - - [Fact] - public void When_enums_are_equal_it_should_succeed() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnum expected = MyEnum.One; - - // Act - Action act = () => subject.Should().Be(expected); - - // Assert - act.Should().NotThrow(); - } - - [Theory] - [InlineData(null, null)] - [InlineData(MyEnum.One, MyEnum.One)] - public void When_nullable_enums_are_equal_it_should_succeed(MyEnum? subject, MyEnum? expected) - { - // Act - Action act = () => subject.Should().Be(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_null_enum_and_an_enum_are_unequal_it_should_throw() - { - // Arrange - MyEnum? subject = null; - MyEnum expected = MyEnum.Two; - - // Act - Action act = () => subject.Should().Be(expected); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_enums_are_unequal_it_should_throw() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnum expected = MyEnum.Two; - - // Act - Action act = () => subject.Should().Be(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*subject*because we want to test the failure message*"); - } - - [Theory] - [InlineData(null, MyEnum.One)] - [InlineData(MyEnum.One, null)] - [InlineData(MyEnum.One, MyEnum.Two)] - public void When_nullable_enums_are_equal_it_should_throw(MyEnum? subject, MyEnum? expected) - { - // Act - Action act = () => subject.Should().Be(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Fact] - public void When_enums_are_unequal_it_should_succeed() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnum expected = MyEnum.Two; - - // Act - Action act = () => subject.Should().NotBe(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_null_enum_and_an_enum_are_unequal_it_should_succeed() - { - // Arrange - MyEnum? subject = null; - MyEnum expected = MyEnum.Two; - - // Act - Action act = () => subject.Should().NotBe(expected); - - // Assert - act.Should().NotThrow(); - } - - [Theory] - [InlineData(null, MyEnum.One)] - [InlineData(MyEnum.One, null)] - [InlineData(MyEnum.One, MyEnum.Two)] - public void When_nullable_enums_are_unequal_it_should_succeed(MyEnum? subject, MyEnum? expected) - { - // Act - Action act = () => subject.Should().NotBe(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_enums_are_equal_it_should_throw() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnum expected = MyEnum.One; - - // Act - Action act = () => subject.Should().NotBe(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Theory] - [InlineData(null, null)] - [InlineData(MyEnum.One, MyEnum.One)] - public void When_nullable_enums_are_unequal_it_should_throw(MyEnum? subject, MyEnum? expected) - { - // Act - Action act = () => subject.Should().NotBe(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - + public class Be + { + [Fact] + public void When_enums_are_equal_it_should_succeed() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnum expected = MyEnum.One; + + // Act + Action act = () => subject.Should().Be(expected); + + // Assert + act.Should().NotThrow(); + } + + [Theory] + [InlineData(null, null)] + [InlineData(MyEnum.One, MyEnum.One)] + public void When_nullable_enums_are_equal_it_should_succeed(MyEnum? subject, MyEnum? expected) + { + // Act + Action act = () => subject.Should().Be(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_null_enum_and_an_enum_are_unequal_it_should_throw() + { + // Arrange + MyEnum? subject = null; + MyEnum expected = MyEnum.Two; + + // Act + Action act = () => subject.Should().Be(expected); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_enums_are_unequal_it_should_throw() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnum expected = MyEnum.Two; + + // Act + Action act = () => subject.Should().Be(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*subject*because we want to test the failure message*"); + } + + [Theory] + [InlineData(null, MyEnum.One)] + [InlineData(MyEnum.One, null)] + [InlineData(MyEnum.One, MyEnum.Two)] + public void When_nullable_enums_are_equal_it_should_throw(MyEnum? subject, MyEnum? expected) + { + // Act + Action act = () => subject.Should().Be(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + + public class NotBe + { + [Fact] + public void When_enums_are_unequal_it_should_succeed() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnum expected = MyEnum.Two; + + // Act + Action act = () => subject.Should().NotBe(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_null_enum_and_an_enum_are_unequal_it_should_succeed() + { + // Arrange + MyEnum? subject = null; + MyEnum expected = MyEnum.Two; + + // Act + Action act = () => subject.Should().NotBe(expected); + + // Assert + act.Should().NotThrow(); + } + + [Theory] + [InlineData(null, MyEnum.One)] + [InlineData(MyEnum.One, null)] + [InlineData(MyEnum.One, MyEnum.Two)] + public void When_nullable_enums_are_unequal_it_should_succeed(MyEnum? subject, MyEnum? expected) + { + // Act + Action act = () => subject.Should().NotBe(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_enums_are_equal_it_should_throw() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnum expected = MyEnum.One; + + // Act + Action act = () => subject.Should().NotBe(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + + [Theory] + [InlineData(null, null)] + [InlineData(MyEnum.One, MyEnum.One)] + public void When_nullable_enums_are_unequal_it_should_throw(MyEnum? subject, MyEnum? expected) + { + // Act + Action act = () => subject.Should().NotBe(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + public enum MyEnum { One = 1, Two = 2 } - #endregion - - #region HaveValue / NotHaveValue - - [Fact] - public void When_enum_has_the_expected_value_it_should_succeed() - { - // Arrange - TestEnum someObject = TestEnum.One; - - // Act / Assert - someObject.Should().HaveValue(1); - } - - [Fact] - public void When_null_enum_does_not_have_the_expected_value_it_should_fail() - { - // Arrange - TestEnum? someObject = null; - - // Act - Action act = () => someObject.Should().HaveValue(3); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_enum_does_not_have_specified_value_it_should_fail_with_a_descriptive_message() - { - // Arrange - TestEnum someObject = TestEnum.One; - - // Act - Action act = () => someObject.Should().HaveValue(3, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected*have value 3*because we want to test the failure message*but found*"); - } - - [Fact] - public void When_enum_does_not_have_the_unexpected_value_it_should_succeed() - { - // Arrange - TestEnum someObject = TestEnum.One; - - // Act / Assert - someObject.Should().NotHaveValue(3); - } - - [Fact] - public void When_enum_does_have_specified_value_it_should_fail_with_a_descriptive_message() - { - // Arrange - TestEnum someObject = TestEnum.One; - - // Act - Action act = () => someObject.Should().NotHaveValue(1, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected*someObject*to not have value 1*because we want to test the failure message*"); - } - - [Fact] - public void When_null_enum_does_not_have_the_expected_value_it_should_not_fail() - { - // Arrange - TestEnum? someObject = null; - - // Act - Action act = () => someObject.Should().NotHaveValue(3); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region HaveSameValueAs / NotHaveSameValueAs - - [Fact] - public void When_enums_have_equal_values_it_should_succeed() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherName expected = MyEnumOtherName.OtherOne; - - // Act - Action act = () => subject.Should().HaveSameValueAs(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_nullable_enums_have_equal_values_it_should_succeed() - { - // Arrange - MyEnum? subject = MyEnum.One; - MyEnumOtherName expected = MyEnumOtherName.OtherOne; - - // Act - Action act = () => subject.Should().HaveSameValueAs(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_enums_have_equal_values_it_should_throw() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherName expected = MyEnumOtherName.OtherTwo; - - // Act - Action act = () => subject.Should().HaveSameValueAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Theory] - [InlineData(null, MyEnumOtherName.OtherOne)] - [InlineData(MyEnum.One, MyEnumOtherName.OtherTwo)] - public void When_nullable_enums_have_equal_values_it_should_throw(MyEnum? subject, MyEnumOtherName expected) - { - // Act - Action act = () => subject.Should().HaveSameValueAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Fact] - public void When_enum_have_unequal_values_it_should_succeed() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherName expected = MyEnumOtherName.OtherTwo; + public class HaveValue + { + [Fact] + public void When_enum_has_the_expected_value_it_should_succeed() + { + // Arrange + TestEnum someObject = TestEnum.One; - // Act - Action act = () => subject.Should().NotHaveSameValueAs(expected); + // Act / Assert + someObject.Should().HaveValue(1); + } + + [Fact] + public void When_null_enum_does_not_have_the_expected_value_it_should_fail() + { + // Arrange + TestEnum? someObject = null; + + // Act + Action act = () => someObject.Should().HaveValue(3); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_enum_does_not_have_specified_value_it_should_fail_with_a_descriptive_message() + { + // Arrange + TestEnum someObject = TestEnum.One; + + // Act + Action act = () => someObject.Should().HaveValue(3, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected*have value 3*because we want to test the failure message*but found*"); + } - [Theory] - [InlineData(null, MyEnumOtherName.OtherOne)] - [InlineData(MyEnum.One, MyEnumOtherName.OtherTwo)] - public void When_nullable_enums_have_unequal_values_it_should_succeed(MyEnum? subject, MyEnumOtherName expected) - { - // Act - Action act = () => subject.Should().NotHaveSameValueAs(expected); + [Fact] + public void When_nullable_enum_has_value_it_should_be_chainable() + { + // Arrange + MyEnum? subject = MyEnum.One; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().HaveValue() + .Which.Should().Be(MyEnum.One); - [Fact] - public void When_enums_have_unequal_values_it_should_throw() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherName expected = MyEnumOtherName.OtherOne; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => subject.Should().NotHaveSameValueAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Fact] - public void When_nullable_enums_have_unequal_values_it_should_throw() - { - // Arrange - MyEnum? subject = MyEnum.One; - MyEnumOtherName expected = MyEnumOtherName.OtherOne; - - // Act - Action act = () => subject.Should().NotHaveSameValueAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); + [Fact] + public void When_nullable_enum_does_not_have_value_it_should_throw() + { + // Arrange + MyEnum? subject = null; + + // Act + Action act = () => subject.Should().HaveValue("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + + public class NotHaveValue + { + [Fact] + public void When_enum_does_not_have_the_unexpected_value_it_should_succeed() + { + // Arrange + TestEnum someObject = TestEnum.One; + + // Act / Assert + someObject.Should().NotHaveValue(3); + } + + [Fact] + public void When_enum_does_have_specified_value_it_should_fail_with_a_descriptive_message() + { + // Arrange + TestEnum someObject = TestEnum.One; + + // Act + Action act = () => someObject.Should().NotHaveValue(1, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected*someObject*to not have value 1*because we want to test the failure message*"); + } + + [Fact] + public void When_null_enum_does_not_have_the_expected_value_it_should_not_fail() + { + // Arrange + TestEnum? someObject = null; + + // Act + Action act = () => someObject.Should().NotHaveValue(3); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_nullable_enum_does_not_have_value_it_should_succeed() + { + // Arrange + MyEnum? subject = null; + + // Act + Action act = () => subject.Should().NotHaveValue(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_nullable_enum_has_value_it_should_throw() + { + // Arrange + MyEnum? subject = MyEnum.One; + + // Act + Action act = () => subject.Should().NotHaveValue("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + + public class HaveSameValueAs + { + [Fact] + public void When_enums_have_equal_values_it_should_succeed() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherName expected = MyEnumOtherName.OtherOne; + + // Act + Action act = () => subject.Should().HaveSameValueAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_nullable_enums_have_equal_values_it_should_succeed() + { + // Arrange + MyEnum? subject = MyEnum.One; + MyEnumOtherName expected = MyEnumOtherName.OtherOne; + + // Act + Action act = () => subject.Should().HaveSameValueAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_enums_have_equal_values_it_should_throw() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherName expected = MyEnumOtherName.OtherTwo; + + // Act + Action act = () => subject.Should().HaveSameValueAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + + [Theory] + [InlineData(null, MyEnumOtherName.OtherOne)] + [InlineData(MyEnum.One, MyEnumOtherName.OtherTwo)] + public void When_nullable_enums_have_equal_values_it_should_throw(MyEnum? subject, MyEnumOtherName expected) + { + // Act + Action act = () => subject.Should().HaveSameValueAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + + public class NotHaveSameValueAs + { + [Fact] + public void When_enum_have_unequal_values_it_should_succeed() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherName expected = MyEnumOtherName.OtherTwo; + + // Act + Action act = () => subject.Should().NotHaveSameValueAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Theory] + [InlineData(null, MyEnumOtherName.OtherOne)] + [InlineData(MyEnum.One, MyEnumOtherName.OtherTwo)] + public void When_nullable_enums_have_unequal_values_it_should_succeed(MyEnum? subject, MyEnumOtherName expected) + { + // Act + Action act = () => subject.Should().NotHaveSameValueAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_enums_have_unequal_values_it_should_throw() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherName expected = MyEnumOtherName.OtherOne; + + // Act + Action act = () => subject.Should().NotHaveSameValueAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + + [Fact] + public void When_nullable_enums_have_unequal_values_it_should_throw() + { + // Arrange + MyEnum? subject = MyEnum.One; + MyEnumOtherName expected = MyEnumOtherName.OtherOne; + + // Act + Action act = () => subject.Should().NotHaveSameValueAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } } public enum MyEnumOtherName @@ -461,414 +526,362 @@ public enum MyEnumOtherName OtherTwo = 2 } - #endregion - - #region HaveSameNameAs / NotHaveSameNameAs - - [Fact] - public void When_enums_have_equal_names_it_should_succeed() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherValue expected = MyEnumOtherValue.One; - - // Act - Action act = () => subject.Should().HaveSameNameAs(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_nullable_enums_have_equal_names_it_should_succeed() - { - // Arrange - MyEnum? subject = MyEnum.One; - MyEnumOtherValue expected = MyEnumOtherValue.One; - - // Act - Action act = () => subject.Should().HaveSameNameAs(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_enums_have_equal_names_it_should_throw() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherValue expected = MyEnumOtherValue.Two; - - // Act - Action act = () => subject.Should().HaveSameNameAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Theory] - [InlineData(null, MyEnumOtherValue.One)] - [InlineData(MyEnum.One, MyEnumOtherValue.Two)] - public void When_nullable_enums_have_equal_names_it_should_throw(MyEnum? subject, MyEnumOtherValue expected) - { - // Act - Action act = () => subject.Should().HaveSameNameAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Fact] - public void When_senum_have_unequal_names_it_should_succeed() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherValue expected = MyEnumOtherValue.Two; - - // Act - Action act = () => subject.Should().NotHaveSameNameAs(expected); - - // Assert - act.Should().NotThrow(); - } - - [Theory] - [InlineData(null, MyEnumOtherValue.One)] - [InlineData(MyEnum.One, MyEnumOtherValue.Two)] - public void When_nullable_enums_have_unequal_names_it_should_succeed(MyEnum? subject, MyEnumOtherValue expected) - { - // Act - Action act = () => subject.Should().NotHaveSameNameAs(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_enums_have_unequal_names_it_should_throw() - { - // Arrange - MyEnum subject = MyEnum.One; - MyEnumOtherValue expected = MyEnumOtherValue.One; - - // Act - Action act = () => subject.Should().NotHaveSameNameAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - - [Fact] - public void When_nullable_enums_have_unequal_names_it_should_throw() - { - // Arrange - MyEnum? subject = MyEnum.One; - MyEnumOtherValue expected = MyEnumOtherValue.One; - - // Act - Action act = () => subject.Should().NotHaveSameNameAs(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } - + public class HaveSameNameAs + { + [Fact] + public void When_enums_have_equal_names_it_should_succeed() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherValue expected = MyEnumOtherValue.One; + + // Act + Action act = () => subject.Should().HaveSameNameAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_nullable_enums_have_equal_names_it_should_succeed() + { + // Arrange + MyEnum? subject = MyEnum.One; + MyEnumOtherValue expected = MyEnumOtherValue.One; + + // Act + Action act = () => subject.Should().HaveSameNameAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_enums_have_equal_names_it_should_throw() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherValue expected = MyEnumOtherValue.Two; + + // Act + Action act = () => subject.Should().HaveSameNameAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + + [Theory] + [InlineData(null, MyEnumOtherValue.One)] + [InlineData(MyEnum.One, MyEnumOtherValue.Two)] + public void When_nullable_enums_have_equal_names_it_should_throw(MyEnum? subject, MyEnumOtherValue expected) + { + // Act + Action act = () => subject.Should().HaveSameNameAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + + public class NotHaveSameNameAs + { + [Fact] + public void When_senum_have_unequal_names_it_should_succeed() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherValue expected = MyEnumOtherValue.Two; + + // Act + Action act = () => subject.Should().NotHaveSameNameAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Theory] + [InlineData(null, MyEnumOtherValue.One)] + [InlineData(MyEnum.One, MyEnumOtherValue.Two)] + public void When_nullable_enums_have_unequal_names_it_should_succeed(MyEnum? subject, MyEnumOtherValue expected) + { + // Act + Action act = () => subject.Should().NotHaveSameNameAs(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_enums_have_unequal_names_it_should_throw() + { + // Arrange + MyEnum subject = MyEnum.One; + MyEnumOtherValue expected = MyEnumOtherValue.One; + + // Act + Action act = () => subject.Should().NotHaveSameNameAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + + [Fact] + public void When_nullable_enums_have_unequal_names_it_should_throw() + { + // Arrange + MyEnum? subject = MyEnum.One; + MyEnumOtherValue expected = MyEnumOtherValue.One; + + // Act + Action act = () => subject.Should().NotHaveSameNameAs(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } + } + public enum MyEnumOtherValue { One = 11, Two = 22 } - #endregion - - #region BeNull / NotBeNull - - [Fact] - public void When_nullable_enum_has_value_it_should_be_chainable() - { - // Arrange - MyEnum? subject = MyEnum.One; - - // Act - Action act = () => subject.Should().HaveValue() - .Which.Should().Be(MyEnum.One); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_nullable_enum_is_not_null_it_should_be_chainable() + public class BeNull { - // Arrange - MyEnum? subject = MyEnum.One; + [Fact] + public void When_nullable_enum_is_null_it_should_succeed() + { + // Arrange + MyEnum? subject = null; - // Act - Action act = () => subject.Should().NotBeNull() - .Which.Should().Be(MyEnum.One); + // Act + Action act = () => subject.Should().BeNull(); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_nullable_enum_does_not_have_value_it_should_throw() - { - // Arrange - MyEnum? subject = null; + [Fact] + public void When_nullable_enum_is_not_null_it_should_throw() + { + // Arrange + MyEnum? subject = MyEnum.One; - // Act - Action act = () => subject.Should().HaveValue("we want to test the failure {0}", "message"); + // Act + Action act = () => subject.Should().BeNull("we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } } - [Fact] - public void When_nullable_enum_is_null_it_should_throw() + public class NotBeNull { - // Arrange - MyEnum? subject = null; - - // Act - Action act = () => subject.Should().NotBeNull("we want to test the failure {0}", "message"); + [Fact] + public void When_nullable_enum_is_not_null_it_should_be_chainable() + { + // Arrange + MyEnum? subject = MyEnum.One; - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } + // Act + Action act = () => subject.Should().NotBeNull() + .Which.Should().Be(MyEnum.One); + + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_nullable_enum_does_not_have_value_it_should_succeed() - { - // Arrange - MyEnum? subject = null; + [Fact] + public void When_nullable_enum_is_null_it_should_throw() + { + // Arrange + MyEnum? subject = null; - // Act - Action act = () => subject.Should().NotHaveValue(); + // Act + Action act = () => subject.Should().NotBeNull("we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } } - - [Fact] - public void When_nullable_enum_is_null_it_should_succeed() + + public class Match { - // Arrange - MyEnum? subject = null; + [Fact] + public void An_enum_matching_the_predicate_should_not_throw() + { + // Arrange + BindingFlags flags = BindingFlags.Public; - // Act - Action act = () => subject.Should().BeNull(); + // Act / Assert + flags.Should().Match(x => x == BindingFlags.Public); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void An_enum_not_matching_the_predicate_should_throw_with_the_predicate_in_the_message() + { + // Arrange + BindingFlags flags = BindingFlags.Public; - [Fact] - public void When_nullable_enum_has_value_it_should_throw() - { - // Arrange - MyEnum? subject = MyEnum.One; - - // Act - Action act = () => subject.Should().NotHaveValue("we want to test the failure {0}", "message"); + // Act + Action act = () => flags.Should().Match(x => x == BindingFlags.Static, "that's what we need"); + + // Assert + act.Should().Throw().WithMessage("Expected*Static*because that's what we need*found*Public*"); + } + + [Fact] + public void An_enum_cannot_be_compared_with_a_null_predicate() + { + // Act + Action act = () => BindingFlags.Public.Should().Match(null); - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); + // Assert + act.Should().Throw().WithMessage("*null*predicate*"); + } } - [Fact] - public void When_nullable_enum_is_not_null_it_should_throw() + public class BeOneOf { - // Arrange - MyEnum? subject = MyEnum.One; - - // Act - Action act = () => subject.Should().BeNull("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); + [Fact] + public void An_enum_that_is_one_of_the_expected_values_should_not_throw() + { + // Arrange + BindingFlags flags = BindingFlags.Public; + + // Act / Assert + flags.Should().BeOneOf(BindingFlags.Public, BindingFlags.ExactBinding); + } + + [Fact] + public void Throws_when_the_enums_is_not_one_of_the_expected_enums() + { + // Arrange + BindingFlags flags = BindingFlags.DeclaredOnly; + + // Act / Assert + Action act = () => flags.Should().BeOneOf(new[] { BindingFlags.Public, BindingFlags.ExactBinding }, "that's what we need"); + + act.Should() + .Throw() + .WithMessage("Expected*Public*ExactBinding*because that's what we need*found*DeclaredOnly*"); + } + + [Fact] + public void An_enum_cannot_be_part_of_an_empty_list() + { + // Arrange + BindingFlags flags = BindingFlags.DeclaredOnly; + + // Act / Assert + Action act = () => flags.Should().BeOneOf(Array.Empty()); + + act.Should() + .Throw() + .WithMessage("Cannot*empty list of enums*"); + } + + [Fact] + public void An_enum_cannot_be_part_of_a_null_list() + { + // Arrange + BindingFlags flags = BindingFlags.DeclaredOnly; + + // Act / Assert + Action act = () => flags.Should().BeOneOf(null); + + act.Should() + .Throw() + .WithMessage("Cannot*null list of enums*"); + } + } + + public class BeDefined + { + [Fact] + public void A_valid_entry_of_an_enum_is_defined() + { + // Arrange + var dayOfWeek = (DayOfWeek)1; + + // Act / Assert + dayOfWeek.Should().BeDefined(); + } + + [Fact] + public void If_a_value_casted_to_an_enum_type_and_it_does_not_exist_in_the_enum_it_throws() + { + // Arrange + var dayOfWeek = (DayOfWeek)999; + + // Act + Action act = () => dayOfWeek.Should().BeDefined("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected *to be defined in*failure message*, but it is not*"); + } + + [Fact] + public void A_null_entry_of_an_enum_throws() + { + // Arrange + MyEnum? subject = null; + + // Act + Action act = () => subject.Should().BeDefined(); + + // Assert + act.Should().Throw() + .WithMessage("Expected *to be defined in*, but found ."); + } } - - #endregion - - #region Match - - [Fact] - public void An_enum_matching_the_predicate_should_not_throw() + + public class NotBeDefined { - // Arrange - BindingFlags flags = BindingFlags.Public; - - // Act / Assert - flags.Should().Match(x => x == BindingFlags.Public); - } - - [Fact] - public void An_enum_not_matching_the_predicate_should_throw_with_the_predicate_in_the_message() - { - // Arrange - BindingFlags flags = BindingFlags.Public; - - // Act - Action act = () => flags.Should().Match(x => x == BindingFlags.Static, "that's what we need"); - - // Assert - act.Should().Throw().WithMessage("Expected*Static*because that's what we need*found*Public*"); - } - - [Fact] - public void An_enum_cannot_be_compared_with_a_null_predicate() - { - // Act - Action act = () => BindingFlags.Public.Should().Match(null); - - // Assert - act.Should().Throw().WithMessage("*null*predicate*"); - } - - #endregion - - #region Be One Of - - [Fact] - public void An_enum_that_is_one_of_the_expected_values_should_not_throw() - { - // Arrange - BindingFlags flags = BindingFlags.Public; - - // Act / Assert - flags.Should().BeOneOf(BindingFlags.Public, BindingFlags.ExactBinding); - } - - [Fact] - public void Throws_when_the_enums_is_not_one_of_the_expected_enums() - { - // Arrange - BindingFlags flags = BindingFlags.DeclaredOnly; - - // Act / Assert - Action act = () => flags.Should().BeOneOf(new[] { BindingFlags.Public, BindingFlags.ExactBinding }, "that's what we need"); - - act.Should() - .Throw() - .WithMessage("Expected*Public*ExactBinding*because that's what we need*found*DeclaredOnly*"); - } - - [Fact] - public void An_enum_cannot_be_part_of_an_empty_list() - { - // Arrange - BindingFlags flags = BindingFlags.DeclaredOnly; - - // Act / Assert - Action act = () => flags.Should().BeOneOf(Array.Empty()); - - act.Should() - .Throw() - .WithMessage("Cannot*empty list of enums*"); - } - - [Fact] - public void An_enum_cannot_be_part_of_a_null_list() - { - // Arrange - BindingFlags flags = BindingFlags.DeclaredOnly; - - // Act / Assert - Action act = () => flags.Should().BeOneOf(null); - - act.Should() - .Throw() - .WithMessage("Cannot*null list of enums*"); - } - - #endregion - - #region Be defined / Not be defined - - [Fact] - public void A_valid_entry_of_an_enum_is_defined() - { - // Arrange - var dayOfWeek = (DayOfWeek)1; - - // Act / Assert - dayOfWeek.Should().BeDefined(); - } - - [Fact] - public void If_a_value_casted_to_an_enum_type_and_it_does_not_exist_in_the_enum_it_throws() - { - // Arrange - var dayOfWeek = (DayOfWeek)999; - - // Act - Action act = () => dayOfWeek.Should().BeDefined("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected *to be defined in*failure message*, but it is not*"); - } - - [Fact] - public void A_null_entry_of_an_enum_throws() - { - // Arrange - MyEnum? subject = null; - - // Act - Action act = () => subject.Should().BeDefined(); - - // Assert - act.Should().Throw() - .WithMessage("Expected *to be defined in*, but found ."); - } - - [Fact] - public void An_invalid_entry_of_an_enum_is_not_defined_passes() - { - // Arrange - var dayOfWeek = (DayOfWeek)999; - - // Act / Assert - dayOfWeek.Should().NotBeDefined(); - } - - [Fact] - public void A_valid_entry_of_an_enum_is_not_defined_fails() - { - // Arrange - var dayOfWeek = (DayOfWeek)1; - - // Act - Action act = () => dayOfWeek.Should().NotBeDefined(); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect*to be defined in*, but it is."); - } - - [Fact] - public void A_null_value_of_an_enum_is_not_defined_and_throws() - { - // Arrange - MyEnum? subject = null; - - // Act - Action act = () => subject.Should().NotBeDefined(); + [Fact] + public void An_invalid_entry_of_an_enum_is_not_defined_passes() + { + // Arrange + var dayOfWeek = (DayOfWeek)999; + + // Act / Assert + dayOfWeek.Should().NotBeDefined(); + } + + [Fact] + public void A_valid_entry_of_an_enum_is_not_defined_fails() + { + // Arrange + var dayOfWeek = (DayOfWeek)1; + + // Act + Action act = () => dayOfWeek.Should().NotBeDefined(); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect*to be defined in*, but it is."); + } + + [Fact] + public void A_null_value_of_an_enum_is_not_defined_and_throws() + { + // Arrange + MyEnum? subject = null; + + // Act + Action act = () => subject.Should().NotBeDefined(); - // Assert - act.Should().Throw() - .WithMessage("Did not expect *to be defined in*, but found ."); + // Assert + act.Should().Throw() + .WithMessage("Did not expect *to be defined in*, but found ."); + } } - #endregion } } From 5699e93ac7f1fda249052ce246830e820c3299c1 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Mon, 18 Apr 2022 17:41:44 +0200 Subject: [PATCH 19/48] Seperate all DateTimeOffset assertions into nested classes --- .../DateTimeOffsetAssertionSpecs.cs | 4923 +++++++++-------- 1 file changed, 2492 insertions(+), 2431 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Primitives/DateTimeOffsetAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/DateTimeOffsetAssertionSpecs.cs index dcd5d383f0..421e23745f 100644 --- a/Tests/FluentAssertions.Specs/Primitives/DateTimeOffsetAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/DateTimeOffsetAssertionSpecs.cs @@ -8,2466 +8,2527 @@ namespace FluentAssertions.Specs.Primitives { public class DateTimeOffsetAssertionSpecs { - #region (Not) Have Value - - [Fact] - public void When_nullable_datetimeoffset_value_with_a_value_to_have_a_value_it_should_succeed() - { - // Arrange - DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => nullableDateTime.Should().HaveValue(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetimeoffset_value_without_a_value_to_have_a_value() - { - // Arrange - DateTimeOffset? nullableDateTime = null; - - // Act - Action action = () => nullableDateTime.Should().HaveValue(); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_datetimeoffset_value_without_a_value_to_not_have_a_value() - { - // Arrange - DateTimeOffset? nullableDateTime = null; - - // Act - Action action = () => - nullableDateTime.Should().NotHaveValue(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetimeoffset_value_with_a_value_to_not_have_a_value() - { - // Arrange - DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTime.Should().NotHaveValue(); - - // Assert - action.Should().Throw(); - } - - #endregion - - #region (Not) Be Null - - [Fact] - public void When_nullable_datetimeoffset_value_with_a_value_not_be_null_it_should_succeed() - { - // Arrange - DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => nullableDateTime.Should().NotBeNull(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetimeoffset_value_without_a_value_to_not_be_null() - { - // Arrange - DateTimeOffset? nullableDateTime = null; - - // Act - Action action = () => nullableDateTime.Should().NotBeNull(); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_datetimeoffset_value_without_a_value_to_be_null() - { - // Arrange - DateTimeOffset? nullableDateTime = null; - - // Act - Action action = () => - nullableDateTime.Should().BeNull(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_nullable_datetimeoffset_value_with_a_value_to_be_null() - { - // Arrange - DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTime.Should().BeNull(); - - // Assert - action.Should().Throw(); - } - - #endregion - - #region (Not) Be - - [Fact] - public void Should_succeed_when_asserting_datetimeoffset_value_is_equal_to_the_same_value() - { - // Arrange - DateTimeOffset dateTime = new DateTime(2016, 06, 04); - DateTimeOffset sameDateTime = new DateTime(2016, 06, 04); - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_datetimeoffset_value_is_equal_to_the_same_nullable_value_be_should_succeed() - { - // Arrange - DateTimeOffset dateTime = 4.June(2016); - DateTimeOffset? sameDateTime = 4.June(2016); - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_both_values_are_at_their_minimum_then_it_should_succeed() - { - // Arrange - DateTimeOffset dateTime = DateTimeOffset.MinValue; - DateTimeOffset sameDateTime = DateTimeOffset.MinValue; - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_both_values_are_at_their_maximum_then_it_should_succeed() - { - // Arrange - DateTimeOffset dateTime = DateTimeOffset.MaxValue; - DateTimeOffset sameDateTime = DateTimeOffset.MaxValue; - - // Act - Action act = () => dateTime.Should().Be(sameDateTime); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_datetimeoffset_value_is_equal_to_the_different_value() - { - // Arrange - var dateTime = 10.March(2012).WithOffset(1.Hours()); - var otherDateTime = 11.March(2012).WithOffset(1.Hours()); - - // Act - Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dateTime to represent the same point in time as <2012-03-11 +1h>*failure message, but <2012-03-10 +1h> does not."); - } - - [Fact] - public void When_datetimeoffset_value_is_equal_to_the_different_nullable_value_be_should_failed() - { - // Arrange - DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); - DateTimeOffset? otherDateTime = 11.March(2012).WithOffset(1.Hours()); - - // Act - Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dateTime to represent the same point in time as <2012-03-11 +1h>*failure message, but <2012-03-10 +1h> does not."); - } - - [Fact] - public void Should_succeed_when_asserting_datetimeoffset_value_is_not_equal_to_a_different_value() + public class HaveValue { - // Arrange - DateTimeOffset dateTime = new DateTime(2016, 06, 04); - DateTimeOffset otherDateTime = new DateTime(2016, 06, 05); + [Fact] + public void When_nullable_datetimeoffset_value_with_a_value_to_have_a_value_it_should_succeed() + { + // Arrange + DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - // Act - Action act = () => dateTime.Should().NotBe(otherDateTime); + // Act + Action action = () => nullableDateTime.Should().HaveValue(); - // Assert - act.Should().NotThrow(); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_datetimeoffset_value_is_not_equal_to_a_nullable_different_value_notbe_should_succeed() - { - // Arrange - DateTimeOffset dateTime = 4.June(2016); - DateTimeOffset? otherDateTime = 5.June(2016); + [Fact] + public void Should_fail_when_asserting_nullable_datetimeoffset_value_without_a_value_to_have_a_value() + { + // Arrange + DateTimeOffset? nullableDateTime = null; - // Act - Action act = () => dateTime.Should().NotBe(otherDateTime); + // Act + Action action = () => nullableDateTime.Should().HaveValue(); - // Assert - act.Should().NotThrow(); + // Assert + action.Should().Throw(); + } } - [Fact] - public void Should_fail_when_asserting_datetimeoffset_value_is_not_equal_to_the_same_value() + public class NotHaveValue { - // Arrange - var dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); - var sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + [Fact] + public void Should_succeed_when_asserting_nullable_datetimeoffset_value_without_a_value_to_not_have_a_value() + { + // Arrange + DateTimeOffset? nullableDateTime = null; - // Act - Action act = - () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); + // Act + Action action = () => + nullableDateTime.Should().NotHaveValue(); - // Assert - act.Should().Throw().WithMessage( - "Did not expect dateTime to represent the same point in time as <2012-03-10 +1h> because we want to test the failure message, but it did."); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_datetimeoffset_value_is_not_equal_to_the_same_nullable_value_notbe_should_failed() - { - // Arrange - DateTimeOffset dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); - DateTimeOffset? sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + [Fact] + public void Should_fail_when_asserting_nullable_datetimeoffset_value_with_a_value_to_not_have_a_value() + { + // Arrange + DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - // Act - Action act = - () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); + // Act + Action action = () => + nullableDateTime.Should().NotHaveValue(); - // Assert - act.Should().Throw().WithMessage( - "Did not expect dateTime to represent the same point in time as <2012-03-10 +1h> because we want to test the failure message, but it did."); + // Assert + action.Should().Throw(); + } } - [Fact] - public void Should_succeed_when_asserting_nullable_datetimeoffset_value_equals_the_same_value() + public class NotBeNull { - // Arrange - DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); - DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 04); + [Fact] + public void When_nullable_datetimeoffset_value_with_a_value_not_be_null_it_should_succeed() + { + // Arrange + DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - // Act - Action action = () => - nullableDateTimeA.Should().Be(nullableDateTimeB); + // Act + Action action = () => nullableDateTime.Should().NotBeNull(); - // Assert - action.Should().NotThrow(); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void Should_succeed_when_asserting_nullable_datetimeoffset_null_value_equals_null() - { - // Arrange - DateTimeOffset? nullableDateTimeA = null; - DateTimeOffset? nullableDateTimeB = null; + [Fact] + public void Should_fail_when_asserting_nullable_datetimeoffset_value_without_a_value_to_not_be_null() + { + // Arrange + DateTimeOffset? nullableDateTime = null; - // Act / Assert - nullableDateTimeA.Should().Be(nullableDateTimeB); + // Act + Action action = () => nullableDateTime.Should().NotBeNull(); + + // Assert + action.Should().Throw(); + } } - [Fact] - public void Should_fail_when_asserting_nullable_datetimeoffset_value_equals_a_different_value() + public class BeNull { - // Arrange - DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); - DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 06); - - // Act - Action action = () => + [Fact] + public void Should_succeed_when_asserting_nullable_datetimeoffset_value_without_a_value_to_be_null() + { + // Arrange + DateTimeOffset? nullableDateTime = null; + + // Act + Action action = () => + nullableDateTime.Should().BeNull(); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_nullable_datetimeoffset_value_with_a_value_to_be_null() + { + // Arrange + DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); + + // Act + Action action = () => + nullableDateTime.Should().BeNull(); + + // Assert + action.Should().Throw(); + } + } + + public class Be + { + [Fact] + public void Should_succeed_when_asserting_datetimeoffset_value_is_equal_to_the_same_value() + { + // Arrange + DateTimeOffset dateTime = new DateTime(2016, 06, 04); + DateTimeOffset sameDateTime = new DateTime(2016, 06, 04); + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_datetimeoffset_value_is_equal_to_the_same_nullable_value_be_should_succeed() + { + // Arrange + DateTimeOffset dateTime = 4.June(2016); + DateTimeOffset? sameDateTime = 4.June(2016); + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_both_values_are_at_their_minimum_then_it_should_succeed() + { + // Arrange + DateTimeOffset dateTime = DateTimeOffset.MinValue; + DateTimeOffset sameDateTime = DateTimeOffset.MinValue; + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_both_values_are_at_their_maximum_then_it_should_succeed() + { + // Arrange + DateTimeOffset dateTime = DateTimeOffset.MaxValue; + DateTimeOffset sameDateTime = DateTimeOffset.MaxValue; + + // Act + Action act = () => dateTime.Should().Be(sameDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_datetimeoffset_value_is_equal_to_the_different_value() + { + // Arrange + var dateTime = 10.March(2012).WithOffset(1.Hours()); + var otherDateTime = 11.March(2012).WithOffset(1.Hours()); + + // Act + Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dateTime to represent the same point in time as <2012-03-11 +1h>*failure message, but <2012-03-10 +1h> does not."); + } + + [Fact] + public void When_datetimeoffset_value_is_equal_to_the_different_nullable_value_be_should_failed() + { + // Arrange + DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); + DateTimeOffset? otherDateTime = 11.March(2012).WithOffset(1.Hours()); + + // Act + Action act = () => dateTime.Should().Be(otherDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dateTime to represent the same point in time as <2012-03-11 +1h>*failure message, but <2012-03-10 +1h> does not."); + } + + [Fact] + public void Should_succeed_when_asserting_nullable_datetimeoffset_value_equals_the_same_value() + { + // Arrange + DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); + DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 04); + + // Act + Action action = () => + nullableDateTimeA.Should().Be(nullableDateTimeB); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void Should_succeed_when_asserting_nullable_datetimeoffset_null_value_equals_null() + { + // Arrange + DateTimeOffset? nullableDateTimeA = null; + DateTimeOffset? nullableDateTimeB = null; + + // Act / Assert nullableDateTimeA.Should().Be(nullableDateTimeB); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_datetimeoffset_null_value_is_equal_to_another_value() - { - // Arrange - DateTimeOffset? nullableDateTime = null; - DateTimeOffset expectation = 27.March(2016).ToDateTimeOffset(1.Hours()); - - // Act - Action action = () => - nullableDateTime.Should().Be(expectation, "because we want to test the failure {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected nullableDateTime to represent the same point in time as <2016-03-27 +1h> because we want to test the failure message, but found a DateTimeOffset."); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_non_null_value_is_equal_to_null_value() - { - // Arrange - DateTimeOffset? nullableDateTime = 27.March(2016).ToDateTimeOffset(1.Hours()); - DateTimeOffset? expectation = null; - - // Act - Action action = () => - nullableDateTime.Should().Be(expectation, "because we want to test the failure {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected nullableDateTime to be because we want to test the failure message, but it was <2016-03-27 +1h>."); - } - - [Fact] - public void - When_asserting_different_date_time_offsets_representing_the_same_world_time_it_should_succeed() - { - // Arrange - var specificDate = 1.May(2008).At(6, 32); - - var dateWithFiveHourOffset = new DateTimeOffset(specificDate - 5.Hours(), -5.Hours()); - - var dateWithSixHourOffset = new DateTimeOffset(specificDate - 6.Hours(), -6.Hours()); - - // Act / Assert - dateWithFiveHourOffset.Should().Be(dateWithSixHourOffset); - } - - [Fact] - public void + } + + [Fact] + public void Should_fail_when_asserting_nullable_datetimeoffset_value_equals_a_different_value() + { + // Arrange + DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); + DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 06); + + // Act + Action action = () => + nullableDateTimeA.Should().Be(nullableDateTimeB); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_datetimeoffset_null_value_is_equal_to_another_value() + { + // Arrange + DateTimeOffset? nullableDateTime = null; + DateTimeOffset expectation = 27.March(2016).ToDateTimeOffset(1.Hours()); + + // Act + Action action = () => + nullableDateTime.Should().Be(expectation, "because we want to test the failure {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected nullableDateTime to represent the same point in time as <2016-03-27 +1h> because we want to test the failure message, but found a DateTimeOffset."); + } + + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_non_null_value_is_equal_to_null_value() + { + // Arrange + DateTimeOffset? nullableDateTime = 27.March(2016).ToDateTimeOffset(1.Hours()); + DateTimeOffset? expectation = null; + + // Act + Action action = () => + nullableDateTime.Should().Be(expectation, "because we want to test the failure {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected nullableDateTime to be because we want to test the failure message, but it was <2016-03-27 +1h>."); + } + + [Fact] + public void + When_asserting_different_date_time_offsets_representing_the_same_world_time_it_should_succeed() + { + // Arrange + var specificDate = 1.May(2008).At(6, 32); + + var dateWithFiveHourOffset = new DateTimeOffset(specificDate - 5.Hours(), -5.Hours()); + + var dateWithSixHourOffset = new DateTimeOffset(specificDate - 6.Hours(), -6.Hours()); + + // Act / Assert + dateWithFiveHourOffset.Should().Be(dateWithSixHourOffset); + } + } + + public class NotBe + { + [Fact] + public void Should_succeed_when_asserting_datetimeoffset_value_is_not_equal_to_a_different_value() + { + // Arrange + DateTimeOffset dateTime = new DateTime(2016, 06, 04); + DateTimeOffset otherDateTime = new DateTime(2016, 06, 05); + + // Act + Action act = () => dateTime.Should().NotBe(otherDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_datetimeoffset_value_is_not_equal_to_a_nullable_different_value_notbe_should_succeed() + { + // Arrange + DateTimeOffset dateTime = 4.June(2016); + DateTimeOffset? otherDateTime = 5.June(2016); + + // Act + Action act = () => dateTime.Should().NotBe(otherDateTime); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_datetimeoffset_value_is_not_equal_to_the_same_value() + { + // Arrange + var dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + var sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + + // Act + Action act = + () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect dateTime to represent the same point in time as <2012-03-10 +1h> because we want to test the failure message, but it did."); + } + + [Fact] + public void When_datetimeoffset_value_is_not_equal_to_the_same_nullable_value_notbe_should_failed() + { + // Arrange + DateTimeOffset dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + DateTimeOffset? sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + + // Act + Action act = + () => dateTime.Should().NotBe(sameDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect dateTime to represent the same point in time as <2012-03-10 +1h> because we want to test the failure message, but it did."); + } + + [Fact] + public void When_asserting_different_date_time_offsets_representing_different_world_times_it_should_not_succeed() - { - // Arrange - var specificDate = 1.May(2008).At(6, 32); - - var dateWithZeroHourOffset = new DateTimeOffset(specificDate, TimeSpan.Zero); - var dateWithOneHourOffset = new DateTimeOffset(specificDate, 1.Hours()); - - // Act / Assert - dateWithZeroHourOffset.Should().NotBe(dateWithOneHourOffset); - } - - #endregion - - #region (Not) BeExactly - - [Fact] - public void Should_succeed_when_asserting_value_is_exactly_equal_to_the_same_value() - { - // Arrange - DateTimeOffset dateTime = new DateTime(2016, 06, 04); - DateTimeOffset sameDateTime = new DateTime(2016, 06, 04); - - // Act / Assert - dateTime.Should().BeExactly(sameDateTime); - } - - [Fact] - public void Should_succeed_when_asserting_value_is_exactly_equal_to_the_same_nullable_value() - { - // Arrange - DateTimeOffset dateTime = 4.June(2016); - DateTimeOffset? sameDateTime = 4.June(2016); - - // Act / Assert - dateTime.Should().BeExactly(sameDateTime); - } - - [Fact] - public void Should_fail_when_asserting_value_is_exactly_equal_to_a_different_value() - { - // Arrange - var dateTime = 10.March(2012).WithOffset(1.Hours()); - var otherDateTime = dateTime.ToUniversalTime(); - - // Act - Action act = () => dateTime.Should().BeExactly(otherDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dateTime to be exactly <2012-03-09 23:00:00 +0h>*failure message, but it was <2012-03-10 +1h>."); - } - - [Fact] - public void Should_fail_when_asserting_value_is_exactly_equal_to_a_different_nullable_value() - { - // Arrange - DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); - DateTimeOffset? otherDateTime = dateTime.ToUniversalTime(); - - // Act - Action act = () => dateTime.Should().BeExactly(otherDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dateTime to be exactly <2012-03-09 23:00:00 +0h>*failure message, but it was <2012-03-10 +1h>."); - } - - [Fact] - public void Should_succeed_when_asserting_value_is_not_exactly_equal_to_a_different_value() - { - // Arrange - DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); - DateTimeOffset otherDateTime = dateTime.ToUniversalTime(); - - // Act / Assert - dateTime.Should().NotBeExactly(otherDateTime); - } - - [Fact] - public void Should_succeed_when_asserting_value_is_not_exactly_equal_to_a_different_nullable_value() - { - // Arrange - DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); - DateTimeOffset? otherDateTime = dateTime.ToUniversalTime(); - - // Act / Assert - dateTime.Should().NotBeExactly(otherDateTime); - } - - [Fact] - public void Should_fail_when_asserting_value_is_not_exactly_equal_to_the_same_value() - { - // Arrange - var dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); - var sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); - - // Act - Action act = - () => dateTime.Should().NotBeExactly(sameDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect dateTime to be exactly <2012-03-10 +1h> because we want to test the failure message, but it was."); - } - - [Fact] - public void Should_fail_when_asserting_value_is_not_exactly_equal_to_the_same_nullable_value() - { - // Arrange - DateTimeOffset dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); - DateTimeOffset? sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); - - // Act - Action act = - () => dateTime.Should().NotBeExactly(sameDateTime, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect dateTime to be exactly <2012-03-10 +1h> because we want to test the failure message, but it was."); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_value_is_exactly_equal_to_the_same_nullable_value() - { - // Arrange - DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); - DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 04); - - // Act / Assert - nullableDateTimeA.Should().BeExactly(nullableDateTimeB); - } - - [Fact] - public void Should_succeed_when_asserting_nullable_null_value_exactly_equals_null() - { - // Arrange - DateTimeOffset? nullableDateTimeA = null; - DateTimeOffset? nullableDateTimeB = null; - - // Act / Assert - nullableDateTimeA.Should().BeExactly(nullableDateTimeB); - } - - [Fact] - public void Should_fail_when_asserting_nullable_value_exactly_equals_a_different_value() - { - // Arrange - DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); - DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 06); - - // Act - Action action = () => + { + // Arrange + var specificDate = 1.May(2008).At(6, 32); + + var dateWithZeroHourOffset = new DateTimeOffset(specificDate, TimeSpan.Zero); + var dateWithOneHourOffset = new DateTimeOffset(specificDate, 1.Hours()); + + // Act / Assert + dateWithZeroHourOffset.Should().NotBe(dateWithOneHourOffset); + } + } + + public class BeExactly + { + [Fact] + public void Should_succeed_when_asserting_value_is_exactly_equal_to_the_same_value() + { + // Arrange + DateTimeOffset dateTime = new DateTime(2016, 06, 04); + DateTimeOffset sameDateTime = new DateTime(2016, 06, 04); + + // Act / Assert + dateTime.Should().BeExactly(sameDateTime); + } + + [Fact] + public void Should_succeed_when_asserting_value_is_exactly_equal_to_the_same_nullable_value() + { + // Arrange + DateTimeOffset dateTime = 4.June(2016); + DateTimeOffset? sameDateTime = 4.June(2016); + + // Act / Assert + dateTime.Should().BeExactly(sameDateTime); + } + + [Fact] + public void Should_fail_when_asserting_value_is_exactly_equal_to_a_different_value() + { + // Arrange + var dateTime = 10.March(2012).WithOffset(1.Hours()); + var otherDateTime = dateTime.ToUniversalTime(); + + // Act + Action act = () => dateTime.Should().BeExactly(otherDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dateTime to be exactly <2012-03-09 23:00:00 +0h>*failure message, but it was <2012-03-10 +1h>."); + } + + [Fact] + public void Should_fail_when_asserting_value_is_exactly_equal_to_a_different_nullable_value() + { + // Arrange + DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); + DateTimeOffset? otherDateTime = dateTime.ToUniversalTime(); + + // Act + Action act = () => dateTime.Should().BeExactly(otherDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dateTime to be exactly <2012-03-09 23:00:00 +0h>*failure message, but it was <2012-03-10 +1h>."); + } + + [Fact] + public void Should_succeed_when_asserting_nullable_value_is_exactly_equal_to_the_same_nullable_value() + { + // Arrange + DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); + DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 04); + + // Act / Assert nullableDateTimeA.Should().BeExactly(nullableDateTimeB); + } - // Assert - action.Should().Throw(); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_null_value_is_exactly_equal_to_another_value() - { - // Arrange - DateTimeOffset? nullableDateTime = null; - DateTimeOffset expectation = 27.March(2016).ToDateTimeOffset(1.Hours()); - - // Act - Action action = () => - nullableDateTime.Should().BeExactly(expectation, "because we want to test the failure {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected nullableDateTime to be exactly <2016-03-27 +1h> because we want to test the failure message, but found a DateTimeOffset."); - } - - #endregion - - #region (Not) Be Close To - - [Fact] - public void When_asserting_that_time_is_close_to_a_negative_precision_it_should_throw() - { - // Arrange - var dateTime = DateTimeOffset.UtcNow; - var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, -1.Ticks()); - - // Assert - act.Should().Throw() - .WithMessage("* value of precision must be non-negative*"); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_a_later_datetimeoffset_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTimeOffset.UtcNow; - var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_an_earlier_datetimeoffset_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTimeOffset.UtcNow; - var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_a_MinValue_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTimeOffset.MinValue; - var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_a_MaxValue_by_one_tick_it_should_succeed() - { - // Arrange - var dateTime = DateTimeOffset.MaxValue; - var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_that_time_is_not_close_to_a_negative_precision_it_should_throw() - { - // Arrange - var dateTime = DateTimeOffset.UtcNow; - var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, -1.Ticks()); - - // Assert - act.Should().Throw() - .WithMessage("* value of precision must be non-negative*"); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_a_later_datetimeoffset_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTimeOffset.UtcNow; - var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_an_earlier_datetimeoffset_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTimeOffset.UtcNow; - var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_a_MinValue_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTimeOffset.MinValue; - var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_datetimeoffset_is_close_to_a_MaxValue_by_one_tick_it_should_fail() - { - // Arrange - var dateTime = DateTimeOffset.MaxValue; - var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); - - // Act - Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_a_later_datetimeoffset_it_should_succeed() - { - // Arrange - DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 30, 980, TimeSpan.Zero); - DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_a_later_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 30, 980, TimeSpan.Zero); - DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31 +0h>, but it was <2016-06-04 12:15:30.980 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_a_later_datetimeoffset_by_a_20ms_timespan_it_should_throw() - { - // Arrange - DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 30, 980, TimeSpan.Zero); - DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect time to be within 20ms from <2016-06-04 12:15:31 +0h>, but it was <2016-06-04 12:15:30.980 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_an_earlier_datetimeoffset_it_should_succeed() - { - // Arrange - DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 020, TimeSpan.Zero); - DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_an_earlier_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 020, TimeSpan.Zero); - DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31 +0h>, but it was <2016-06-04 12:15:31.020 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_another_value_that_is_later_by_more_than_20ms_it_should_throw() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 30, 979).ToDateTimeOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + [Fact] + public void Should_succeed_when_asserting_nullable_null_value_exactly_equals_null() + { + // Arrange + DateTimeOffset? nullableDateTimeA = null; + DateTimeOffset? nullableDateTimeB = null; - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected time to be within 20ms from <2012-03-13 12:15:31 +1H>, but it was <2012-03-13 12:15:30.979 +1H>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_another_value_that_is_later_by_more_than_20ms_it_should_succeed() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 30, 979).ToDateTimeOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_throw() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 31, 021).ToDateTimeOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected time to be within 20ms from <2012-03-13 12:15:31 +1h>, but it was <2012-03-13 12:15:31.021 +1h>."); + // Act / Assert + nullableDateTimeA.Should().BeExactly(nullableDateTimeB); + } + + [Fact] + public void Should_fail_when_asserting_nullable_value_exactly_equals_a_different_value() + { + // Arrange + DateTimeOffset? nullableDateTimeA = new DateTime(2016, 06, 04); + DateTimeOffset? nullableDateTimeB = new DateTime(2016, 06, 06); + + // Act + Action action = () => + nullableDateTimeA.Should().BeExactly(nullableDateTimeB); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_null_value_is_exactly_equal_to_another_value() + { + // Arrange + DateTimeOffset? nullableDateTime = null; + DateTimeOffset expectation = 27.March(2016).ToDateTimeOffset(1.Hours()); + + // Act + Action action = () => + nullableDateTime.Should().BeExactly(expectation, "because we want to test the failure {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected nullableDateTime to be exactly <2016-03-27 +1h> because we want to test the failure message, but found a DateTimeOffset."); + } + } + + public class NotBeExactly + { + [Fact] + public void Should_succeed_when_asserting_value_is_not_exactly_equal_to_a_different_value() + { + // Arrange + DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); + DateTimeOffset otherDateTime = dateTime.ToUniversalTime(); + + // Act / Assert + dateTime.Should().NotBeExactly(otherDateTime); + } + + [Fact] + public void Should_succeed_when_asserting_value_is_not_exactly_equal_to_a_different_nullable_value() + { + // Arrange + DateTimeOffset dateTime = 10.March(2012).WithOffset(1.Hours()); + DateTimeOffset? otherDateTime = dateTime.ToUniversalTime(); + + // Act / Assert + dateTime.Should().NotBeExactly(otherDateTime); + } + + [Fact] + public void Should_fail_when_asserting_value_is_not_exactly_equal_to_the_same_value() + { + // Arrange + var dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + var sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + + // Act + Action act = + () => dateTime.Should().NotBeExactly(sameDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect dateTime to be exactly <2012-03-10 +1h> because we want to test the failure message, but it was."); + } + + [Fact] + public void Should_fail_when_asserting_value_is_not_exactly_equal_to_the_same_nullable_value() + { + // Arrange + DateTimeOffset dateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + DateTimeOffset? sameDateTime = new DateTimeOffset(10.March(2012), 1.Hours()); + + // Act + Action act = + () => dateTime.Should().NotBeExactly(sameDateTime, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect dateTime to be exactly <2012-03-10 +1h> because we want to test the failure message, but it was."); + } + } + + public class BeCloseTo + { + [Fact] + public void When_asserting_that_time_is_close_to_a_negative_precision_it_should_throw() + { + // Arrange + var dateTime = DateTimeOffset.UtcNow; + var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, -1.Ticks()); + + // Assert + act.Should().Throw() + .WithMessage("* value of precision must be non-negative*"); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_a_later_datetimeoffset_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTimeOffset.UtcNow; + var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_an_earlier_datetimeoffset_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTimeOffset.UtcNow; + var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_a_MinValue_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTimeOffset.MinValue; + var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_a_MaxValue_by_one_tick_it_should_succeed() + { + // Arrange + var dateTime = DateTimeOffset.MaxValue; + var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().BeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_a_later_datetimeoffset_it_should_succeed() + { + // Arrange + DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 30, 980, TimeSpan.Zero); + DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_an_earlier_datetimeoffset_it_should_succeed() + { + // Arrange + DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 020, TimeSpan.Zero); + DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_another_value_that_is_later_by_more_than_20ms_it_should_throw() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 30, 979).ToDateTimeOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected time to be within 20ms from <2012-03-13 12:15:31 +1H>, but it was <2012-03-13 12:15:30.979 +1H>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_throw() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 31, 021).ToDateTimeOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected time to be within 20ms from <2012-03-13 12:15:31 +1h>, but it was <2012-03-13 12:15:31.021 +1h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_another_value_that_is_earlier_by_more_than_a_35ms_timespan_it_should_throw() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 31, 036).WithOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).WithOffset(1.Hours()); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(35)); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected time to be within 35ms from <2012-03-13 12:15:31 +1h>, but it was <2012-03-13 12:15:31.036 +1h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_an_earlier_datetimeoffset_by_35ms_it_should_succeed() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 31, 035).ToDateTimeOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_is_close_to_another_it_should_throw() + { + // Arrange + DateTimeOffset? time = null; + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(5.Hours()); + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Expected*, but it was ."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_the_maximum_datetimeoffset_it_should_succeed() + { + // Arrange + DateTimeOffset time = DateTimeOffset.MaxValue - 50.Milliseconds(); + DateTimeOffset nearbyTime = DateTimeOffset.MaxValue; + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_close_to_the_minimum_datetimeoffset_it_should_succeed() + { + // Arrange + DateTimeOffset time = DateTimeOffset.MinValue + 50.Milliseconds(); + DateTimeOffset nearbyTime = DateTimeOffset.MinValue; + + // Act + Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + } + + public class NotBeCloseTo + { + [Fact] + public void When_asserting_that_time_is_not_close_to_a_negative_precision_it_should_throw() + { + // Arrange + var dateTime = DateTimeOffset.UtcNow; + var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, -1.Ticks()); + + // Assert + act.Should().Throw() + .WithMessage("* value of precision must be non-negative*"); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_a_later_datetimeoffset_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTimeOffset.UtcNow; + var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_an_earlier_datetimeoffset_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTimeOffset.UtcNow; + var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_a_MinValue_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTimeOffset.MinValue; + var actual = new DateTimeOffset(dateTime.Ticks + 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_datetimeoffset_is_close_to_a_MaxValue_by_one_tick_it_should_fail() + { + // Arrange + var dateTime = DateTimeOffset.MaxValue; + var actual = new DateTimeOffset(dateTime.Ticks - 1, TimeSpan.Zero); + + // Act + Action act = () => actual.Should().NotBeCloseTo(dateTime, TimeSpan.FromTicks(1)); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_a_later_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 30, 980, TimeSpan.Zero); + DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31 +0h>, but it was <2016-06-04 12:15:30.980 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_a_later_datetimeoffset_by_a_20ms_timespan_it_should_throw() + { + // Arrange + DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 30, 980, TimeSpan.Zero); + DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect time to be within 20ms from <2016-06-04 12:15:31 +0h>, but it was <2016-06-04 12:15:30.980 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_an_earlier_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset time = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 020, TimeSpan.Zero); + DateTimeOffset nearbyTime = new DateTimeOffset(2016, 06, 04, 12, 15, 31, 0, TimeSpan.Zero); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 20ms from <2016-06-04 12:15:31 +0h>, but it was <2016-06-04 12:15:31.020 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_another_value_that_is_later_by_more_than_20ms_it_should_succeed() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 30, 979).ToDateTimeOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_succeed() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 31, 021).ToDateTimeOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_an_earlier_datetimeoffset_by_35ms_it_should_throw() + { + // Arrange + DateTimeOffset time = 13.March(2012).At(12, 15, 31, 035).ToDateTimeOffset(1.Hours()); + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 35ms from <2012-03-13 12:15:31 +1h>, but it was <2012-03-13 12:15:31.035 +1h>."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_is_not_close_to_another_it_should_throw() + { + // Arrange + DateTimeOffset? time = null; + DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(5.Hours()); + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect*, but it was ."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_the_minimum_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset time = DateTimeOffset.MinValue + 50.Milliseconds(); + DateTimeOffset nearbyTime = DateTimeOffset.MinValue; + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 100ms from <0001-01-01 00:00:00.000>, but it was <00:00:00.050 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_close_to_the_maximum_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset time = DateTimeOffset.MaxValue - 50.Milliseconds(); + DateTimeOffset nearbyTime = DateTimeOffset.MaxValue; + + // Act + Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect time to be within 100ms from <9999-12-31 23:59:59.9999999 +0h>, but it was <9999-12-31 23:59:59.9499999 +0h>."); + } + } + + public class BeBefore + { + [Fact] + public void When_asserting_a_point_of_time_is_before_a_later_point_it_should_succeed() + { + // Arrange + DateTimeOffset earlierDate = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset laterDate = new DateTimeOffset(new DateTime(2016, 06, 04, 0, 5, 0), TimeSpan.Zero); + + // Act + Action act = () => earlierDate.Should().BeBefore(laterDate); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_is_before_earlier_expected_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeBefore(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_before_the_same_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeBefore(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); + } + } + + public class NotBeBefore + { + [Fact] + public void When_asserting_a_point_of_time_is_not_before_another_it_should_throw() + { + // Arrange + DateTimeOffset earlierDate = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset laterDate = new DateTimeOffset(new DateTime(2016, 06, 04, 0, 5, 0), TimeSpan.Zero); + + // Act + Action act = () => earlierDate.Should().NotBeBefore(laterDate); + + // Assert + act.Should().Throw().WithMessage( + "Expected earlierDate to be on or after <2016-06-04 00:05:00 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_is_not_before_earlier_expected_datetimeoffset_it_should_succeed() + { + // Arrange + DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeBefore(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_before_the_same_datetimeoffset_it_should_succeed() + { + // Arrange + DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeBefore(expected); + + // Assert + act.Should().NotThrow(); + } + } + + public class BeOnOrBefore + { + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_before_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeOnOrBefore(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_before_the_same_date_as_the_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeOnOrBefore(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_on_or_before_earlier_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeOnOrBefore(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be on or before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); + } + } + + public class NotBeOnOrBefore + { + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_before_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeOnOrBefore(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be after <2016-06-05 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_before_the_same_date_as_the_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeOnOrBefore(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be after <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_on_or_before_earlier_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeOnOrBefore(expectation); + + // Assert + act.Should().NotThrow(); + } + } + + public class BeAfter + { + [Fact] + public void When_asserting_subject_datetimeoffset_is_after_earlier_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_after_later_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeAfter(expectation); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject to be after <2016-06-05 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_after_the_same_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeAfter(expectation); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject to be after <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); + } + } + + public class NotBeAfter + { + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_after_earlier_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeAfter(expectation); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject to be on or before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_after_later_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_after_the_same_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + } + + public class BeOnOrAfter + { + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_after_earlier_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeOnOrAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_after_the_same_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeOnOrAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_on_or_after_later_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeOnOrAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be on or after <2016-06-05 +0h>, but it was <2016-06-04 +0h>."); + } + } + + public class NotBeOnOrAfter + { + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_on_or_after_earlier_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeOnOrAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_on_or_after_the_same_expected_datetimeoffset_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeOnOrAfter(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to be before <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_is_not_on_or_after_later_expected_datetimeoffset_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeOnOrAfter(expectation); + + // Assert + act.Should().NotThrow(); + } + } + + public class HaveYear + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_year_with_the_same_value_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); + int expectation = 2009; + + // Act + Action act = () => subject.Should().HaveYear(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_year_with_a_different_value_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); + int expectation = 2008; + + // Act + Action act = () => subject.Should().HaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the year part of subject to be 2008, but it was 2009."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_year_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 2008; + + // Act + Action act = () => subject.Should().HaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the year part of subject to be 2008, but found a DateTimeOffset."); + } + } + + public class NotHaveYear + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_year_with_the_same_value_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); + int expectation = 2009; + + // Act + Action act = () => subject.Should().NotHaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the year part of subject to be 2009, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_year_with_a_different_value_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); + int expectation = 2008; + + // Act + Action act = () => subject.Should().NotHaveYear(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_year_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 2008; + + // Act + Action act = () => subject.Should().NotHaveYear(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the year part of subject to be 2008, but found a DateTimeOffset."); + } + } + + public class HaveMonth + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_month_with_the_same_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 12; + + // Act + Action act = () => subject.Should().HaveMonth(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_a_month_with_a_different_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 11; + + // Act + Action act = () => subject.Should().HaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the month part of subject to be 11, but it was 12."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_month_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 12; + + // Act + Action act = () => subject.Should().HaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the month part of subject to be 12, but found a DateTimeOffset."); + } + } + + public class NotHaveMonth + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_month_with_the_same_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 12; + + // Act + Action act = () => subject.Should().NotHaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the month part of subject to be 12, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_a_month_with_a_different_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 11; + + // Act + Action act = () => subject.Should().NotHaveMonth(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_month_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 12; + + // Act + Action act = () => subject.Should().NotHaveMonth(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the month part of subject to be 12, but found a DateTimeOffset."); + } + } + + public class HaveDay + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_day_with_the_same_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 31; + + // Act + Action act = () => subject.Should().HaveDay(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_day_with_a_different_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 30; + + // Act + Action act = () => subject.Should().HaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the day part of subject to be 30, but it was 31."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_day_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the day part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class NotHaveDay + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_day_with_the_same_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 31; + + // Act + Action act = () => subject.Should().NotHaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the day part of subject to be 31, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_day_with_a_different_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + int expectation = 30; + + // Act + Action act = () => subject.Should().NotHaveDay(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_day_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveDay(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the day part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class HaveHour + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_hour_with_the_same_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 23; + + // Act + Action act = () => subject.Should().HaveHour(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_hour_with_different_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the hour part of subject to be 22, but it was 23."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_hour_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the hour part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class NotHaveHour + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_hour_with_the_same_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 23; + + // Act + Action act = () => subject.Should().NotHaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the hour part of subject to be 23, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_hour_with_different_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveHour(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_hour_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveHour(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the hour part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class HaveMinute + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_minutes_with_the_same_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 59; + + // Act + Action act = () => subject.Should().HaveMinute(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_minutes_with_different_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 58; + + // Act + Action act = () => subject.Should().HaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the minute part of subject to be 58, but it was 59."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_minute_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the minute part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class NotHaveMinute + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_minutes_with_the_same_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 59; + + // Act + Action act = () => subject.Should().NotHaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the minute part of subject to be 59, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_minutes_with_different_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 58; + + // Act + Action act = () => subject.Should().NotHaveMinute(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_minute_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveMinute(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the minute part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class HaveSecond + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_seconds_with_the_same_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 0; + + // Act + Action act = () => subject.Should().HaveSecond(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_seconds_with_different_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 1; + + // Act + Action act = () => subject.Should().HaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the seconds part of subject to be 1, but it was 0."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_second_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().HaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the seconds part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class NotHaveSecond + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_seconds_with_the_same_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 0; + + // Act + Action act = () => subject.Should().NotHaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the seconds part of subject to be 0, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_seconds_with_different_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + int expectation = 1; + + // Act + Action act = () => subject.Should().NotHaveSecond(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_second_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + int expectation = 22; + + // Act + Action act = () => subject.Should().NotHaveSecond(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the seconds part of subject to be 22, but found a DateTimeOffset."); + } + } + + public class HaveOffset + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_offset_with_the_same_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.FromHours(7)); + TimeSpan expectation = TimeSpan.FromHours(7); + + // Act + Action act = () => subject.Should().HaveOffset(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_offset_with_different_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 10), TimeSpan.Zero); + TimeSpan expectation = TimeSpan.FromHours(3); + + // Act + Action act = () => subject.Should().HaveOffset(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the offset of subject to be 3h, but it was default."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_have_offset_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + TimeSpan expectation = TimeSpan.FromHours(3); + + // Act + Action act = () => subject.Should().HaveOffset(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Expected the offset of subject to be 3h, but found a DateTimeOffset."); + } + } + + public class NotHaveOffset + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_offset_with_the_same_value_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.FromHours(7)); + TimeSpan expectation = TimeSpan.FromHours(7); + + // Act + Action act = () => subject.Should().NotHaveOffset(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the offset of subject to be 7h, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_offset_with_different_value_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); + TimeSpan expectation = TimeSpan.FromHours(3); + + // Act + Action act = () => subject.Should().NotHaveOffset(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_should_not_have_offset_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + TimeSpan expectation = TimeSpan.FromHours(3); + + // Act + Action act = () => subject.Should().NotHaveOffset(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the offset of subject to be 3h, but found a DateTimeOffset."); + } + } + + public class BeSameDateAs + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_be_same_date_as_another_with_the_same_date_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeSameDateAs(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_be_same_as_another_with_same_date_but_different_time_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31, 11, 15, 11), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeSameDateAs(expectation); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_to_be_same_date_as_another_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeSameDateAs(expectation); + + // Assert + act.Should().Throw().WithMessage( + "Expected the date part of subject to be <2009-12-31>, but found a DateTimeOffset."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_have_same_date_as_another_but_it_doesnt_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 30), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().BeSameDateAs(expectation); + + // Assert + act.Should().Throw().WithMessage( + "Expected the date part of subject to be <2009-12-30>, but it was <2009-12-31>."); + } + } + + public class NotBeSameDateAs + { + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_be_same_date_as_another_with_the_same_date_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_be_same_as_another_with_same_date_but_different_time_it_should_throw() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31, 11, 15, 11), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(expectation); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); + } + + [Fact] + public void When_asserting_subject_null_datetimeoffset_to_not_be_same_date_as_another_datetimeoffset_it_should_throw() + { + // Arrange + DateTimeOffset? subject = null; + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(expectation); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect the date part of subject to be <2009-12-31>, but found a DateTimeOffset."); + } + + [Fact] + public void When_asserting_subject_datetimeoffset_should_not_have_same_date_as_another_but_it_doesnt_it_should_succeed() + { + // Arrange + DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); + DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 30), TimeSpan.Zero); + + // Act + Action act = () => subject.Should().NotBeSameDateAs(expectation); + + // Assert + act.Should().NotThrow(); + } + } + + public class TimespanComparison + { + [Fact] + public void When_date_is_not_more_than_the_required_one_day_before_another_it_should_throw() + { + // Arrange + var target = new DateTimeOffset(2.October(2009), 0.Hours()); + DateTimeOffset subject = target - 1.Days(); + + // Act + Action act = () => subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <2009-10-01 +0h> to be more than 1d before <2009-10-02 +0h> because we like that, but it is behind by 1d."); + } + + [Fact] + public void When_date_is_more_than_the_required_one_day_before_another_it_should_not_throw() + { + // Arrange + var target = new DateTimeOffset(2.October(2009)); + DateTimeOffset subject = target - 25.Hours(); + + // Act / Assert + subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target); + } + + [Fact] + public void When_date_is_not_at_least_one_day_before_another_it_should_throw() + { + // Arrange + var target = new DateTimeOffset(2.October(2009), 0.Hours()); + DateTimeOffset subject = target - 23.Hours(); + + // Act + Action act = () => subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <2009-10-01 01:00:00 +0h> to be at least 1d before <2009-10-02 +0h> because we like that, but it is behind by 23h."); + } + + [Fact] + public void When_date_is_at_least_one_day_before_another_it_should_not_throw() + { + // Arrange + var target = new DateTimeOffset(2.October(2009)); + DateTimeOffset subject = target - 24.Hours(); + + // Act / Assert + subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target); + } + + [Fact] + public void When_time_is_not_at_exactly_20_minutes_before_another_time_it_should_throw() + { + // Arrange + DateTimeOffset target = 1.January(0001).At(12, 55).ToDateTimeOffset(); + DateTimeOffset subject = 1.January(0001).At(12, 36).ToDateTimeOffset(); + + // Act + Action act = + () => subject.Should().BeExactly(TimeSpan.FromMinutes(20)).Before(target, "{0} minutes is enough", 20); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <12:36:00 +0h> to be exactly 20m before <12:55:00 +0h> because 20 minutes is enough, but it is behind by 19m."); + } + + [Fact] + public void When_time_is_exactly_90_seconds_before_another_time_it_should_not_throw() + { + // Arrange + DateTimeOffset target = 1.January(0001).At(12, 55).ToDateTimeOffset(); + DateTimeOffset subject = 1.January(0001).At(12, 53, 30).ToDateTimeOffset(); + + // Act / Assert + subject.Should().BeExactly(TimeSpan.FromSeconds(90)).Before(target); + } + + [Fact] + public void When_date_is_not_within_50_hours_before_another_date_it_should_throw() + { + // Arrange + var target = 10.April(2010).At(12, 0).WithOffset(0.Hours()); + DateTimeOffset subject = target - 50.Hours() - 1.Seconds(); + + // Act + Action act = + () => subject.Should().BeWithin(TimeSpan.FromHours(50)).Before(target, "{0} hours is enough", 50); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <2010-04-08 09:59:59 +0h> to be within 2d and 2h before <2010-04-10 12:00:00 +0h> because 50 hours is enough, but it is behind by 2d, 2h and 1s."); + } + + [Fact] + public void When_date_is_exactly_within_1d_before_another_date_it_should_not_throw() + { + // Arrange + var target = new DateTimeOffset(10.April(2010)); + DateTimeOffset subject = target - 1.Days(); + + // Act / Assert + subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); + } + + [Fact] + public void When_date_is_within_1d_before_another_date_it_should_not_throw() + { + // Arrange + var target = new DateTimeOffset(10.April(2010)); + DateTimeOffset subject = target - 23.Hours(); + + // Act / Assert + subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); + } + + [Fact] + public void When_a_utc_date_is_within_0s_before_itself_it_should_not_throw() + { + // Arrange + var date = DateTimeOffset.UtcNow; // local timezone differs from +0h + + // Act / Assert + date.Should().BeWithin(TimeSpan.Zero).Before(date); + } + + [Fact] + public void When_a_utc_date_is_within_0s_after_itself_it_should_not_throw() + { + // Arrange + var date = DateTimeOffset.UtcNow; // local timezone differs from +0h + + // Act / Assert + date.Should().BeWithin(TimeSpan.Zero).After(date); + } + + [Fact] + public void When_time_is_not_less_than_30s_after_another_time_it_should_throw() + { + // Arrange + var target = 1.January(1).At(12, 0, 30).WithOffset(1.Hours()); + DateTimeOffset subject = target + 30.Seconds(); + + // Act + Action act = + () => subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target, "{0}s is the max", 30); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject <12:01:00 +1h> to be less than 30s after <12:00:30 +1h> because 30s is the max, but it is ahead by 30s."); + } + + [Fact] + public void When_time_is_less_than_30s_after_another_time_it_should_not_throw() + { + // Arrange + var target = new DateTimeOffset(1.January(1).At(12, 0, 30)); + DateTimeOffset subject = target + 20.Seconds(); + + // Act / Assert + subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target); + } + + [Fact] + public void When_asserting_subject_be_more_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, 15).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeMoreThan(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:15 +0h> to be more than 10s after <00:00:30 +0h>, but it is behind by 15s."); + } + + [Theory] + [InlineData(30, 20)] // edge case + [InlineData(30, 15)] + public void When_asserting_subject_be_at_least_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeAtLeast(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be at least 10s after <00:00:30 +0h>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_exactly_10_seconds_after_target_but_subject_is_before_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, 20).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeExactly(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:20 +0h> to be exactly 10s after <00:00:30 +0h>, but it is behind by 10s."); + } + + [Theory] + [InlineData(30, 20)] // edge case + [InlineData(30, 25)] + public void When_asserting_subject_be_within_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeWithin(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be within 10s after <00:00:30 +0h>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_less_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, 25).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeLessThan(10.Seconds()).After(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:25 +0h> to be less than 10s after <00:00:30 +0h>, but it is behind by 5s."); + } + + [Fact] + public void When_asserting_subject_be_more_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, 45).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeMoreThan(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:45 +0h> to be more than 10s before <00:00:30 +0h>, but it is ahead by 15s."); + } + + [Theory] + [InlineData(30, 40)] // edge case + [InlineData(30, 45)] + public void When_asserting_subject_be_at_least_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeAtLeast(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be at least 10s before <00:00:30 +0h>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_exactly_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, 40).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeExactly(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:40 +0h> to be exactly 10s before <00:00:30 +0h>, but it is ahead by 10s."); + } + + [Theory] + [InlineData(30, 40)] // edge case + [InlineData(30, 35)] + public void When_asserting_subject_be_within_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) + { + // Arrange + var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeWithin(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be within 10s before <00:00:30 +0h>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); + } + + [Fact] + public void When_asserting_subject_be_less_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() + { + // Arrange + var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); + var subject = 1.January(0001).At(0, 0, 45).WithOffset(0.Hours()); + + // Act + Action action = () => subject.Should().BeLessThan(10.Seconds()).Before(expectation); + + // Assert + action.Should().Throw() + .WithMessage("Expected subject <00:00:45 +0h> to be less than 10s before <00:00:30 +0h>, but it is ahead by 15s."); + } + } + + public class ChainingConstraint + { + [Fact] + public void Should_support_chaining_constraints_with_and() + { + // Arrange + DateTimeOffset yesterday = new DateTime(2016, 06, 03); + DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); + + // Act + Action action = () => + nullableDateTime.Should() + .HaveValue() + .And + .BeAfter(yesterday); + + // Assert + action.Should().NotThrow(); + } + } + + public class BeOneOf + { + [Fact] + public void When_a_value_is_not_one_of_the_specified_values_it_should_throw() + { + // Arrange + var value = new DateTimeOffset(31.December(2016), 1.Hours()); + + // Act + Action action = () => value.Should().BeOneOf(value + 1.Days(), value + 4.Hours()); + + // Assert + action.Should().Throw().WithMessage( + "Expected value to be one of {<2017-01-01 +1h>, <2016-12-31 04:00:00 +1h>}, but it was <2016-12-31 +1h>."); + } + + [Fact] + public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() + { + // Arrange + DateTimeOffset value = 31.December(2016).WithOffset(1.Hours()); + + // Act + Action action = () => value.Should().BeOneOf(new[] { value + 1.Days(), value + 2.Days() }, "because it's true"); + + // Assert + action.Should().Throw().WithMessage( + "Expected value to be one of {<2017-01-01 +1h>, <2017-01-02 +1h>} because it's true, but it was <2016-12-31 +1h>."); + } + + [Fact] + public void When_a_value_is_one_of_the_specified_values_it_should_succeed() + { + // Arrange + DateTimeOffset value = new DateTimeOffset(2016, 12, 30, 23, 58, 57, TimeSpan.FromHours(4)); + + // Act + Action action = () => value.Should().BeOneOf(new DateTimeOffset(2216, 1, 30, 0, 5, 7, TimeSpan.FromHours(2)), new DateTimeOffset(2016, 12, 30, 23, 58, 57, TimeSpan.FromHours(4))); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_a_null_value_is_not_one_of_the_specified_values_it_should_throw() + { + // Arrange + DateTimeOffset? value = null; + + // Act + Action action = () => value.Should().BeOneOf(new DateTimeOffset(2216, 1, 30, 0, 5, 7, TimeSpan.FromHours(1)), new DateTimeOffset(2016, 2, 10, 2, 45, 7, TimeSpan.FromHours(2))); + + // Assert + action.Should().Throw().WithMessage( + "Expected value to be one of {<2216-01-30 00:05:07 +1h>, <2016-02-10 02:45:07 +2h>}, but it was ."); + } + + [Fact] + public void When_a_value_is_one_of_the_specified_values_it_should_succeed_when_datetimeoffset_is_null() + { + // Arrange + DateTimeOffset? value = null; + + // Act + Action action = () => value.Should().BeOneOf(new DateTimeOffset(2216, 1, 30, 0, 5, 7, TimeSpan.Zero), null); + + // Assert + action.Should().NotThrow(); + } } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_another_value_that_is_earlier_by_more_than_a_35ms_timespan_it_should_throw() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 31, 036).WithOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).WithOffset(1.Hours()); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(35)); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected time to be within 35ms from <2012-03-13 12:15:31 +1h>, but it was <2012-03-13 12:15:31.036 +1h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_succeed() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 31, 021).ToDateTimeOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_an_earlier_datetimeoffset_by_35ms_it_should_succeed() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 31, 035).ToDateTimeOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_an_earlier_datetimeoffset_by_35ms_it_should_throw() - { - // Arrange - DateTimeOffset time = 13.March(2012).At(12, 15, 31, 035).ToDateTimeOffset(1.Hours()); - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(1.Hours()); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 35ms from <2012-03-13 12:15:31 +1h>, but it was <2012-03-13 12:15:31.035 +1h>."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_is_close_to_another_it_should_throw() - { - // Arrange - DateTimeOffset? time = null; - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(5.Hours()); - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Expected*, but it was ."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_is_not_close_to_another_it_should_throw() - { - // Arrange - DateTimeOffset? time = null; - DateTimeOffset nearbyTime = 13.March(2012).At(12, 15, 31).ToDateTimeOffset(5.Hours()); - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect*, but it was ."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_the_minimum_datetimeoffset_it_should_succeed() - { - // Arrange - DateTimeOffset time = DateTimeOffset.MinValue + 50.Milliseconds(); - DateTimeOffset nearbyTime = DateTimeOffset.MinValue; - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_the_minimum_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset time = DateTimeOffset.MinValue + 50.Milliseconds(); - DateTimeOffset nearbyTime = DateTimeOffset.MinValue; - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 100ms from <0001-01-01 00:00:00.000>, but it was <00:00:00.050 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_close_to_the_maximum_datetimeoffset_it_should_succeed() - { - // Arrange - DateTimeOffset time = DateTimeOffset.MaxValue - 50.Milliseconds(); - DateTimeOffset nearbyTime = DateTimeOffset.MaxValue; - - // Act - Action act = () => time.Should().BeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_close_to_the_maximum_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset time = DateTimeOffset.MaxValue - 50.Milliseconds(); - DateTimeOffset nearbyTime = DateTimeOffset.MaxValue; - - // Act - Action act = () => time.Should().NotBeCloseTo(nearbyTime, 100.Milliseconds()); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect time to be within 100ms from <9999-12-31 23:59:59.9999999 +0h>, but it was <9999-12-31 23:59:59.9499999 +0h>."); - } - #endregion - - #region (Not) Be Before - [Fact] - public void When_asserting_a_point_of_time_is_before_a_later_point_it_should_succeed() - { - // Arrange - DateTimeOffset earlierDate = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset laterDate = new DateTimeOffset(new DateTime(2016, 06, 04, 0, 5, 0), TimeSpan.Zero); - - // Act - Action act = () => earlierDate.Should().BeBefore(laterDate); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_point_of_time_is_not_before_another_it_should_throw() - { - // Arrange - DateTimeOffset earlierDate = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset laterDate = new DateTimeOffset(new DateTime(2016, 06, 04, 0, 5, 0), TimeSpan.Zero); - - // Act - Action act = () => earlierDate.Should().NotBeBefore(laterDate); - - // Assert - act.Should().Throw().WithMessage( - "Expected earlierDate to be on or after <2016-06-04 00:05:00 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_is_before_earlier_expected_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeBefore(expected); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_is_not_before_earlier_expected_datetimeoffset_it_should_succeed() - { - // Arrange - DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeBefore(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_before_the_same_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeBefore(expected); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_before_the_same_datetimeoffset_it_should_succeed() - { - // Arrange - DateTimeOffset expected = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeBefore(expected); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Be On Or Before - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_before_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeOnOrBefore(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_before_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeOnOrBefore(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be after <2016-06-05 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_before_the_same_date_as_the_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeOnOrBefore(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_before_the_same_date_as_the_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeOnOrBefore(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be after <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_on_or_before_earlier_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeOnOrBefore(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be on or before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_on_or_before_earlier_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeOnOrBefore(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Be After - [Fact] - public void When_asserting_subject_datetimeoffset_is_after_earlier_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_after_earlier_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeAfter(expectation); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject to be on or before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_after_later_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeAfter(expectation); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject to be after <2016-06-05 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_after_later_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_after_the_same_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeAfter(expectation); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject to be after <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_after_the_same_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Be On Or After - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_after_earlier_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeOnOrAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_on_or_after_earlier_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 03), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeOnOrAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-03 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_after_the_same_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeOnOrAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_on_or_after_the_same_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeOnOrAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be before <2016-06-04 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_on_or_after_later_expected_datetimeoffset_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeOnOrAfter(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to be on or after <2016-06-05 +0h>, but it was <2016-06-04 +0h>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_is_not_on_or_after_later_expected_datetimeoffset_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2016, 06, 04), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2016, 06, 05), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeOnOrAfter(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region (Not) Have Year - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_year_with_the_same_value_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); - int expectation = 2009; - - // Act - Action act = () => subject.Should().HaveYear(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_year_with_the_same_value_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); - int expectation = 2009; - - // Act - Action act = () => subject.Should().NotHaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the year part of subject to be 2009, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_year_with_a_different_value_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); - int expectation = 2008; - - // Act - Action act = () => subject.Should().HaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the year part of subject to be 2008, but it was 2009."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_year_with_a_different_value_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 06, 04), TimeSpan.Zero); - int expectation = 2008; - - // Act - Action act = () => subject.Should().NotHaveYear(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_year_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 2008; - - // Act - Action act = () => subject.Should().HaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the year part of subject to be 2008, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_year_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 2008; - - // Act - Action act = () => subject.Should().NotHaveYear(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the year part of subject to be 2008, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Have Month - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_month_with_the_same_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 12; - - // Act - Action act = () => subject.Should().HaveMonth(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_month_with_the_same_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 12; - - // Act - Action act = () => subject.Should().NotHaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the month part of subject to be 12, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_a_month_with_a_different_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 11; - - // Act - Action act = () => subject.Should().HaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the month part of subject to be 11, but it was 12."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_a_month_with_a_different_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 11; - - // Act - Action act = () => subject.Should().NotHaveMonth(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_month_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 12; - - // Act - Action act = () => subject.Should().HaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the month part of subject to be 12, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_month_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 12; - - // Act - Action act = () => subject.Should().NotHaveMonth(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the month part of subject to be 12, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Have Day - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_day_with_the_same_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 31; - - // Act - Action act = () => subject.Should().HaveDay(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_day_with_the_same_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 31; - - // Act - Action act = () => subject.Should().NotHaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the day part of subject to be 31, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_day_with_a_different_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 30; - - // Act - Action act = () => subject.Should().HaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the day part of subject to be 30, but it was 31."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_day_with_a_different_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - int expectation = 30; - - // Act - Action act = () => subject.Should().NotHaveDay(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_day_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the day part of subject to be 22, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_day_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveDay(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the day part of subject to be 22, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Have Hour - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_hour_with_the_same_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 23; - - // Act - Action act = () => subject.Should().HaveHour(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_hour_with_the_same_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 23; - - // Act - Action act = () => subject.Should().NotHaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the hour part of subject to be 23, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_hour_with_different_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the hour part of subject to be 22, but it was 23."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_hour_with_different_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveHour(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_hour_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the hour part of subject to be 22, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_hour_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveHour(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the hour part of subject to be 22, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Have Minute - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_minutes_with_the_same_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 59; - - // Act - Action act = () => subject.Should().HaveMinute(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_minutes_with_the_same_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 59; - - // Act - Action act = () => subject.Should().NotHaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the minute part of subject to be 59, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_minutes_with_different_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 58; - - // Act - Action act = () => subject.Should().HaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the minute part of subject to be 58, but it was 59."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_minutes_with_different_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 58; - - // Act - Action act = () => subject.Should().NotHaveMinute(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_minute_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the minute part of subject to be 22, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_minute_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveMinute(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the minute part of subject to be 22, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Have Second - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_seconds_with_the_same_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 0; - - // Act - Action act = () => subject.Should().HaveSecond(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_seconds_with_the_same_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 0; - - // Act - Action act = () => subject.Should().NotHaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the seconds part of subject to be 0, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_seconds_with_different_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 1; - - // Act - Action act = () => subject.Should().HaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the seconds part of subject to be 1, but it was 0."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_seconds_with_different_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - int expectation = 1; - - // Act - Action act = () => subject.Should().NotHaveSecond(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_second_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().HaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the seconds part of subject to be 22, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_second_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - int expectation = 22; - - // Act - Action act = () => subject.Should().NotHaveSecond(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the seconds part of subject to be 22, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Have Offset - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_offset_with_the_same_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.FromHours(7)); - TimeSpan expectation = TimeSpan.FromHours(7); - - // Act - Action act = () => subject.Should().HaveOffset(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_offset_with_the_same_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.FromHours(7)); - TimeSpan expectation = TimeSpan.FromHours(7); - - // Act - Action act = () => subject.Should().NotHaveOffset(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the offset of subject to be 7h, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_offset_with_different_value_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 10), TimeSpan.Zero); - TimeSpan expectation = TimeSpan.FromHours(3); - - // Act - Action act = () => subject.Should().HaveOffset(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the offset of subject to be 3h, but it was default."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_offset_with_different_value_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 23, 59, 00), TimeSpan.Zero); - TimeSpan expectation = TimeSpan.FromHours(3); - - // Act - Action act = () => subject.Should().NotHaveOffset(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_have_offset_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - TimeSpan expectation = TimeSpan.FromHours(3); - - // Act - Action act = () => subject.Should().HaveOffset(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Expected the offset of subject to be 3h, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_should_not_have_offset_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - TimeSpan expectation = TimeSpan.FromHours(3); - - // Act - Action act = () => subject.Should().NotHaveOffset(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the offset of subject to be 3h, but found a DateTimeOffset."); - } - #endregion - - #region (Not) Be Same Date As - [Fact] - public void When_asserting_subject_datetimeoffset_should_be_same_date_as_another_with_the_same_date_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeSameDateAs(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_be_same_date_as_another_with_the_same_date_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_be_same_as_another_with_same_date_but_different_time_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31, 11, 15, 11), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeSameDateAs(expectation); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_be_same_as_another_with_same_date_but_different_time_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31, 4, 5, 6), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31, 11, 15, 11), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(expectation); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect the date part of subject to be <2009-12-31>, but it was."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_to_be_same_date_as_another_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeSameDateAs(expectation); - - // Assert - act.Should().Throw().WithMessage( - "Expected the date part of subject to be <2009-12-31>, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_null_datetimeoffset_to_not_be_same_date_as_another_datetimeoffset_it_should_throw() - { - // Arrange - DateTimeOffset? subject = null; - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(expectation); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect the date part of subject to be <2009-12-31>, but found a DateTimeOffset."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_have_same_date_as_another_but_it_doesnt_it_should_throw() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 30), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().BeSameDateAs(expectation); - - // Assert - act.Should().Throw().WithMessage( - "Expected the date part of subject to be <2009-12-30>, but it was <2009-12-31>."); - } - - [Fact] - public void When_asserting_subject_datetimeoffset_should_not_have_same_date_as_another_but_it_doesnt_it_should_succeed() - { - // Arrange - DateTimeOffset subject = new DateTimeOffset(new DateTime(2009, 12, 31), TimeSpan.Zero); - DateTimeOffset expectation = new DateTimeOffset(new DateTime(2009, 12, 30), TimeSpan.Zero); - - // Act - Action act = () => subject.Should().NotBeSameDateAs(expectation); - - // Assert - act.Should().NotThrow(); - } - #endregion - - #region Timespan Comparison - [Fact] - public void When_date_is_not_more_than_the_required_one_day_before_another_it_should_throw() - { - // Arrange - var target = new DateTimeOffset(2.October(2009), 0.Hours()); - DateTimeOffset subject = target - 1.Days(); - - // Act - Action act = () => subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <2009-10-01 +0h> to be more than 1d before <2009-10-02 +0h> because we like that, but it is behind by 1d."); - } - - [Fact] - public void When_date_is_more_than_the_required_one_day_before_another_it_should_not_throw() - { - // Arrange - var target = new DateTimeOffset(2.October(2009)); - DateTimeOffset subject = target - 25.Hours(); - - // Act / Assert - subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target); - } - - [Fact] - public void When_date_is_not_at_least_one_day_before_another_it_should_throw() - { - // Arrange - var target = new DateTimeOffset(2.October(2009), 0.Hours()); - DateTimeOffset subject = target - 23.Hours(); - - // Act - Action act = () => subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that"); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <2009-10-01 01:00:00 +0h> to be at least 1d before <2009-10-02 +0h> because we like that, but it is behind by 23h."); - } - - [Fact] - public void When_date_is_at_least_one_day_before_another_it_should_not_throw() - { - // Arrange - var target = new DateTimeOffset(2.October(2009)); - DateTimeOffset subject = target - 24.Hours(); - - // Act / Assert - subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target); - } - - [Fact] - public void When_time_is_not_at_exactly_20_minutes_before_another_time_it_should_throw() - { - // Arrange - DateTimeOffset target = 1.January(0001).At(12, 55).ToDateTimeOffset(); - DateTimeOffset subject = 1.January(0001).At(12, 36).ToDateTimeOffset(); - - // Act - Action act = - () => subject.Should().BeExactly(TimeSpan.FromMinutes(20)).Before(target, "{0} minutes is enough", 20); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <12:36:00 +0h> to be exactly 20m before <12:55:00 +0h> because 20 minutes is enough, but it is behind by 19m."); - } - - [Fact] - public void When_time_is_exactly_90_seconds_before_another_time_it_should_not_throw() - { - // Arrange - DateTimeOffset target = 1.January(0001).At(12, 55).ToDateTimeOffset(); - DateTimeOffset subject = 1.January(0001).At(12, 53, 30).ToDateTimeOffset(); - - // Act / Assert - subject.Should().BeExactly(TimeSpan.FromSeconds(90)).Before(target); - } - - [Fact] - public void When_date_is_not_within_50_hours_before_another_date_it_should_throw() - { - // Arrange - var target = 10.April(2010).At(12, 0).WithOffset(0.Hours()); - DateTimeOffset subject = target - 50.Hours() - 1.Seconds(); - - // Act - Action act = - () => subject.Should().BeWithin(TimeSpan.FromHours(50)).Before(target, "{0} hours is enough", 50); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <2010-04-08 09:59:59 +0h> to be within 2d and 2h before <2010-04-10 12:00:00 +0h> because 50 hours is enough, but it is behind by 2d, 2h and 1s."); - } - - [Fact] - public void When_date_is_exactly_within_1d_before_another_date_it_should_not_throw() - { - // Arrange - var target = new DateTimeOffset(10.April(2010)); - DateTimeOffset subject = target - 1.Days(); - - // Act / Assert - subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); - } - - [Fact] - public void When_date_is_within_1d_before_another_date_it_should_not_throw() - { - // Arrange - var target = new DateTimeOffset(10.April(2010)); - DateTimeOffset subject = target - 23.Hours(); - - // Act / Assert - subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target); - } - - [Fact] - public void When_a_utc_date_is_within_0s_before_itself_it_should_not_throw() - { - // Arrange - var date = DateTimeOffset.UtcNow; // local timezone differs from +0h - - // Act / Assert - date.Should().BeWithin(TimeSpan.Zero).Before(date); - } - - [Fact] - public void When_a_utc_date_is_within_0s_after_itself_it_should_not_throw() - { - // Arrange - var date = DateTimeOffset.UtcNow; // local timezone differs from +0h - - // Act / Assert - date.Should().BeWithin(TimeSpan.Zero).After(date); - } - - [Fact] - public void When_time_is_not_less_than_30s_after_another_time_it_should_throw() - { - // Arrange - var target = 1.January(1).At(12, 0, 30).WithOffset(1.Hours()); - DateTimeOffset subject = target + 30.Seconds(); - - // Act - Action act = - () => subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target, "{0}s is the max", 30); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject <12:01:00 +1h> to be less than 30s after <12:00:30 +1h> because 30s is the max, but it is ahead by 30s."); - } - - [Fact] - public void When_time_is_less_than_30s_after_another_time_it_should_not_throw() - { - // Arrange - var target = new DateTimeOffset(1.January(1).At(12, 0, 30)); - DateTimeOffset subject = target + 20.Seconds(); - - // Act / Assert - subject.Should().BeLessThan(TimeSpan.FromSeconds(30)).After(target); - } - - [Fact] - public void When_asserting_subject_be_more_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, 15).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeMoreThan(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:15 +0h> to be more than 10s after <00:00:30 +0h>, but it is behind by 15s."); - } - - [Theory] - [InlineData(30, 20)] // edge case - [InlineData(30, 15)] - public void When_asserting_subject_be_at_least_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeAtLeast(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be at least 10s after <00:00:30 +0h>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_exactly_10_seconds_after_target_but_subject_is_before_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, 20).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeExactly(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:20 +0h> to be exactly 10s after <00:00:30 +0h>, but it is behind by 10s."); - } - - [Theory] - [InlineData(30, 20)] // edge case - [InlineData(30, 25)] - public void When_asserting_subject_be_within_10_seconds_after_target_but_subject_is_before_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeWithin(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be within 10s after <00:00:30 +0h>, but it is behind by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_less_than_10_seconds_after_target_but_subject_is_before_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, 25).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeLessThan(10.Seconds()).After(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:25 +0h> to be less than 10s after <00:00:30 +0h>, but it is behind by 5s."); - } - - [Fact] - public void When_asserting_subject_be_more_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, 45).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeMoreThan(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:45 +0h> to be more than 10s before <00:00:30 +0h>, but it is ahead by 15s."); - } - - [Theory] - [InlineData(30, 40)] // edge case - [InlineData(30, 45)] - public void When_asserting_subject_be_at_least_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeAtLeast(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be at least 10s before <00:00:30 +0h>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_exactly_10_seconds_before_target_but_subject_is_after_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, 40).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeExactly(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:40 +0h> to be exactly 10s before <00:00:30 +0h>, but it is ahead by 10s."); - } - - [Theory] - [InlineData(30, 40)] // edge case - [InlineData(30, 35)] - public void When_asserting_subject_be_within_10_seconds_before_target_but_subject_is_after_target_it_should_throw(int targetSeconds, int subjectSeconds) - { - // Arrange - var expectation = 1.January(0001).At(0, 0, targetSeconds).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, subjectSeconds).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeWithin(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage($"Expected subject <00:00:{subjectSeconds} +0h> to be within 10s before <00:00:30 +0h>, but it is ahead by {Math.Abs(subjectSeconds - targetSeconds)}s."); - } - - [Fact] - public void When_asserting_subject_be_less_than_10_seconds_before_target_but_subject_is_after_target_it_should_throw() - { - // Arrange - var expectation = 1.January(0001).At(0, 0, 30).WithOffset(0.Hours()); - var subject = 1.January(0001).At(0, 0, 45).WithOffset(0.Hours()); - - // Act - Action action = () => subject.Should().BeLessThan(10.Seconds()).Before(expectation); - - // Assert - action.Should().Throw() - .WithMessage("Expected subject <00:00:45 +0h> to be less than 10s before <00:00:30 +0h>, but it is ahead by 15s."); - } - - #endregion - - [Fact] - public void Should_support_chaining_constraints_with_and() - { - // Arrange - DateTimeOffset yesterday = new DateTime(2016, 06, 03); - DateTimeOffset? nullableDateTime = new DateTime(2016, 06, 04); - - // Act - Action action = () => - nullableDateTime.Should() - .HaveValue() - .And - .BeAfter(yesterday); - - // Assert - action.Should().NotThrow(); - } - - #region Be One Of - - [Fact] - public void When_a_value_is_not_one_of_the_specified_values_it_should_throw() - { - // Arrange - var value = new DateTimeOffset(31.December(2016), 1.Hours()); - - // Act - Action action = () => value.Should().BeOneOf(value + 1.Days(), value + 4.Hours()); - - // Assert - action.Should().Throw().WithMessage( - "Expected value to be one of {<2017-01-01 +1h>, <2016-12-31 04:00:00 +1h>}, but it was <2016-12-31 +1h>."); - } - - [Fact] - public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() - { - // Arrange - DateTimeOffset value = 31.December(2016).WithOffset(1.Hours()); - - // Act - Action action = () => value.Should().BeOneOf(new[] { value + 1.Days(), value + 2.Days() }, "because it's true"); - - // Assert - action.Should().Throw().WithMessage( - "Expected value to be one of {<2017-01-01 +1h>, <2017-01-02 +1h>} because it's true, but it was <2016-12-31 +1h>."); - } - - [Fact] - public void When_a_value_is_one_of_the_specified_values_it_should_succeed() - { - // Arrange - DateTimeOffset value = new DateTimeOffset(2016, 12, 30, 23, 58, 57, TimeSpan.FromHours(4)); - - // Act - Action action = () => value.Should().BeOneOf(new DateTimeOffset(2216, 1, 30, 0, 5, 7, TimeSpan.FromHours(2)), new DateTimeOffset(2016, 12, 30, 23, 58, 57, TimeSpan.FromHours(4))); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_a_null_value_is_not_one_of_the_specified_values_it_should_throw() - { - // Arrange - DateTimeOffset? value = null; - - // Act - Action action = () => value.Should().BeOneOf(new DateTimeOffset(2216, 1, 30, 0, 5, 7, TimeSpan.FromHours(1)), new DateTimeOffset(2016, 2, 10, 2, 45, 7, TimeSpan.FromHours(2))); - - // Assert - action.Should().Throw().WithMessage( - "Expected value to be one of {<2216-01-30 00:05:07 +1h>, <2016-02-10 02:45:07 +2h>}, but it was ."); - } - - [Fact] - public void When_a_value_is_one_of_the_specified_values_it_should_succeed_when_datetimeoffset_is_null() - { - // Arrange - DateTimeOffset? value = null; - - // Act - Action action = () => value.Should().BeOneOf(new DateTimeOffset(2216, 1, 30, 0, 5, 7, TimeSpan.Zero), null); - - // Assert - action.Should().NotThrow(); - } - - #endregion } } From 02b5797f17a6583b28e096d8a5dd5b4f84ebe139 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Mon, 18 Apr 2022 13:10:59 +0200 Subject: [PATCH 20/48] Add missing `null` check tests in Data*Specs --- .../DataRowSpecs.cs | 56 ++++++++++++++++++- .../DataSetSpecs.cs | 50 +++++++++++++++++ .../DataTableSpecs.cs | 48 ++++++++++++++++ 3 files changed, 153 insertions(+), 1 deletion(-) diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs index a7c26d3188..4639d70ff6 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataRowSpecs.cs @@ -364,7 +364,7 @@ public void Any_type_is_not_equivalent_to_data_row_colletion() { // Arrange var o = new object(); - + // Act Action act = () => o.Should().BeEquivalentTo((DataRowCollection)null); @@ -403,6 +403,20 @@ public void When_data_row_does_not_have_column_then_asserting_that_it_has_that_c action.Should().Throw().WithMessage("Expected dataRow to contain a column named *Unicorn*"); } + [Fact] + public void Null_data_row_does_not_have_column() + { + // Arrange + var dataRow = (DataRow)null; + + // Act + Action action = + () => dataRow.Should().HaveColumn("Does not matter"); + + // Assert + action.Should().Throw().WithMessage("Expected dataRow to contain a column named *Does not matter*, but found *"); + } + [Fact] public void When_data_row_data_has_all_columns_being_asserted_then_it_should_succeed() { @@ -419,6 +433,46 @@ public void When_data_row_data_has_all_columns_being_asserted_then_it_should_suc dataRow.Should().HaveColumns(subsetOfColumnNames); } + [Fact] + public void Data_row_with_all_colums_asserted_and_using_the_array_overload_passes() + { + // Arrange + var dataSet = CreateDummyDataSet(); + + var dataRow = dataSet.TypedDataTable1[0]; + + string[] subsetOfColumnNames = dataRow.Table.Columns.Cast() + .Take(dataRow.Table.Columns.Count - 2) + .Select(column => column.ColumnName) + .ToArray(); + + // Act & Assert + dataRow.Should().HaveColumns(subsetOfColumnNames); + } + + [Fact] + public void Null_data_row_and_using_the_array_overload_fails() + { + // Arrange + var dataSet = CreateDummyDataSet(); + + var dataRow = dataSet.TypedDataTable1[0]; + + var actual = (DataRow)null; + + string[] subsetOfColumnNames = dataRow.Table.Columns.Cast() + .Take(dataRow.Table.Columns.Count - 2) + .Select(column => column.ColumnName) + .ToArray(); + + // Act + Action act = () => actual.Should().HaveColumns(subsetOfColumnNames); + + // Assert + act.Should().Throw() + .WithMessage("Expected actual to be in a table containing *column*, but found *"); + } + [Fact] public void When_data_row_data_has_only_some_of_the_columns_being_asserted_then_it_should_fail() { diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs index dd8c0ade56..a3618cb0cd 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs @@ -648,6 +648,22 @@ public void When_data_set_table_count_has_expected_value_equivalence_test_should // Act & Assert dataSet.Should().HaveTableCount(correctTableCount); } + + [Fact] + public void Null_data_set_fails() + { + // Arrange + var dataSet = (DataSet)null; + + var correctTableCount = -1; + + // Act + Action act = () => dataSet.Should().HaveTableCount(correctTableCount); + + // Assert + act.Should().Throw() + .WithMessage("Expected dataSet to contain exactly*, but found *"); + } [Fact] public void When_data_set_table_count_has_unexpected_value_equivalence_test_should_fail() @@ -679,6 +695,22 @@ public void When_data_set_contains_expected_table_and_asserting_that_it_has_that dataSet.Should().HaveTable(existingTableName); } + [Fact] + public void Null_data_set_does_not_contain_expected_table() + { + // Arrange + var dataSet = (DataSet)null; + + var existingTableName = "Does not matter"; + + // Act + Action act = () => dataSet.Should().HaveTable(existingTableName); + + // Assert + act.Should().Throw() + .WithMessage("Expected dataSet to contain a table named*, but found *"); + } + [Fact] public void When_data_set_does_not_contain_expected_table_asserting_that_it_has_that_table_should_fail() { @@ -708,6 +740,24 @@ public void When_data_set_has_all_expected_tables_asserting_that_it_has_them_sho dataSet.Should().HaveTables(existingTableNames); } + [Fact] + public void Null_data_set_has_no_tables_and_fails() + { + // Arrange + var dataSet = CreateDummyDataSet(); + var actual = (DataSet)null; + + var existingTableNames = dataSet.Tables.Cast() + .Select(table => table.TableName); + + // Act + Action act = () => actual.Should().HaveTables(existingTableNames); + + // Assert + act.Should().Throw() + .WithMessage("Expected actual to contain*table*with specific name*, but found *"); + } + [Fact] public void When_data_set_has_some_of_the_expected_tables_but_not_all_then_asserting_that_it_has_them_should_fail() { diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs index 89d5689125..dd8c705488 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs @@ -757,6 +757,22 @@ public void When_data_table_has_expected_row_count_it_should_succeed() dataTable.Should().HaveRowCount(correctRowCount); } + [Fact] + public void Null_data_table_no_rows_and_fails_test() + { + // Arrange + var dataTable = (DataTable)null; + + int correctRowCount = -1; + + // Act + Action act = () => dataTable.Should().HaveRowCount(correctRowCount); + + // Assert + act.Should().Throw() + .WithMessage("Expected dataTable to contain exactly*row*, but found *"); + } + [Fact] public void When_empty_data_table_has_expected_row_count_of_zero_it_should_succeed() { @@ -805,6 +821,22 @@ public void When_data_table_has_expected_column_it_should_succeed() // Act & Assert dataTable.Should().HaveColumn(expectedColumnName); } + + [Fact] + public void Null_data_table_has_no_columns_and_fail_the_test() + { + // Arrange + var dataTable = (DataTable)null; + + var expectedColumnName = "Does not matter"; + + // Act + Action act = () => dataTable.Should().HaveColumn(expectedColumnName); + + // Assert + act.Should().Throw() + .WithMessage("Expected dataTable to contain a column named*, but found *"); + } [Fact] public void When_data_table_does_not_have_expected_column_it_should_fail() @@ -837,6 +869,22 @@ public void When_data_table_has_all_expected_columns_it_should_succeed() dataTable.Should().HaveColumns(existingColumnNames); } + [Fact] + public void Null_data_table_has_no_columns_and_fails_the_test() + { + // Arrange + var actual = (DataTable)null; + + var existingColumnName = "Does not matter"; + + // Act + Action act = () => actual.Should().HaveColumns(existingColumnName); + + // Assert + act.Should().Throw() + .WithMessage("Expected actual to contain*column*with specific name*, but found *"); + } + [Fact] public void When_data_table_has_only_some_expected_columns_then_asserting_that_it_has_all_of_them_should_fail() { From ee621f9bd5442af9d8314f703035eb65966630aa Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Mon, 18 Apr 2022 17:46:33 +0200 Subject: [PATCH 21/48] Seperate all `Guid` assertions into nested classes --- .../Primitives/GuidAssertionSpecs.cs | 371 +++++++++--------- 1 file changed, 189 insertions(+), 182 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Primitives/GuidAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/GuidAssertionSpecs.cs index c86ae89170..486dafa84f 100644 --- a/Tests/FluentAssertions.Specs/Primitives/GuidAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/GuidAssertionSpecs.cs @@ -6,201 +6,208 @@ namespace FluentAssertions.Specs.Primitives { public class GuidAssertionSpecs { - #region BeEmpty / NotBeEmpty - - [Fact] - public void Should_succeed_when_asserting_empty_guid_is_empty() - { - // Arrange - Guid guid = Guid.Empty; - - // Act / Assert - guid.Should().BeEmpty(); - } - - [Fact] - public void Should_fail_when_asserting_non_empty_guid_is_empty() - { - // Arrange - var guid = new Guid("12345678-1234-1234-1234-123456789012"); - - // Act - Action act = () => guid.Should().BeEmpty("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected Guid to be empty because we want to test the failure message, but found {12345678-1234-1234-1234-123456789012}."); - } - - [Fact] - public void Should_succeed_when_asserting_non_empty_guid_is_not_empty() - { - // Arrange - var guid = new Guid("12345678-1234-1234-1234-123456789012"); - - // Act - Action act = () => guid.Should().NotBeEmpty(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_empty_guid_is_not_empty() - { - // Act - Action act = () => Guid.Empty.Should().NotBeEmpty("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect Guid.Empty to be empty because we want to test the failure message."); - } - - #endregion - - #region Be / NotBe - - [Fact] - public void Should_succeed_when_asserting_guid_equals_the_same_guid() - { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - var sameGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => guid.Should().Be(sameGuid); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_succeed_when_asserting_guid_equals_the_same_guid_in_string_format() - { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => guid.Should().Be("11111111-aaaa-bbbb-cccc-999999999999"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_fail_when_asserting_guid_equals_a_different_guid() - { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - var differentGuid = new Guid("55555555-ffff-eeee-dddd-444444444444"); - - // Act - Action act = () => guid.Should().Be(differentGuid, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected Guid to be {55555555-ffff-eeee-dddd-444444444444} because we want to test the failure message, but found {11111111-aaaa-bbbb-cccc-999999999999}."); - } - - [Fact] - public void Should_throw_when_asserting_guid_equals_a_string_that_is_not_a_valid_guid() - { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => guid.Should().Be(string.Empty, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithParameterName("expected"); - } - - [Fact] - public void Should_succeed_when_asserting_guid_does_not_equal_a_different_guid() - { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - var differentGuid = new Guid("55555555-ffff-eeee-dddd-444444444444"); - - // Act - Action act = () => - guid.Should().NotBe(differentGuid); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Should_succeed_when_asserting_guid_does_not_equal_the_same_guid() + public class BeEmpty { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - var sameGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => guid.Should().NotBe(sameGuid, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect Guid to be {11111111-aaaa-bbbb-cccc-999999999999} because we want to test the failure message."); + [Fact] + public void Should_succeed_when_asserting_empty_guid_is_empty() + { + // Arrange + Guid guid = Guid.Empty; + + // Act / Assert + guid.Should().BeEmpty(); + } + + [Fact] + public void Should_fail_when_asserting_non_empty_guid_is_empty() + { + // Arrange + var guid = new Guid("12345678-1234-1234-1234-123456789012"); + + // Act + Action act = () => guid.Should().BeEmpty("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected Guid to be empty because we want to test the failure message, but found {12345678-1234-1234-1234-123456789012}."); + } } - [Fact] - public void Should_throw_when_asserting_guid_does_not_equal_a_string_that_is_not_a_valid_guid() + public class NotBeEmpty { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => guid.Should().NotBe(string.Empty, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithParameterName("unexpected"); + [Fact] + public void Should_succeed_when_asserting_non_empty_guid_is_not_empty() + { + // Arrange + var guid = new Guid("12345678-1234-1234-1234-123456789012"); + + // Act + Action act = () => guid.Should().NotBeEmpty(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_empty_guid_is_not_empty() + { + // Act + Action act = () => Guid.Empty.Should().NotBeEmpty("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect Guid.Empty to be empty because we want to test the failure message."); + } } - [Fact] - public void Should_succeed_when_asserting_guid_does_not_equal_a_different_guid_in_string_format() + public class Be { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => - guid.Should().NotBe("55555555-ffff-eeee-dddd-444444444444"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void Should_succeed_when_asserting_guid_equals_the_same_guid() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + var sameGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => guid.Should().Be(sameGuid); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_succeed_when_asserting_guid_equals_the_same_guid_in_string_format() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => guid.Should().Be("11111111-aaaa-bbbb-cccc-999999999999"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_fail_when_asserting_guid_equals_a_different_guid() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + var differentGuid = new Guid("55555555-ffff-eeee-dddd-444444444444"); + + // Act + Action act = () => guid.Should().Be(differentGuid, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected Guid to be {55555555-ffff-eeee-dddd-444444444444} because we want to test the failure message, but found {11111111-aaaa-bbbb-cccc-999999999999}."); + } + + [Fact] + public void Should_throw_when_asserting_guid_equals_a_string_that_is_not_a_valid_guid() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => guid.Should().Be(string.Empty, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithParameterName("expected"); + } } - [Fact] - public void Should_succeed_when_asserting_guid_does_not_equal_the_same_guid_in_string_format() + public class NotBe { - // Arrange - var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); - - // Act - Action act = () => - guid.Should().NotBe("11111111-aaaa-bbbb-cccc-999999999999", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect Guid to be {11111111-aaaa-bbbb-cccc-999999999999} *failure message*."); + [Fact] + public void Should_succeed_when_asserting_guid_does_not_equal_a_different_guid() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + var differentGuid = new Guid("55555555-ffff-eeee-dddd-444444444444"); + + // Act + Action act = () => + guid.Should().NotBe(differentGuid); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_succeed_when_asserting_guid_does_not_equal_the_same_guid() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + var sameGuid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => guid.Should().NotBe(sameGuid, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect Guid to be {11111111-aaaa-bbbb-cccc-999999999999} because we want to test the failure message."); + } + + [Fact] + public void Should_throw_when_asserting_guid_does_not_equal_a_string_that_is_not_a_valid_guid() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => guid.Should().NotBe(string.Empty, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithParameterName("unexpected"); + } + + [Fact] + public void Should_succeed_when_asserting_guid_does_not_equal_a_different_guid_in_string_format() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => + guid.Should().NotBe("55555555-ffff-eeee-dddd-444444444444"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Should_succeed_when_asserting_guid_does_not_equal_the_same_guid_in_string_format() + { + // Arrange + var guid = new Guid("11111111-aaaa-bbbb-cccc-999999999999"); + + // Act + Action act = () => + guid.Should().NotBe("11111111-aaaa-bbbb-cccc-999999999999", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect Guid to be {11111111-aaaa-bbbb-cccc-999999999999} *failure message*."); + } } - #endregion - - [Fact] - public void Should_support_chaining_constraints_with_and() + public class ChainingConstraint { - // Arrange - Guid guid = Guid.NewGuid(); - - // Act / Assert - guid.Should() - .NotBeEmpty() - .And.Be(guid); + [Fact] + public void Should_support_chaining_constraints_with_and() + { + // Arrange + Guid guid = Guid.NewGuid(); + + // Act / Assert + guid.Should() + .NotBeEmpty() + .And.Be(guid); + } } } } From b971ce9312abca0a92b1dd5f190d927fd0388185 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Mon, 18 Apr 2022 18:20:35 +0200 Subject: [PATCH 22/48] Seperate all `object` assertions into nested classes --- .../Primitives/ObjectAssertionSpecs.cs | 1751 ++++++++--------- 1 file changed, 875 insertions(+), 876 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs index 6ac03c28bf..ac1acef301 100644 --- a/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs @@ -14,132 +14,136 @@ namespace FluentAssertions.Specs.Primitives { public class ObjectAssertionSpecs { - #region Be / NotBe - - [Fact] - public void When_two_equal_object_are_expected_to_be_equal_it_should_not_fail() + public class Be { - // Arrange - var someObject = new ClassWithCustomEqualMethod(1); - var equalObject = new ClassWithCustomEqualMethod(1); + [Fact] + public void When_two_equal_object_are_expected_to_be_equal_it_should_not_fail() + { + // Arrange + var someObject = new ClassWithCustomEqualMethod(1); + var equalObject = new ClassWithCustomEqualMethod(1); - // Act / Assert - someObject.Should().Be(equalObject); - } + // Act / Assert + someObject.Should().Be(equalObject); + } - [Fact] - public void When_two_different_objects_are_expected_to_be_equal_it_should_fail_with_a_clear_explanation() - { - // Arrange - var someObject = new ClassWithCustomEqualMethod(1); - var nonEqualObject = new ClassWithCustomEqualMethod(2); + [Fact] + public void When_two_different_objects_are_expected_to_be_equal_it_should_fail_with_a_clear_explanation() + { + // Arrange + var someObject = new ClassWithCustomEqualMethod(1); + var nonEqualObject = new ClassWithCustomEqualMethod(2); - // Act - Action act = () => someObject.Should().Be(nonEqualObject); + // Act + Action act = () => someObject.Should().Be(nonEqualObject); - // Assert - act.Should().Throw().WithMessage( - "Expected someObject to be ClassWithCustomEqualMethod(2), but found ClassWithCustomEqualMethod(1)."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected someObject to be ClassWithCustomEqualMethod(2), but found ClassWithCustomEqualMethod(1)."); + } - [Fact] - public void When_both_subject_and_expected_are_null_it_should_succeed() - { - // Arrange - object someObject = null; - object expectedObject = null; + [Fact] + public void When_both_subject_and_expected_are_null_it_should_succeed() + { + // Arrange + object someObject = null; + object expectedObject = null; - // Act / Assert - someObject.Should().Be(expectedObject); - } + // Act / Assert + someObject.Should().Be(expectedObject); + } - [Fact] - public void When_the_subject_is_null_it_should_fail() - { - // Arrange - object someObject = null; - var nonEqualObject = new ClassWithCustomEqualMethod(2); + [Fact] + public void When_the_subject_is_null_it_should_fail() + { + // Arrange + object someObject = null; + var nonEqualObject = new ClassWithCustomEqualMethod(2); - // Act - Action act = () => someObject.Should().Be(nonEqualObject); + // Act + Action act = () => someObject.Should().Be(nonEqualObject); - // Assert - act.Should().Throw() - .WithMessage("Expected someObject to be ClassWithCustomEqualMethod(2), but found ."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected someObject to be ClassWithCustomEqualMethod(2), but found ."); + } - [Fact] - public void When_two_different_objects_are_expected_to_be_equal_it_should_fail_and_use_the_reason() - { - // Arrange - var someObject = new ClassWithCustomEqualMethod(1); - var nonEqualObject = new ClassWithCustomEqualMethod(2); + [Fact] + public void When_two_different_objects_are_expected_to_be_equal_it_should_fail_and_use_the_reason() + { + // Arrange + var someObject = new ClassWithCustomEqualMethod(1); + var nonEqualObject = new ClassWithCustomEqualMethod(2); - // Act - Action act = () => someObject.Should().Be(nonEqualObject, "because it should use the {0}", "reason"); + // Act + Action act = () => someObject.Should().Be(nonEqualObject, "because it should use the {0}", "reason"); - // Assert - act.Should().Throw() - .WithMessage( - "Expected someObject to be ClassWithCustomEqualMethod(2) because it should use the reason, but found ClassWithCustomEqualMethod(1)."); - } + // Assert + act.Should().Throw() + .WithMessage( + "Expected someObject to be ClassWithCustomEqualMethod(2) because it should use the reason, but found ClassWithCustomEqualMethod(1)."); + } - [Fact] - public void When_non_equal_objects_are_expected_to_be_not_equal_it_should_not_fail() - { - // Arrange - var someObject = new ClassWithCustomEqualMethod(1); - var nonEqualObject = new ClassWithCustomEqualMethod(2); + [Fact] + public void When_comparing_a_numeric_and_an_enum_for_equality_it_should_throw() + { + // Arrange + object subject = 1; + MyEnum expected = MyEnum.One; + + // Act + Action act = () => subject.Should().Be(expected); - // Act / Assert - someObject.Should().NotBe(nonEqualObject); + // Assert + act.Should().Throw(); + } } - [Fact] - public void When_two_equal_objects_are_expected_not_to_be_equal_it_should_fail_with_a_clear_explanation() + public class NotBe { - // Arrange - var someObject = new ClassWithCustomEqualMethod(1); - var equalObject = new ClassWithCustomEqualMethod(1); - - // Act - Action act = () => - someObject.Should().NotBe(equalObject); + [Fact] + public void When_non_equal_objects_are_expected_to_be_not_equal_it_should_not_fail() + { + // Arrange + var someObject = new ClassWithCustomEqualMethod(1); + var nonEqualObject = new ClassWithCustomEqualMethod(2); - // Assert - act.Should().Throw().WithMessage( - "Did not expect someObject to be equal to ClassWithCustomEqualMethod(1)."); - } + // Act / Assert + someObject.Should().NotBe(nonEqualObject); + } - [Fact] - public void When_two_equal_objects_are_expected_not_to_be_equal_it_should_fail_and_use_the_reason() - { - // Arrange - var someObject = new ClassWithCustomEqualMethod(1); - var equalObject = new ClassWithCustomEqualMethod(1); - - // Act - Action act = () => - someObject.Should().NotBe(equalObject, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect someObject to be equal to ClassWithCustomEqualMethod(1) " + - "because we want to test the failure message."); - } + [Fact] + public void When_two_equal_objects_are_expected_not_to_be_equal_it_should_fail_with_a_clear_explanation() + { + // Arrange + var someObject = new ClassWithCustomEqualMethod(1); + var equalObject = new ClassWithCustomEqualMethod(1); - [Fact] - public void When_comparing_a_numeric_and_an_enum_for_equality_it_should_throw() - { - // Arrange - object subject = 1; - MyEnum expected = MyEnum.One; + // Act + Action act = () => + someObject.Should().NotBe(equalObject); - // Act - Action act = () => subject.Should().Be(expected); + // Assert + act.Should().Throw().WithMessage( + "Did not expect someObject to be equal to ClassWithCustomEqualMethod(1)."); + } - // Assert - act.Should().Throw(); + [Fact] + public void When_two_equal_objects_are_expected_not_to_be_equal_it_should_fail_and_use_the_reason() + { + // Arrange + var someObject = new ClassWithCustomEqualMethod(1); + var equalObject = new ClassWithCustomEqualMethod(1); + + // Act + Action act = () => + someObject.Should().NotBe(equalObject, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect someObject to be equal to ClassWithCustomEqualMethod(1) " + + "because we want to test the failure message."); + } } private enum MyEnum @@ -148,810 +152,810 @@ private enum MyEnum Two = 2 } - #endregion - - #region BeNull / BeNotNull - - [Fact] - public void Should_succeed_when_asserting_null_object_to_be_null() - { - // Arrange - object someObject = null; - - // Act / Assert - someObject.Should().BeNull(); - } - - [Fact] - public void Should_fail_when_asserting_non_null_object_to_be_null() - { - // Arrange - var someObject = new object(); - - // Act - Action act = () => someObject.Should().BeNull(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_non_null_object_is_expected_to_be_null_it_should_fail() - { - // Arrange - var someObject = new object(); - - // Act - Action act = () => someObject.Should().BeNull("because we want to test the failure {0}", "message"); - - // Assert - act - .Should().Throw() - .Where(e => e.Message.StartsWith( - "Expected someObject to be because we want to test the failure message, but found System.Object", - StringComparison.Ordinal)); - } - - [Fact] - public void Should_succeed_when_asserting_non_null_object_not_to_be_null() - { - // Arrange - var someObject = new object(); - - // Act / Assert - someObject.Should().NotBeNull(); - } - - [Fact] - public void Should_fail_when_asserting_null_object_not_to_be_null() - { - // Arrange - object someObject = null; - - // Act - Action act = () => someObject.Should().NotBeNull(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_null_object_not_to_be_null() - { - // Arrange - object someObject = null; - - // Act - Action act = () => someObject.Should().NotBeNull("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected someObject not to be because we want to test the failure message."); - } - - #endregion - - #region BeOfType / NotBeOfType - - [Fact] - public void When_object_type_is_matched_against_null_type_exactly_it_should_throw() + public class BeNull { - // Arrange - var someObject = new object(); + [Fact] + public void Should_succeed_when_asserting_null_object_to_be_null() + { + // Arrange + object someObject = null; - // Act - Action act = () => someObject.Should().BeOfType(null); + // Act / Assert + someObject.Should().BeNull(); + } - // Assert - act.Should().Throw() - .WithParameterName("expectedType"); - } + [Fact] + public void Should_fail_when_asserting_non_null_object_to_be_null() + { + // Arrange + var someObject = new object(); - [Fact] - public void When_object_type_is_matched_negatively_against_null_type_exactly_it_should_throw() - { - // Arrange - var someObject = new object(); + // Act + Action act = () => someObject.Should().BeNull(); - // Act - Action act = () => someObject.Should().NotBeOfType(null); + // Assert + act.Should().Throw(); + } - // Assert - act.Should().Throw() - .WithParameterName("unexpectedType"); + [Fact] + public void When_a_non_null_object_is_expected_to_be_null_it_should_fail() + { + // Arrange + var someObject = new object(); + + // Act + Action act = () => someObject.Should().BeNull("because we want to test the failure {0}", "message"); + + // Assert + act + .Should().Throw() + .Where(e => e.Message.StartsWith( + "Expected someObject to be because we want to test the failure message, but found System.Object", + StringComparison.Ordinal)); + } } - [Fact] - public void When_object_type_is_exactly_equal_to_the_specified_type_it_should_not_fail() + public class BeNotNull { - // Arrange - var someObject = new Exception(); - - // Act - Action act = () => someObject.Should().BeOfType(); + [Fact] + public void Should_succeed_when_asserting_non_null_object_not_to_be_null() + { + // Arrange + var someObject = new object(); - // Assert - act.Should().NotThrow(); - } + // Act / Assert + someObject.Should().NotBeNull(); + } - [Fact] - public void When_object_type_is_value_type_and_matches_received_type_should_not_fail_and_assert_correctly() - { - // Arrange - int valueTypeObject = 42; + [Fact] + public void Should_fail_when_asserting_null_object_not_to_be_null() + { + // Arrange + object someObject = null; - // Act - Action act = () => valueTypeObject.Should().BeOfType(typeof(int)); + // Act + Action act = () => someObject.Should().NotBeNull(); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_object_is_matched_against_a_null_type_it_should_throw() - { - // Arrange - int valueTypeObject = 42; + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_null_object_not_to_be_null() + { + // Arrange + object someObject = null; - // Act - Action act = () => valueTypeObject.Should().BeOfType(null); + // Act + Action act = () => someObject.Should().NotBeNull("because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithParameterName("expectedType"); + // Assert + act.Should().Throw().WithMessage( + "Expected someObject not to be because we want to test the failure message."); + } } - [Fact] - public void When_null_object_is_matched_against_a_type_it_should_throw() + public class BeOfType { - // Arrange - int? valueTypeObject = null; + [Fact] + public void When_object_type_is_matched_against_null_type_exactly_it_should_throw() + { + // Arrange + var someObject = new object(); - // Act - Action act = () => valueTypeObject.Should().BeOfType(typeof(int), "because we want to test the failure {0}", "message"); + // Act + Action act = () => someObject.Should().BeOfType(null); - // Assert - act.Should().Throw() - .WithMessage("*type to be System.Int32*because we want to test the failure message*"); - } + // Assert + act.Should().Throw() + .WithParameterName("expectedType"); + } - [Fact] - public void When_object_is_matched_negatively_against_a_null_type_it_should_throw() - { - // Arrange - int valueTypeObject = 42; + [Fact] + public void When_object_type_is_exactly_equal_to_the_specified_type_it_should_not_fail() + { + // Arrange + var someObject = new Exception(); - // Act - Action act = () => valueTypeObject.Should().NotBeOfType(null); + // Act + Action act = () => someObject.Should().BeOfType(); - // Assert - act.Should().Throw() - .WithParameterName("unexpectedType"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_object_type_is_value_type_and_doesnt_match_received_type_as_expected_should_not_fail_and_assert_correctly() - { - // Arrange - int valueTypeObject = 42; + [Fact] + public void When_object_type_is_value_type_and_matches_received_type_should_not_fail_and_assert_correctly() + { + // Arrange + int valueTypeObject = 42; - // Act - Action act = () => valueTypeObject.Should().NotBeOfType(typeof(double)); + // Act + Action act = () => valueTypeObject.Should().BeOfType(typeof(int)); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_null_object_is_matched_negatively_against_a_type_it_should_throw() - { - // Arrange - int? valueTypeObject = null; + [Fact] + public void When_object_is_matched_against_a_null_type_it_should_throw() + { + // Arrange + int valueTypeObject = 42; - // Act - Action act = () => valueTypeObject.Should().NotBeOfType(typeof(int), "because we want to test the failure {0}", "message"); + // Act + Action act = () => valueTypeObject.Should().BeOfType(null); - // Assert - act.Should().Throw() - .WithMessage("*type not to be System.Int32*because we want to test the failure message*"); - } + // Assert + act.Should().Throw() + .WithParameterName("expectedType"); + } - [Fact] - public void When_object_type_is_value_type_and_matches_received_type_not_as_expected_should_fail() - { - // Arrange - int valueTypeObject = 42; - var expectedType = typeof(int); + [Fact] + public void When_null_object_is_matched_against_a_type_it_should_throw() + { + // Arrange + int? valueTypeObject = null; - // Act - Action act = () => valueTypeObject.Should().NotBeOfType(expectedType); + // Act + Action act = () => valueTypeObject.Should().BeOfType(typeof(int), "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage($"Expected type not to be [{expectedType.AssemblyQualifiedName}], but it is."); - } + // Assert + act.Should().Throw() + .WithMessage("*type to be System.Int32*because we want to test the failure message*"); + } - [Fact] - public void When_object_type_is_value_type_and_doesnt_match_received_type_should_fail() - { - // Arrange - int valueTypeObject = 42; - var doubleType = typeof(double); + [Fact] + public void When_object_type_is_value_type_and_doesnt_match_received_type_should_fail() + { + // Arrange + int valueTypeObject = 42; + var doubleType = typeof(double); - // Act - Action act = () => valueTypeObject.Should().BeOfType(doubleType); + // Act + Action act = () => valueTypeObject.Should().BeOfType(doubleType); - // Assert - act.Should().Throw().WithMessage($"Expected type to be {doubleType}, but found {valueTypeObject.GetType()}."); - } + // Assert + act.Should().Throw().WithMessage($"Expected type to be {doubleType}, but found {valueTypeObject.GetType()}."); + } - [Fact] - public void When_object_is_of_the_expected_type_it_should_cast_the_returned_object_for_chaining() - { - // Arrange - var someObject = new Exception("Actual Message"); + [Fact] + public void When_object_is_of_the_expected_type_it_should_cast_the_returned_object_for_chaining() + { + // Arrange + var someObject = new Exception("Actual Message"); - // Act - Action act = () => someObject.Should().BeOfType().Which.Message.Should().Be("Other Message"); + // Act + Action act = () => someObject.Should().BeOfType().Which.Message.Should().Be("Other Message"); - // Assert - act.Should().Throw().WithMessage("*Expected*Other*Actual*"); - } + // Assert + act.Should().Throw().WithMessage("*Expected*Other*Actual*"); + } - [Fact] - public void When_object_type_is_different_than_expected_type_it_should_fail_with_descriptive_message() - { - // Arrange - var someObject = new object(); + [Fact] + public void When_object_type_is_different_than_expected_type_it_should_fail_with_descriptive_message() + { + // Arrange + var someObject = new object(); - // Act - Action act = () => someObject.Should().BeOfType("because they are {0} {1}", "of different", "type"); + // Act + Action act = () => someObject.Should().BeOfType("because they are {0} {1}", "of different", "type"); - // Assert - act.Should().Throw().WithMessage( - "Expected type to be System.Int32 because they are of different type, but found System.Object."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected type to be System.Int32 because they are of different type, but found System.Object."); + } - [Fact] - public void When_asserting_the_type_of_a_null_object_it_should_throw() - { - // Arrange - object someObject = null; + [Fact] + public void When_asserting_the_type_of_a_null_object_it_should_throw() + { + // Arrange + object someObject = null; - // Act - Action act = () => someObject.Should().BeOfType(); + // Act + Action act = () => someObject.Should().BeOfType(); - // Assert - act.Should().Throw() - .WithMessage("Expected someObject to be System.Int32, but found ."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected someObject to be System.Int32, but found ."); + } - [Fact] - public void When_object_type_is_same_as_expected_type_but_in_different_assembly_it_should_fail_with_assembly_qualified_name() - { - // Arrange - var typeFromOtherAssembly = - new AssemblyA.ClassA().ReturnClassC(); + [Fact] + public void When_object_type_is_same_as_expected_type_but_in_different_assembly_it_should_fail_with_assembly_qualified_name() + { + // Arrange + var typeFromOtherAssembly = + new AssemblyA.ClassA().ReturnClassC(); - // Act + // Act #pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec - Action act = () => - typeFromOtherAssembly.Should().BeOfType(); + Action act = () => + typeFromOtherAssembly.Should().BeOfType(); #pragma warning restore 436 - // Assert - act.Should().Throw() - .WithMessage("Expected type to be [AssemblyB.ClassC, FluentAssertions.Specs*], but found [AssemblyB.ClassC, AssemblyB*]."); - } - - [Fact] - public void When_object_type_is_a_subclass_of_the_expected_type_it_should_fail() - { - // Arrange - var someObject = new DummyImplementingClass(); - - // Act - Action act = () => someObject.Should().BeOfType(); - - // Assert - act.Should().Throw().WithMessage( - "Expected type to be FluentAssertions*DummyBaseClass, but found FluentAssertions*DummyImplementingClass."); - } - - #endregion - - #region BeAssignableTo + // Assert + act.Should().Throw() + .WithMessage("Expected type to be [AssemblyB.ClassC, FluentAssertions.Specs*], but found [AssemblyB.ClassC, AssemblyB*]."); + } - [Fact] - public void When_object_type_is_matched_against_null_type_it_should_throw() - { - // Arrange - var someObject = new object(); + [Fact] + public void When_object_type_is_a_subclass_of_the_expected_type_it_should_fail() + { + // Arrange + var someObject = new DummyImplementingClass(); - // Act - Action act = () => someObject.Should().BeAssignableTo(null); + // Act + Action act = () => someObject.Should().BeOfType(); - // Assert - act.Should().Throw() - .WithParameterName("type"); + // Assert + act.Should().Throw().WithMessage( + "Expected type to be FluentAssertions*DummyBaseClass, but found FluentAssertions*DummyImplementingClass."); + } } - [Fact] - public void When_its_own_type_it_should_succeed() + public class NotBeOfType { - // Arrange - var someObject = new DummyImplementingClass(); + [Fact] + public void When_object_type_is_matched_negatively_against_null_type_exactly_it_should_throw() + { + // Arrange + var someObject = new object(); - // Act / Assert - someObject.Should().BeAssignableTo(); - } + // Act + Action act = () => someObject.Should().NotBeOfType(null); - [Fact] - public void When_its_base_type_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); + // Assert + act.Should().Throw() + .WithParameterName("unexpectedType"); + } - // Act / Assert - someObject.Should().BeAssignableTo(); - } + [Fact] + public void When_object_is_matched_negatively_against_a_null_type_it_should_throw() + { + // Arrange + int valueTypeObject = 42; - [Fact] - public void When_an_implemented_interface_type_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); + // Act + Action act = () => valueTypeObject.Should().NotBeOfType(null); - // Act / Assert - someObject.Should().BeAssignableTo(); - } + // Assert + act.Should().Throw() + .WithParameterName("unexpectedType"); + } - [Fact] - public void When_an_unrelated_type_it_should_fail_with_a_descriptive_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().BeAssignableTo("because we want to test the failure {0}", "message"); + [Fact] + public void When_object_type_is_value_type_and_doesnt_match_received_type_as_expected_should_not_fail_and_assert_correctly() + { + // Arrange + int valueTypeObject = 42; - // Act / Assert - act.Should().Throw() - .WithMessage($"*assignable to {typeof(DateTime)}*failure message*{typeof(DummyImplementingClass)} is not*"); - } + // Act + Action act = () => valueTypeObject.Should().NotBeOfType(typeof(double)); - [Fact] - public void When_to_the_expected_type_it_should_cast_the_returned_object_for_chaining() - { - // Arrange - var someObject = new Exception("Actual Message"); + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => someObject.Should().BeAssignableTo().Which.Message.Should().Be("Other Message"); + [Fact] + public void When_null_object_is_matched_negatively_against_a_type_it_should_throw() + { + // Arrange + int? valueTypeObject = null; - // Assert - act.Should().Throw().WithMessage("*Expected*Other*Actual*"); - } + // Act + Action act = () => valueTypeObject.Should().NotBeOfType(typeof(int), "because we want to test the failure {0}", "message"); - [Fact] - public void When_a_null_instance_is_asserted_to_be_assignableOfT_it_should_fail() - { - // Arrange - object someObject = null; + // Assert + act.Should().Throw() + .WithMessage("*type not to be System.Int32*because we want to test the failure message*"); + } - // Act - Action act = () => + [Fact] + public void When_object_type_is_value_type_and_matches_received_type_not_as_expected_should_fail() { - using var _ = new AssertionScope(); - someObject.Should().BeAssignableTo("because we want to test the failure {0}", "message"); - }; + // Arrange + int valueTypeObject = 42; + var expectedType = typeof(int); - // Assert - act.Should().Throw() - .WithMessage($"*assignable to {typeof(DateTime)}*failure message*found *"); - } + // Act + Action act = () => valueTypeObject.Should().NotBeOfType(expectedType); - [Fact] - public void When_its_own_type_instance_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); - - // Act / Assert - someObject.Should().BeAssignableTo(typeof(DummyImplementingClass)); + // Assert + act.Should().Throw().WithMessage($"Expected type not to be [{expectedType.AssemblyQualifiedName}], but it is."); + } } - [Fact] - public void When_its_base_type_instance_it_should_succeed() + public class BeAssignableTo { - // Arrange - var someObject = new DummyImplementingClass(); + [Fact] + public void When_object_type_is_matched_against_null_type_it_should_throw() + { + // Arrange + var someObject = new object(); - // Act / Assert - someObject.Should().BeAssignableTo(typeof(DummyBaseClass)); - } + // Act + Action act = () => someObject.Should().BeAssignableTo(null); - [Fact] - public void When_an_implemented_interface_type_instance_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); + // Assert + act.Should().Throw() + .WithParameterName("type"); + } - // Act / Assert - someObject.Should().BeAssignableTo(typeof(IDisposable)); - } + [Fact] + public void When_its_own_type_it_should_succeed() + { + // Arrange + var someObject = new DummyImplementingClass(); - [Fact] - public void When_an_implemented_open_generic_interface_type_instance_it_should_succeed() - { - // Arrange - var someObject = new System.Collections.Generic.List(); + // Act / Assert + someObject.Should().BeAssignableTo(); + } - // Act / Assert - someObject.Should().BeAssignableTo(typeof(System.Collections.Generic.IList<>)); - } + [Fact] + public void When_its_base_type_it_should_succeed() + { + // Arrange + var someObject = new DummyImplementingClass(); - [Fact] - public void When_a_null_instance_is_asserted_to_be_assignable_it_should_fail_with_a_descriptive_message() - { - // Arrange - object someObject = null; + // Act / Assert + someObject.Should().BeAssignableTo(); + } - // Act - Action act = () => + [Fact] + public void When_an_implemented_interface_type_it_should_succeed() { - using var _ = new AssertionScope(); - someObject.Should().BeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage($"*assignable to {typeof(DateTime)}*failure message*found *"); - } + // Arrange + var someObject = new DummyImplementingClass(); - [Fact] - public void When_an_unrelated_type_instance_it_should_fail_with_a_descriptive_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().BeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); + // Act / Assert + someObject.Should().BeAssignableTo(); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*assignable to {typeof(DateTime)}*failure message*{typeof(DummyImplementingClass)} is not*"); - } + [Fact] + public void When_an_unrelated_type_it_should_fail_with_a_descriptive_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().BeAssignableTo("because we want to test the failure {0}", "message"); - [Fact] - public void When_unrelated_to_open_generic_type_it_should_fail_with_a_descriptive_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().BeAssignableTo(typeof(System.Collections.Generic.IList<>), "because we want to test the failure {0}", "message"); + // Act / Assert + act.Should().Throw() + .WithMessage($"*assignable to {typeof(DateTime)}*failure message*{typeof(DummyImplementingClass)} is not*"); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*assignable to {typeof(System.Collections.Generic.IList<>)}*failure message*{typeof(DummyImplementingClass)} is not*"); - } + [Fact] + public void When_to_the_expected_type_it_should_cast_the_returned_object_for_chaining() + { + // Arrange + var someObject = new Exception("Actual Message"); - [Fact] - public void When_an_assertion_fails_on_BeAssignableTo_succeeding_message_should_be_included() - { - // Act - Action act = () => - { - using var _ = new AssertionScope(); - var item = string.Empty; - item.Should().BeAssignableTo(); - item.Should().BeAssignableTo(); - }; - - // Assert - act.Should().Throw() - .WithMessage( - "Expected * to be assignable to System.Int32, but System.String is not.*" + - "Expected * to be assignable to System.Int64, but System.String is not."); - } + // Act + Action act = () => someObject.Should().BeAssignableTo().Which.Message.Should().Be("Other Message"); - #endregion + // Assert + act.Should().Throw().WithMessage("*Expected*Other*Actual*"); + } - #region NotBeAssignableTo + [Fact] + public void When_a_null_instance_is_asserted_to_be_assignableOfT_it_should_fail() + { + // Arrange + object someObject = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someObject.Should().BeAssignableTo("because we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage($"*assignable to {typeof(DateTime)}*failure message*found *"); + } - [Fact] - public void When_object_type_is_matched_negatively_against_null_type_it_should_throw() - { - // Arrange - var someObject = new object(); + [Fact] + public void When_its_own_type_instance_it_should_succeed() + { + // Arrange + var someObject = new DummyImplementingClass(); - // Act - Action act = () => someObject.Should().NotBeAssignableTo(null); + // Act / Assert + someObject.Should().BeAssignableTo(typeof(DummyImplementingClass)); + } - // Assert - act.Should().Throw() - .WithParameterName("type"); - } + [Fact] + public void When_its_base_type_instance_it_should_succeed() + { + // Arrange + var someObject = new DummyImplementingClass(); - [Fact] - public void When_its_own_type_and_asserting_not_assignable_it_should_fail_with_a_useful_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().NotBeAssignableTo("because we want to test the failure {0}", "message"); + // Act / Assert + someObject.Should().BeAssignableTo(typeof(DummyBaseClass)); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(DummyImplementingClass)}*failure message*{typeof(DummyImplementingClass)} is*"); - } + [Fact] + public void When_an_implemented_interface_type_instance_it_should_succeed() + { + // Arrange + var someObject = new DummyImplementingClass(); - [Fact] - public void When_its_base_type_and_asserting_not_assignable_it_should_fail_with_a_useful_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().NotBeAssignableTo("because we want to test the failure {0}", "message"); + // Act / Assert + someObject.Should().BeAssignableTo(typeof(IDisposable)); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(DummyBaseClass)}*failure message*{typeof(DummyImplementingClass)} is*"); - } + [Fact] + public void When_an_implemented_open_generic_interface_type_instance_it_should_succeed() + { + // Arrange + var someObject = new System.Collections.Generic.List(); - [Fact] - public void When_an_implemented_interface_type_and_asserting_not_assignable_it_should_fail_with_a_useful_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().NotBeAssignableTo("because we want to test the failure {0}", "message"); + // Act / Assert + someObject.Should().BeAssignableTo(typeof(System.Collections.Generic.IList<>)); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(IDisposable)}*failure message*{typeof(DummyImplementingClass)} is*"); - } + [Fact] + public void When_a_null_instance_is_asserted_to_be_assignable_it_should_fail_with_a_descriptive_message() + { + // Arrange + object someObject = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someObject.Should().BeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage($"*assignable to {typeof(DateTime)}*failure message*found *"); + } - [Fact] - public void When_an_unrelated_type_and_asserting_not_assignable_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); + [Fact] + public void When_an_unrelated_type_instance_it_should_fail_with_a_descriptive_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().BeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); - // Act / Assert - someObject.Should().NotBeAssignableTo(); - } + // Act / Assert + act.Should().Throw() + .WithMessage($"*assignable to {typeof(DateTime)}*failure message*{typeof(DummyImplementingClass)} is not*"); + } - [Fact] - public void When_not_to_the_unexpected_type_and_asserting_not_assignable_it_should_not_cast_the_returned_object_for_chaining() - { - // Arrange - var someObject = new Exception("Actual Message"); + [Fact] + public void When_unrelated_to_open_generic_type_it_should_fail_with_a_descriptive_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().BeAssignableTo(typeof(System.Collections.Generic.IList<>), "because we want to test the failure {0}", "message"); - // Act - Action act = () => someObject.Should().NotBeAssignableTo() - .And.Subject.Should().BeOfType() - .Which.Message.Should().Be("Other Message"); + // Act / Assert + act.Should().Throw() + .WithMessage($"*assignable to {typeof(System.Collections.Generic.IList<>)}*failure message*{typeof(DummyImplementingClass)} is not*"); + } - // Assert - act.Should().Throw().WithMessage("*Expected*Other*Actual*"); + [Fact] + public void When_an_assertion_fails_on_BeAssignableTo_succeeding_message_should_be_included() + { + // Act + Action act = () => + { + using var _ = new AssertionScope(); + var item = string.Empty; + item.Should().BeAssignableTo(); + item.Should().BeAssignableTo(); + }; + + // Assert + act.Should().Throw() + .WithMessage( + "Expected * to be assignable to System.Int32, but System.String is not.*" + + "Expected * to be assignable to System.Int64, but System.String is not."); + } } - [Fact] - public void When_its_own_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + public class NotBeAssignableTo { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().NotBeAssignableTo(typeof(DummyImplementingClass), "because we want to test the failure {0}", "message"); + [Fact] + public void When_object_type_is_matched_negatively_against_null_type_it_should_throw() + { + // Arrange + var someObject = new object(); - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(DummyImplementingClass)}*failure message*{typeof(DummyImplementingClass)} is*"); - } + // Act + Action act = () => someObject.Should().NotBeAssignableTo(null); - [Fact] - public void When_its_base_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().NotBeAssignableTo(typeof(DummyBaseClass), "because we want to test the failure {0}", "message"); + // Assert + act.Should().Throw() + .WithParameterName("type"); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(DummyBaseClass)}*failure message*{typeof(DummyImplementingClass)} is*"); - } + [Fact] + public void When_its_own_type_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().NotBeAssignableTo("because we want to test the failure {0}", "message"); - [Fact] - public void When_an_implemented_interface_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() - { - // Arrange - var someObject = new DummyImplementingClass(); - Action act = () => someObject.Should().NotBeAssignableTo(typeof(IDisposable), "because we want to test the failure {0}", "message"); + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(DummyImplementingClass)}*failure message*{typeof(DummyImplementingClass)} is*"); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(IDisposable)}*failure message*{typeof(DummyImplementingClass)} is*"); - } + [Fact] + public void When_its_base_type_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().NotBeAssignableTo("because we want to test the failure {0}", "message"); - [Fact] - public void When_an_implemented_open_generic_interface_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() - { - // Arrange - var someObject = new System.Collections.Generic.List(); - Action act = () => someObject.Should().NotBeAssignableTo(typeof(System.Collections.Generic.IList<>), "because we want to test the failure {0}", "message"); + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(DummyBaseClass)}*failure message*{typeof(DummyImplementingClass)} is*"); + } - // Act / Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(System.Collections.Generic.IList<>)}*failure message*{typeof(System.Collections.Generic.List)} is*"); - } + [Fact] + public void When_an_implemented_interface_type_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().NotBeAssignableTo("because we want to test the failure {0}", "message"); - [Fact] - public void When_a_null_instance_is_asserted_to_not_be_assignable_it_should_fail_with_a_descriptive_message() - { - // Arrange - object someObject = null; + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(IDisposable)}*failure message*{typeof(DummyImplementingClass)} is*"); + } - // Act - Action act = () => + [Fact] + public void When_an_unrelated_type_and_asserting_not_assignable_it_should_succeed() { - using var _ = new AssertionScope(); - someObject.Should().NotBeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); - }; + // Arrange + var someObject = new DummyImplementingClass(); - // Assert - act.Should().Throw() - .WithMessage($"*not be assignable to {typeof(DateTime)}*failure message*found *"); - } + // Act / Assert + someObject.Should().NotBeAssignableTo(); + } - [Fact] - public void When_an_unrelated_type_instance_and_asserting_not_assignable_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); + [Fact] + public void When_not_to_the_unexpected_type_and_asserting_not_assignable_it_should_not_cast_the_returned_object_for_chaining() + { + // Arrange + var someObject = new Exception("Actual Message"); - // Act / Assert - someObject.Should().NotBeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); - } + // Act + Action act = () => someObject.Should().NotBeAssignableTo() + .And.Subject.Should().BeOfType() + .Which.Message.Should().Be("Other Message"); - [Fact] - public void When_unrelated_to_open_generic_type_and_asserting_not_assignable_it_should_succeed() - { - // Arrange - var someObject = new DummyImplementingClass(); + // Assert + act.Should().Throw().WithMessage("*Expected*Other*Actual*"); + } - // Act / Assert - someObject.Should().NotBeAssignableTo(typeof(System.Collections.Generic.IList<>), "because we want to test the failure {0}", "message"); - } + [Fact] + public void When_its_own_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().NotBeAssignableTo(typeof(DummyImplementingClass), "because we want to test the failure {0}", "message"); - #endregion + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(DummyImplementingClass)}*failure message*{typeof(DummyImplementingClass)} is*"); + } - #region Miscellaneous + [Fact] + public void When_its_base_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().NotBeAssignableTo(typeof(DummyBaseClass), "because we want to test the failure {0}", "message"); - [Fact] - public void Should_support_chaining_constraints_with_and() - { - // Arrange - var someObject = new Exception(); - - // Act / Assert - someObject.Should() - .BeOfType() - .And - .NotBeNull(); - } + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(DummyBaseClass)}*failure message*{typeof(DummyImplementingClass)} is*"); + } - #endregion + [Fact] + public void When_an_implemented_interface_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() + { + // Arrange + var someObject = new DummyImplementingClass(); + Action act = () => someObject.Should().NotBeAssignableTo(typeof(IDisposable), "because we want to test the failure {0}", "message"); - #region BeBinarySerializable + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(IDisposable)}*failure message*{typeof(DummyImplementingClass)} is*"); + } - [Fact] - public void When_an_object_is_binary_serializable_it_should_succeed() - { - // Arrange - var subject = new SerializableClass + [Fact] + public void When_an_implemented_open_generic_interface_type_instance_and_asserting_not_assignable_it_should_fail_with_a_useful_message() { - Name = "John", - Id = 2 - }; + // Arrange + var someObject = new System.Collections.Generic.List(); + Action act = () => someObject.Should().NotBeAssignableTo(typeof(System.Collections.Generic.IList<>), "because we want to test the failure {0}", "message"); - // Act - Action act = () => subject.Should().BeBinarySerializable(); + // Act / Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(System.Collections.Generic.IList<>)}*failure message*{typeof(System.Collections.Generic.List)} is*"); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_a_null_instance_is_asserted_to_not_be_assignable_it_should_fail_with_a_descriptive_message() + { + // Arrange + object someObject = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someObject.Should().NotBeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage($"*not be assignable to {typeof(DateTime)}*failure message*found *"); + } - [Fact] - public void When_an_object_is_binary_serializable_with_non_serializable_members_it_should_succeed() - { - // Arrange - var subject = new SerializableClassWithNonSerializableMember() + [Fact] + public void When_an_unrelated_type_instance_and_asserting_not_assignable_it_should_succeed() { - Name = "John", - NonSerializable = "Nonserializable value" - }; + // Arrange + var someObject = new DummyImplementingClass(); - // Act - Action act = () => subject.Should().BeBinarySerializable(options => - options.Excluding(s => s.NonSerializable)); + // Act / Assert + someObject.Should().NotBeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message"); + } - // Assert - act.Should().NotThrow(); + [Fact] + public void When_unrelated_to_open_generic_type_and_asserting_not_assignable_it_should_succeed() + { + // Arrange + var someObject = new DummyImplementingClass(); + + // Act / Assert + someObject.Should().NotBeAssignableTo(typeof(System.Collections.Generic.IList<>), "because we want to test the failure {0}", "message"); + } } - [Fact] - public void When_injecting_null_options_it_should_throw() + public class Miscellaneous { - // Arrange - var subject = new SerializableClassWithNonSerializableMember(); - - // Act - Action act = () => subject.Should().BeBinarySerializable(options: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("options"); + [Fact] + public void Should_support_chaining_constraints_with_and() + { + // Arrange + var someObject = new Exception(); + + // Act / Assert + someObject.Should() + .BeOfType() + .And + .NotBeNull(); + } } - [Fact] - public void When_an_object_is_not_binary_serializable_it_should_fail() + public class BeBinarySerializable { - // Arrange - var subject = new UnserializableClass + [Fact] + public void When_an_object_is_binary_serializable_it_should_succeed() { - Name = "John" - }; - - // Act - Action act = () => subject.Should().BeBinarySerializable("we need to store it on {0}", "disk"); + // Arrange + var subject = new SerializableClass + { + Name = "John", + Id = 2 + }; + + // Act + Action act = () => subject.Should().BeBinarySerializable(); + + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw() - .WithMessage("*to be serializable because we need to store it on disk, but serialization failed with:*UnserializableClass*"); - } + [Fact] + public void When_an_object_is_binary_serializable_with_non_serializable_members_it_should_succeed() + { + // Arrange + var subject = new SerializableClassWithNonSerializableMember() + { + Name = "John", + NonSerializable = "Nonserializable value" + }; + + // Act + Action act = () => subject.Should().BeBinarySerializable(options => + options.Excluding(s => s.NonSerializable)); + + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_an_object_is_binary_serializable_but_not_deserializable_it_should_fail() - { - // Arrange - var subject = new BinarySerializableClassMissingDeserializationConstructor + [Fact] + public void When_injecting_null_options_it_should_throw() { - Name = "John", - BirthDay = 20.September(1973) - }; + // Arrange + var subject = new SerializableClassWithNonSerializableMember(); - // Act - Action act = () => subject.Should().BeBinarySerializable(); + // Act + Action act = () => subject.Should().BeBinarySerializable(options: null); - // Assert - act.Should().Throw() - .WithMessage("*to be serializable, but serialization failed with:*BinarySerializableClassMissingDeserializationConstructor*"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("options"); + } - [Fact] - public void When_an_object_is_binary_serializable_but_doesnt_restore_all_properties_it_should_fail() - { - // Arrange - var subject = new BinarySerializableClassNotRestoringAllProperties + [Fact] + public void When_an_object_is_not_binary_serializable_it_should_fail() { - Name = "John", - BirthDay = 20.September(1973) - }; + // Arrange + var subject = new UnserializableClass + { + Name = "John" + }; + + // Act + Action act = () => subject.Should().BeBinarySerializable("we need to store it on {0}", "disk"); + + // Assert + act.Should().Throw() + .WithMessage("*to be serializable because we need to store it on disk, but serialization failed with:*UnserializableClass*"); + } - // Act - Action act = () => subject.Should().BeBinarySerializable(); + [Fact] + public void When_an_object_is_binary_serializable_but_not_deserializable_it_should_fail() + { + // Arrange + var subject = new BinarySerializableClassMissingDeserializationConstructor + { + Name = "John", + BirthDay = 20.September(1973) + }; + + // Act + Action act = () => subject.Should().BeBinarySerializable(); + + // Assert + act.Should().Throw() + .WithMessage("*to be serializable, but serialization failed with:*BinarySerializableClassMissingDeserializationConstructor*"); + } - // Assert - act.Should().Throw() - .WithMessage("*to be serializable, but serialization failed with:*subject.Name*to be*"); - } + [Fact] + public void When_an_object_is_binary_serializable_but_doesnt_restore_all_properties_it_should_fail() + { + // Arrange + var subject = new BinarySerializableClassNotRestoringAllProperties + { + Name = "John", + BirthDay = 20.September(1973) + }; + + // Act + Action act = () => subject.Should().BeBinarySerializable(); + + // Assert + act.Should().Throw() + .WithMessage("*to be serializable, but serialization failed with:*subject.Name*to be*"); + } - [Fact] - public void When_a_system_exception_is_asserted_to_be_serializable_it_should_compare_its_fields_and_properties() - { - // Arrange - var subject = new Exception("some error"); + [Fact] + public void When_a_system_exception_is_asserted_to_be_serializable_it_should_compare_its_fields_and_properties() + { + // Arrange + var subject = new Exception("some error"); - // Act - Action act = () => subject.Should().BeBinarySerializable(); + // Act + Action act = () => subject.Should().BeBinarySerializable(); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - + internal class UnserializableClass { public string Name { get; set; } @@ -1013,61 +1017,60 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("BirthDay", BirthDay); } } - - #endregion - - #region BeXmlSerializable - - [Fact] - public void When_an_object_is_xml_serializable_it_should_succeed() + + public class BeXmlSerializable { - // Arrange - var subject = new XmlSerializableClass + [Fact] + public void When_an_object_is_xml_serializable_it_should_succeed() { - Name = "John", - Id = 1 - }; - - // Act - Action act = () => subject.Should().BeXmlSerializable(); - - // Assert - act.Should().NotThrow(); - } + // Arrange + var subject = new XmlSerializableClass + { + Name = "John", + Id = 1 + }; + + // Act + Action act = () => subject.Should().BeXmlSerializable(); + + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_an_object_is_not_xml_serializable_it_should_fail() - { - // Arrange - var subject = new NonPublicClass + [Fact] + public void When_an_object_is_not_xml_serializable_it_should_fail() { - Name = "John" - }; - - // Act - Action act = () => subject.Should().BeXmlSerializable("we need to store it on {0}", "disk"); - - // Assert - act.Should().Throw() - .WithMessage("*to be serializable because we need to store it on disk, but serialization failed with:*NonPublicClass*"); - } + // Arrange + var subject = new NonPublicClass + { + Name = "John" + }; + + // Act + Action act = () => subject.Should().BeXmlSerializable("we need to store it on {0}", "disk"); + + // Assert + act.Should().Throw() + .WithMessage("*to be serializable because we need to store it on disk, but serialization failed with:*NonPublicClass*"); + } - [Fact] - public void When_an_object_is_xml_serializable_but_doesnt_restore_all_properties_it_should_fail() - { - // Arrange - var subject = new XmlSerializableClassNotRestoringAllProperties + [Fact] + public void When_an_object_is_xml_serializable_but_doesnt_restore_all_properties_it_should_fail() { - Name = "John", - BirthDay = 20.September(1973) - }; - - // Act - Action act = () => subject.Should().BeXmlSerializable(); - - // Assert - act.Should().Throw() - .WithMessage("*to be serializable, but serialization failed with:*Name*to be*"); + // Arrange + var subject = new XmlSerializableClassNotRestoringAllProperties + { + Name = "John", + BirthDay = 20.September(1973) + }; + + // Act + Action act = () => subject.Should().BeXmlSerializable(); + + // Assert + act.Should().Throw() + .WithMessage("*to be serializable, but serialization failed with:*Name*to be*"); + } } internal class NonPublicClass @@ -1104,91 +1107,90 @@ public void WriteXml(XmlWriter writer) } } - #endregion - - #region BeDataContractSerializable - - [Fact] - public void When_an_object_is_data_contract_serializable_it_should_succeed() + public class BeDataContractSerializable { - // Arrange - var subject = new DataContractSerializableClass + [Fact] + public void When_an_object_is_data_contract_serializable_it_should_succeed() { - Name = "John", - Id = 1 - }; - - // Act - Action act = () => subject.Should().BeDataContractSerializable(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_object_is_not_data_contract_serializable_it_should_fail() - { - // Arrange - var subject = new NonDataContractSerializableClass(); - - // Act - Action act = () => subject.Should().BeDataContractSerializable("we need to store it on {0}", "disk"); - - // Assert - act - .Should().Throw() - .WithMessage("*we need to store it on disk*EnumMemberAttribute*"); - } + // Arrange + var subject = new DataContractSerializableClass + { + Name = "John", + Id = 1 + }; + + // Act + Action act = () => subject.Should().BeDataContractSerializable(); + + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_an_object_is_data_contract_serializable_but_doesnt_restore_all_properties_it_should_fail() - { - // Arrange - var subject = new DataContractSerializableClassNotRestoringAllProperties + [Fact] + public void When_an_object_is_not_data_contract_serializable_it_should_fail() { - Name = "John", - BirthDay = 20.September(1973) - }; + // Arrange + var subject = new NonDataContractSerializableClass(); - // Act - Action act = () => subject.Should().BeDataContractSerializable(); + // Act + Action act = () => subject.Should().BeDataContractSerializable("we need to store it on {0}", "disk"); - // Assert - act.Should().Throw() - .WithMessage("*to be serializable, but serialization failed with:*property subject.Name*to be*"); - } + // Assert + act + .Should().Throw() + .WithMessage("*we need to store it on disk*EnumMemberAttribute*"); + } - [Fact] - public void When_a_data_contract_serializable_object_doesnt_restore_an_ignored_property_it_should_succeed() - { - // Arrange - var subject = new DataContractSerializableClassNotRestoringAllProperties + [Fact] + public void When_an_object_is_data_contract_serializable_but_doesnt_restore_all_properties_it_should_fail() { - Name = "John", - BirthDay = 20.September(1973) - }; - - // Act - Action act = () => subject.Should().BeDataContractSerializable( - options => options.Excluding(x => x.Name)); + // Arrange + var subject = new DataContractSerializableClassNotRestoringAllProperties + { + Name = "John", + BirthDay = 20.September(1973) + }; + + // Act + Action act = () => subject.Should().BeDataContractSerializable(); + + // Assert + act.Should().Throw() + .WithMessage("*to be serializable, but serialization failed with:*property subject.Name*to be*"); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_a_data_contract_serializable_object_doesnt_restore_an_ignored_property_it_should_succeed() + { + // Arrange + var subject = new DataContractSerializableClassNotRestoringAllProperties + { + Name = "John", + BirthDay = 20.September(1973) + }; + + // Act + Action act = () => subject.Should().BeDataContractSerializable( + options => options.Excluding(x => x.Name)); + + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_injecting_null_options_to_BeDataContractSerializable_it_should_throw() - { - // Arrange - var subject = new DataContractSerializableClassNotRestoringAllProperties(); + [Fact] + public void When_injecting_null_options_to_BeDataContractSerializable_it_should_throw() + { + // Arrange + var subject = new DataContractSerializableClassNotRestoringAllProperties(); - // Act - Action act = () => subject.Should().BeDataContractSerializable( - options: null); + // Act + Action act = () => subject.Should().BeDataContractSerializable( + options: null); - // Assert - act.Should().ThrowExactly() - .WithParameterName("options"); + // Assert + act.Should().ThrowExactly() + .WithParameterName("options"); + } } public enum Color @@ -1217,9 +1219,6 @@ public class DataContractSerializableClassNotRestoringAllProperties [DataMember] public DateTime BirthDay { get; set; } } - - #endregion - } internal class DummyBaseClass From cdbab6bad3a013cf3580ac0c55548a0b7aecb06f Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:10:54 +0200 Subject: [PATCH 23/48] NUKE 6.0.1 -> 6.0.2 --- Build/_build.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/_build.csproj b/Build/_build.csproj index 14a1ece568..7982cfa62a 100644 --- a/Build/_build.csproj +++ b/Build/_build.csproj @@ -12,6 +12,6 @@ - + From ff232900008e319417015f28605dae61df659a0c Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:12:28 +0200 Subject: [PATCH 24/48] ReportGenerator 5.1.3 -> 5.1.4 --- Build/_build.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/_build.csproj b/Build/_build.csproj index 7982cfa62a..b9da9d8e1c 100644 --- a/Build/_build.csproj +++ b/Build/_build.csproj @@ -10,7 +10,7 @@ - + From 05706d405d1fa94df988a0ad756b6938060e7e29 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:12:52 +0200 Subject: [PATCH 25/48] GitVersion.Tool 5.9.0 -> 5.10.1 --- Build/_build.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/_build.csproj b/Build/_build.csproj index b9da9d8e1c..b3394d14d5 100644 --- a/Build/_build.csproj +++ b/Build/_build.csproj @@ -8,7 +8,7 @@ ..\ - + From 6fecad6464c249f8841cfb065c0069f8a5fee7b4 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:14:47 +0200 Subject: [PATCH 26/48] JetBrains.Annotations 2021.3.0 -> 2022.1.0 --- Src/FluentAssertions/FluentAssertions.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/FluentAssertions/FluentAssertions.csproj b/Src/FluentAssertions/FluentAssertions.csproj index 9c82594817..c13a513dc3 100644 --- a/Src/FluentAssertions/FluentAssertions.csproj +++ b/Src/FluentAssertions/FluentAssertions.csproj @@ -54,7 +54,7 @@ - + From aa9e05ed8cbafb9ddc6268d26e2bf1ad2b744241 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:15:55 +0200 Subject: [PATCH 27/48] Verify.Xunit 16.4.4 -> 16.5.4 --- Tests/Approval.Tests/Approval.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Approval.Tests/Approval.Tests.csproj b/Tests/Approval.Tests/Approval.Tests.csproj index 79005a9c42..650f89992a 100644 --- a/Tests/Approval.Tests/Approval.Tests.csproj +++ b/Tests/Approval.Tests/Approval.Tests.csproj @@ -13,7 +13,7 @@ - + From 293cabaaa85c36f7459e8f19486016dc7772043c Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:17:36 +0200 Subject: [PATCH 28/48] Bogus 34.0.1 -> 34.0.2 --- Tests/Benchmarks/Benchmarks.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Benchmarks/Benchmarks.csproj b/Tests/Benchmarks/Benchmarks.csproj index 21ecd9e546..b557deed67 100644 --- a/Tests/Benchmarks/Benchmarks.csproj +++ b/Tests/Benchmarks/Benchmarks.csproj @@ -11,7 +11,7 @@ - + From b7d63c02cf705f13aef6f568c84f29c615596455 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 18:17:51 +0200 Subject: [PATCH 29/48] MSTest 2.2.8 -> 2.2.9 --- Tests/TestFrameworks/MSTestV2.Specs/MSTestV2.Specs.csproj | 4 ++-- Tests/UWP.Specs/UWP.Specs.csproj | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/TestFrameworks/MSTestV2.Specs/MSTestV2.Specs.csproj b/Tests/TestFrameworks/MSTestV2.Specs/MSTestV2.Specs.csproj index 8862ec11d1..fc7b7d0805 100644 --- a/Tests/TestFrameworks/MSTestV2.Specs/MSTestV2.Specs.csproj +++ b/Tests/TestFrameworks/MSTestV2.Specs/MSTestV2.Specs.csproj @@ -13,7 +13,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - + + \ No newline at end of file diff --git a/Tests/UWP.Specs/UWP.Specs.csproj b/Tests/UWP.Specs/UWP.Specs.csproj index 45a4d06107..faa2f209b5 100644 --- a/Tests/UWP.Specs/UWP.Specs.csproj +++ b/Tests/UWP.Specs/UWP.Specs.csproj @@ -87,10 +87,10 @@ 6.2.13 - 2.2.8 + 2.2.9 - 2.2.8 + 2.2.9 4.3.0 From 0aa74174fef7cc8685eaf3cce981eb8e0bbec272 Mon Sep 17 00:00:00 2001 From: Rob Date: Tue, 19 Apr 2022 20:00:27 +0200 Subject: [PATCH 30/48] Cleanup README.md (#1905) * Cleanup README.md * Removed duplicate dot --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index eb819e72ce..c052de024c 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,7 @@ Install Visual Studio 2022 17.0+ or JetBrains Rider 2021.3 as well as the Build # What are these Approval.Tests? This is a special set of tests that use the [Verify](https://github.com/VerifyTests/Verify) project to verify whether you've introduced any breaking changes in the public API of the library. -If you've verified the changes and decided they are valid, you can accept them using `AcceptApiChanges.ps1` or `AcceptApiChanges.sh`. Alternatively, you can use the [Verify Support](https://plugins.jetbrains.com/plugin/17240-verify-support) plug-in to compare the changes and accept them right from inside Rider. See also the [Contribution Guidelines.](CONTRIBUTING.md). - -`build.ps1` +If you've verified the changes and decided they are valid, you can accept them using `AcceptApiChanges.ps1` or `AcceptApiChanges.sh`. Alternatively, you can use the [Verify Support](https://plugins.jetbrains.com/plugin/17240-verify-support) plug-in to compare the changes and accept them right from inside Rider. See also the [Contribution Guidelines](CONTRIBUTING.md). # Powered By
and
From 37a241bf21395a8356226b68ca17b28b810207ad Mon Sep 17 00:00:00 2001 From: Oliver Date: Wed, 20 Apr 2022 20:10:21 +0200 Subject: [PATCH 31/48] Add `For`/`Exclude` to allow exclusion of members inside a collection (#1782) --- Src/FluentAssertions/Common/MemberPath.cs | 24 +- .../MemberPathSegmentEqualityComparer.cs | 49 +++ .../EquivalencyAssertionOptions.cs | 12 +- .../NestedExclusionOptionBuilder.cs | 46 +++ .../ExcludeMemberByPathSelectionRule.cs | 8 +- .../SelectMemberByPathSelectionRule.cs | 7 +- .../FluentAssertions/net47.verified.txt | 6 + .../FluentAssertions/net6.0.verified.txt | 6 + .../netcoreapp2.1.verified.txt | 6 + .../netcoreapp3.0.verified.txt | 6 + .../netstandard2.0.verified.txt | 6 + .../netstandard2.1.verified.txt | 6 + .../CollectionSpecs.cs | 367 ++++++++++++++++++ docs/_pages/objectgraphs.md | 17 + docs/_pages/releases.md | 1 + 15 files changed, 558 insertions(+), 9 deletions(-) create mode 100644 Src/FluentAssertions/Common/MemberPathSegmentEqualityComparer.cs create mode 100644 Src/FluentAssertions/Equivalency/NestedExclusionOptionBuilder.cs diff --git a/Src/FluentAssertions/Common/MemberPath.cs b/Src/FluentAssertions/Common/MemberPath.cs index 505f7f0ab6..5d62ddf12f 100644 --- a/Src/FluentAssertions/Common/MemberPath.cs +++ b/Src/FluentAssertions/Common/MemberPath.cs @@ -17,6 +17,8 @@ internal class MemberPath private string[] segments; + private static readonly MemberPathSegmentEqualityComparer MemberPathSegmentEqualityComparer = new(); + public MemberPath(IMember member, string parentPath) : this(member.ReflectedType, member.DeclaringType, parentPath.Combine(member.Name)) { @@ -53,7 +55,7 @@ public bool IsSameAs(MemberPath candidate) { string[] candidateSegments = candidate.Segments; - return candidateSegments.SequenceEqual(Segments); + return candidateSegments.SequenceEqual(Segments, MemberPathSegmentEqualityComparer); } return false; @@ -64,7 +66,7 @@ private bool IsParentOf(MemberPath candidate) string[] candidateSegments = candidate.Segments; return candidateSegments.Length > Segments.Length && - candidateSegments.Take(Segments.Length).SequenceEqual(Segments); + candidateSegments.Take(Segments.Length).SequenceEqual(Segments, MemberPathSegmentEqualityComparer); } private bool IsChildOf(MemberPath candidate) @@ -72,7 +74,14 @@ private bool IsChildOf(MemberPath candidate) string[] candidateSegments = candidate.Segments; return candidateSegments.Length < Segments.Length - && candidateSegments.SequenceEqual(Segments.Take(candidateSegments.Length)); + && candidateSegments.SequenceEqual(Segments.Take(candidateSegments.Length), + MemberPathSegmentEqualityComparer); + } + + public MemberPath AsParentCollectionOf(MemberPath nextPath) + { + var extendedDottedPath = dottedPath.Combine(nextPath.dottedPath, "[]"); + return new MemberPath(declaringType, nextPath.reflectedType, extendedDottedPath); } /// @@ -86,7 +95,7 @@ public bool IsEquivalentTo(string path) public bool HasSameParentAs(MemberPath path) { return Segments.Length == path.Segments.Length - && GetParentSegments().SequenceEqual(path.GetParentSegments()); + && GetParentSegments().SequenceEqual(path.GetParentSegments(), MemberPathSegmentEqualityComparer); } private IEnumerable GetParentSegments() => Segments.Take(Segments.Length - 1); @@ -96,6 +105,11 @@ public bool HasSameParentAs(MemberPath path) /// public bool GetContainsSpecificCollectionIndex() => dottedPath.ContainsSpecificCollectionIndex(); + private string[] Segments => + segments ??= dottedPath + .Replace("[]", "[*]", StringComparison.Ordinal) + .Split(new[] { '.', '[', ']' }, StringSplitOptions.RemoveEmptyEntries); + /// /// Returns a copy of the current object as if it represented an un-indexed item in a collection. /// @@ -104,8 +118,6 @@ public MemberPath WithCollectionAsRoot() return new MemberPath(reflectedType, declaringType, "[]." + dottedPath); } - private string[] Segments => segments ??= dottedPath.Split(new[] { '.', '[', ']' }, StringSplitOptions.RemoveEmptyEntries); - /// /// Returns the name of the member the current path points to without its parent path. /// diff --git a/Src/FluentAssertions/Common/MemberPathSegmentEqualityComparer.cs b/Src/FluentAssertions/Common/MemberPathSegmentEqualityComparer.cs new file mode 100644 index 0000000000..10c1a43215 --- /dev/null +++ b/Src/FluentAssertions/Common/MemberPathSegmentEqualityComparer.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace FluentAssertions.Common +{ + /// + /// Compares two segments of a . + /// Sets the equal with any numeric index qualifier. + /// All other comparisons are default string equality. + /// + internal class MemberPathSegmentEqualityComparer : IEqualityComparer + { + private const string AnyIndexQualifier = "*"; + private static readonly Regex IndexQualifierRegex = new(@"^\d+$"); + + /// + /// Compares two segments of a . + /// + /// Left part of the comparison. + /// Right part of the comparison. + /// True if segments are equal, false if not. + public bool Equals(string x, string y) + { + if (x == AnyIndexQualifier) + { + return IsIndexQualifier(y); + } + + if (y == AnyIndexQualifier) + { + return IsIndexQualifier(x); + } + + return x == y; + } + + private static bool IsIndexQualifier(string segment) + => segment == AnyIndexQualifier || IndexQualifierRegex.IsMatch(segment); + + public int GetHashCode(string obj) + { +#if NETCOREAPP2_1_OR_GREATER + return obj.GetHashCode(System.StringComparison.Ordinal); +#else + return obj.GetHashCode(); +#endif + } + } +} diff --git a/Src/FluentAssertions/Equivalency/EquivalencyAssertionOptions.cs b/Src/FluentAssertions/Equivalency/EquivalencyAssertionOptions.cs index 0b16cdf241..14fbc86abc 100644 --- a/Src/FluentAssertions/Equivalency/EquivalencyAssertionOptions.cs +++ b/Src/FluentAssertions/Equivalency/EquivalencyAssertionOptions.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using FluentAssertions.Common; using FluentAssertions.Equivalency.Execution; @@ -40,6 +39,17 @@ public EquivalencyAssertionOptions Excluding(Expression + /// Selects a collection to define exclusions at. + /// Allows to navigate deeper by using . + /// + public NestedExclusionOptionBuilder For(Expression>> expression) + { + var selectionRule = new ExcludeMemberByPathSelectionRule(expression.GetMemberPath()); + AddSelectionRule(selectionRule); + return new NestedExclusionOptionBuilder(this, selectionRule); + } + /// /// Includes the specified member in the equality check. /// diff --git a/Src/FluentAssertions/Equivalency/NestedExclusionOptionBuilder.cs b/Src/FluentAssertions/Equivalency/NestedExclusionOptionBuilder.cs new file mode 100644 index 0000000000..02821424f1 --- /dev/null +++ b/Src/FluentAssertions/Equivalency/NestedExclusionOptionBuilder.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using FluentAssertions.Common; +using FluentAssertions.Equivalency.Selection; + +namespace FluentAssertions.Equivalency +{ + public class NestedExclusionOptionBuilder + { + /// + /// The selected path starting at the first . + /// + private readonly ExcludeMemberByPathSelectionRule currentPathSelectionRule; + + private readonly EquivalencyAssertionOptions capturedAssertionOptions; + + internal NestedExclusionOptionBuilder(EquivalencyAssertionOptions capturedAssertionOptions, + ExcludeMemberByPathSelectionRule currentPathSelectionRule) + { + this.capturedAssertionOptions = capturedAssertionOptions; + this.currentPathSelectionRule = currentPathSelectionRule; + } + + /// + /// Selects a nested property to exclude. This ends the chain. + /// + public EquivalencyAssertionOptions Exclude(Expression> expression) + { + var nextPath = expression.GetMemberPath(); + currentPathSelectionRule.AppendPath(nextPath); + return capturedAssertionOptions; + } + + /// + /// Adds the selected collection to the chain. + /// + public NestedExclusionOptionBuilder For( + Expression>> expression) + { + var nextPath = expression.GetMemberPath(); + currentPathSelectionRule.AppendPath(nextPath); + return new NestedExclusionOptionBuilder(capturedAssertionOptions, currentPathSelectionRule); + } + } +} diff --git a/Src/FluentAssertions/Equivalency/Selection/ExcludeMemberByPathSelectionRule.cs b/Src/FluentAssertions/Equivalency/Selection/ExcludeMemberByPathSelectionRule.cs index 3b4c263837..0d68882444 100644 --- a/Src/FluentAssertions/Equivalency/Selection/ExcludeMemberByPathSelectionRule.cs +++ b/Src/FluentAssertions/Equivalency/Selection/ExcludeMemberByPathSelectionRule.cs @@ -8,7 +8,7 @@ namespace FluentAssertions.Equivalency.Selection /// internal class ExcludeMemberByPathSelectionRule : SelectMemberByPathSelectionRule { - private readonly MemberPath memberToExclude; + private MemberPath memberToExclude; public ExcludeMemberByPathSelectionRule(MemberPath pathToExclude) : base(pathToExclude.ToString()) @@ -23,6 +23,12 @@ public ExcludeMemberByPathSelectionRule(MemberPath pathToExclude) memberToExclude.IsSameAs(new MemberPath(member, parentPath))); } + public void AppendPath(MemberPath nextPath) + { + memberToExclude = memberToExclude.AsParentCollectionOf(nextPath); + SetSelectedPath(memberToExclude.ToString()); + } + public override string ToString() { return "Exclude member " + memberToExclude; diff --git a/Src/FluentAssertions/Equivalency/Selection/SelectMemberByPathSelectionRule.cs b/Src/FluentAssertions/Equivalency/Selection/SelectMemberByPathSelectionRule.cs index 8a32b13ea3..753b59818a 100644 --- a/Src/FluentAssertions/Equivalency/Selection/SelectMemberByPathSelectionRule.cs +++ b/Src/FluentAssertions/Equivalency/Selection/SelectMemberByPathSelectionRule.cs @@ -7,7 +7,7 @@ namespace FluentAssertions.Equivalency.Selection { internal abstract class SelectMemberByPathSelectionRule : IMemberSelectionRule { - private readonly string selectedPath; + private string selectedPath; protected SelectMemberByPathSelectionRule(string selectedPath) { @@ -16,6 +16,11 @@ protected SelectMemberByPathSelectionRule(string selectedPath) public virtual bool IncludesMembers => false; + protected void SetSelectedPath(string path) + { + this.selectedPath = path; + } + public IEnumerable SelectMembers(INode currentNode, IEnumerable selectedMembers, MemberSelectionContext context) { diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt index 8e6e5e5a1d..a86a4adf5e 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt @@ -791,6 +791,7 @@ namespace FluentAssertions.Equivalency public EquivalencyAssertionOptions(FluentAssertions.Equivalency.IEquivalencyAssertionOptions defaults) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions> AsCollection() { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Excluding(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Including(System.Linq.Expressions.Expression> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(string expectationMemberPath, string subjectMemberPath) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(System.Linq.Expressions.Expression> expectationMemberPath, System.Linq.Expressions.Expression> subjectMemberPath) { } @@ -959,6 +960,11 @@ namespace FluentAssertions.Equivalency Internal = 1, Public = 2, } + public class NestedExclusionOptionBuilder + { + public FluentAssertions.Equivalency.EquivalencyAssertionOptions Exclude(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } + } public class Node : FluentAssertions.Equivalency.INode { public Node() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt index 48dce352e8..45386470fb 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt @@ -803,6 +803,7 @@ namespace FluentAssertions.Equivalency public EquivalencyAssertionOptions(FluentAssertions.Equivalency.IEquivalencyAssertionOptions defaults) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions> AsCollection() { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Excluding(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Including(System.Linq.Expressions.Expression> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(string expectationMemberPath, string subjectMemberPath) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(System.Linq.Expressions.Expression> expectationMemberPath, System.Linq.Expressions.Expression> subjectMemberPath) { } @@ -971,6 +972,11 @@ namespace FluentAssertions.Equivalency Internal = 1, Public = 2, } + public class NestedExclusionOptionBuilder + { + public FluentAssertions.Equivalency.EquivalencyAssertionOptions Exclude(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } + } public class Node : FluentAssertions.Equivalency.INode { public Node() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt index e0c1d1a59c..32f7082f3f 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt @@ -791,6 +791,7 @@ namespace FluentAssertions.Equivalency public EquivalencyAssertionOptions(FluentAssertions.Equivalency.IEquivalencyAssertionOptions defaults) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions> AsCollection() { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Excluding(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Including(System.Linq.Expressions.Expression> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(string expectationMemberPath, string subjectMemberPath) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(System.Linq.Expressions.Expression> expectationMemberPath, System.Linq.Expressions.Expression> subjectMemberPath) { } @@ -959,6 +960,11 @@ namespace FluentAssertions.Equivalency Internal = 1, Public = 2, } + public class NestedExclusionOptionBuilder + { + public FluentAssertions.Equivalency.EquivalencyAssertionOptions Exclude(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } + } public class Node : FluentAssertions.Equivalency.INode { public Node() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt index 48cf7bfda4..cd16c72a15 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt @@ -791,6 +791,7 @@ namespace FluentAssertions.Equivalency public EquivalencyAssertionOptions(FluentAssertions.Equivalency.IEquivalencyAssertionOptions defaults) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions> AsCollection() { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Excluding(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Including(System.Linq.Expressions.Expression> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(string expectationMemberPath, string subjectMemberPath) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(System.Linq.Expressions.Expression> expectationMemberPath, System.Linq.Expressions.Expression> subjectMemberPath) { } @@ -959,6 +960,11 @@ namespace FluentAssertions.Equivalency Internal = 1, Public = 2, } + public class NestedExclusionOptionBuilder + { + public FluentAssertions.Equivalency.EquivalencyAssertionOptions Exclude(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } + } public class Node : FluentAssertions.Equivalency.INode { public Node() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt index 80b123a3d3..e7ef120517 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt @@ -784,6 +784,7 @@ namespace FluentAssertions.Equivalency public EquivalencyAssertionOptions(FluentAssertions.Equivalency.IEquivalencyAssertionOptions defaults) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions> AsCollection() { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Excluding(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Including(System.Linq.Expressions.Expression> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(string expectationMemberPath, string subjectMemberPath) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(System.Linq.Expressions.Expression> expectationMemberPath, System.Linq.Expressions.Expression> subjectMemberPath) { } @@ -952,6 +953,11 @@ namespace FluentAssertions.Equivalency Internal = 1, Public = 2, } + public class NestedExclusionOptionBuilder + { + public FluentAssertions.Equivalency.EquivalencyAssertionOptions Exclude(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } + } public class Node : FluentAssertions.Equivalency.INode { public Node() { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt index 618a9a052d..f17275a93c 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt @@ -791,6 +791,7 @@ namespace FluentAssertions.Equivalency public EquivalencyAssertionOptions(FluentAssertions.Equivalency.IEquivalencyAssertionOptions defaults) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions> AsCollection() { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Excluding(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions Including(System.Linq.Expressions.Expression> expression) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(string expectationMemberPath, string subjectMemberPath) { } public FluentAssertions.Equivalency.EquivalencyAssertionOptions WithMapping(System.Linq.Expressions.Expression> expectationMemberPath, System.Linq.Expressions.Expression> subjectMemberPath) { } @@ -959,6 +960,11 @@ namespace FluentAssertions.Equivalency Internal = 1, Public = 2, } + public class NestedExclusionOptionBuilder + { + public FluentAssertions.Equivalency.EquivalencyAssertionOptions Exclude(System.Linq.Expressions.Expression> expression) { } + public FluentAssertions.Equivalency.NestedExclusionOptionBuilder For(System.Linq.Expressions.Expression>> expression) { } + } public class Node : FluentAssertions.Equivalency.INode { public Node() { } diff --git a/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs index 6e228e27d1..0d5856bec0 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/CollectionSpecs.cs @@ -558,6 +558,373 @@ public void When_a_deeply_nested_property_of_a_collection_with_an_invalid_value_ act.Should().NotThrow(); } + public class For + { + [Fact] + public void When_property_in_collection_is_excluded_it_should_not_throw() + { + // Arrange + var subject = new + { + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 2, + Text = "Actual" + } + } + } + }; + + var expected = new + { + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 3, + Text = "Actual" + } + } + } + }; + + // Act / Assert + subject.Should().BeEquivalentTo(expected, + options => options + .For(x => x.Level.Collection) + .Exclude(x => x.Number)); + } + + [Fact] + public void When_collection_in_collection_is_excluded_it_should_not_throw() + { + // Arrange + var subject = new + { + Level = new + { + Collection = new[] + { + new + { + Number = 1, + NextCollection = new[] + { + new + { + Text = "Text" + } + } + }, + new + { + Number = 2, + NextCollection = new[] + { + new + { + Text = "Actual" + } + } + } + } + } + }; + + var expected = new + { + Level = new + { + Collection = new[] + { + new + { + Number = 1, + NextCollection = new[] + { + new + { + Text = "Text" + } + } + }, + new + { + Number = 2, + NextCollection = new[] + { + new + { + Text = "Expected" + } + } + } + } + } + }; + + // Act / Assert + subject.Should().BeEquivalentTo(expected, + options => options + .For(x => x.Level.Collection) + .Exclude(x => x.NextCollection)); + } + + [Fact] + public void When_property_in_collection_in_collection_is_excluded_it_should_not_throw() + { + // Arrange + var subject = new + { + Text = "Text", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + NextCollection = new[] + { + new + { + Text = "Text" + } + } + }, + new + { + Number = 2, + NextCollection = new[] + { + new + { + Text = "Actual" + } + } + } + } + } + }; + + var expected = new + { + Text = "Text", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + NextCollection = new[] + { + new + { + Text = "Text" + } + } + }, + new + { + Number = 2, + NextCollection = new[] + { + new + { + Text = "Expected" + } + } + } + } + } + }; + + // Act / Assert + subject.Should().BeEquivalentTo(expected, + options => options + .For(x => x.Level.Collection) + .For(x => x.NextCollection) + .Exclude(x => x.Text) + ); + } + + [Fact] + public void A_nested_exclusion_can_be_followed_by_a_root_level_exclusion() + { + // Arrange + var subject = new + { + Text = "Actual", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 2, + Text = "Actual" + } + } + } + }; + + var expected = new + { + Text = "Expected", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 2, + Text = "Expected" + } + } + } + }; + + // Act / Assert + subject.Should().BeEquivalentTo(expected, + options => options + .For(x => x.Level.Collection).Exclude(x => x.Text) + .Excluding(x => x.Text)); + } + + [Fact] + public void A_nested_exclusion_can_be_preceded_by_a_root_level_exclusion() + { + // Arrange + var subject = new + { + Text = "Actual", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 2, + Text = "Actual" + } + } + } + }; + + var expected = new + { + Text = "Expected", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 2, + Text = "Expected" + } + } + } + }; + + // Act / Assert + subject.Should().BeEquivalentTo(expected, + options => options + .Excluding(x => x.Text) + .For(x => x.Level.Collection).Exclude(x => x.Text)); + } + + [Fact] + public void A_nested_exclusion_can_be_followed_by_a_nested_exclusion() + { + // Arrange + var subject = new + { + Text = "Actual", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 2, + Text = "Actual" + } + } + } + }; + + var expected = new + { + Text = "Actual", + Level = new + { + Collection = new[] + { + new + { + Number = 1, + Text = "Text" + }, + new + { + Number = 3, + Text = "Expected" + } + } + } + }; + + // Act / Assert + subject.Should().BeEquivalentTo(expected, + options => options + .For(x => x.Level.Collection).Exclude(x => x.Text) + .For(x => x.Level.Collection).Exclude(x => x.Number)); + } + } + [Fact] public void When_a_dictionary_property_is_detected_it_should_ignore_the_order_of_the_pairs() { diff --git a/docs/_pages/objectgraphs.md b/docs/_pages/objectgraphs.md index a21abb76ed..fc37bf3496 100644 --- a/docs/_pages/objectgraphs.md +++ b/docs/_pages/objectgraphs.md @@ -130,6 +130,23 @@ orderDto.Should().BeEquivalentTo(order, options => options.Excluding(o => o.Products[1].Status)); ``` +You can use `For` and `Exclude` if you want to exclude a member on each nested object regardless of its index. + +```csharp +orderDto.Should().BeEquivalentTo(order, options => + options.For(o => o.Products) + .Exclude(o => o.Status)); +``` + +Using `For` you can navigate arbitrarily deep. Consider a `Product` has a collection of `Part`s and a `Part` has a name. Using `For` your can also exclude the `Name` of all `Part`s of all `Product`s. + +```csharp +orderDto.Should().BeEquivalentTo(order, options => + options.For(o => o.Products) + .For(o => o.Parts) + .Exclude(o => o.Name)); +``` + Of course, `Excluding()` and `ExcludingMissingMembers()` can be combined. You can also take a different approach and explicitly tell Fluent Assertions which members to include. You can directly specify a property expression or use a predicate that acts on the provided `ISubjectInfo`. diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index ff728d4bb2..4953f2f24f 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -13,6 +13,7 @@ sidebar: * Add `BeDefined` and `NotBeDefined` to assert on existence of an enum value - [#1888](https://github.com/fluentassertions/fluentassertions/pull/1888) * Added the ability to exclude fields & properties marked as non-browsable in the code editor from structural equality comparisons - [#1807](https://github.com/fluentassertions/fluentassertions/pull/1807) & [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) * Assertions on the collection types in System.Data (`DataSet.Tables`, `DataTable.Columns`, `DataTable.Rows`) have been restored - [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) +* Add `For`/`Exclude` to allow exclusion of members inside a collection - [#1782](https://github.com/fluentassertions/fluentassertions/pull/1782) ## 6.6.0 From d6b2d52b8c0f720a760056ee141c17241e924ce3 Mon Sep 17 00:00:00 2001 From: IT-VBFK <49762557+IT-VBFK@users.noreply.github.com> Date: Wed, 20 Apr 2022 20:12:08 +0200 Subject: [PATCH 32/48] Seperate all `string` assertions into nested classes (#1903) --- .../Primitives/StringAssertionSpecs.Be.cs | 520 +++++----- .../StringAssertionSpecs.BeEmpty.cs | 198 ++-- .../StringAssertionSpecs.BeEquivalentTo.cs | 368 ++++--- .../StringAssertionSpecs.BeLowerCased.cs | 264 +++--- .../StringAssertionSpecs.BeNullOrEmpty.cs | 146 ++- ...StringAssertionSpecs.BeNullOrWhiteSpace.cs | 126 ++- .../StringAssertionSpecs.BeOneOf.cs | 83 +- .../StringAssertionSpecs.BeUpperCased.cs | 244 +++-- .../StringAssertionSpecs.Contain.cs | 897 +++++++++--------- .../StringAssertionSpecs.ContainAll.cs | 456 +++++---- .../StringAssertionSpecs.ContainAny.cs | 453 +++++---- ...tringAssertionSpecs.ContainEquivalentOf.cs | 849 ++++++++--------- .../StringAssertionSpecs.EndWith.cs | 288 +++--- ...tringAssertionSpecs.EndWithEquivalentOf.cs | 278 +++--- .../StringAssertionSpecs.HaveLength.cs | 85 +- .../Primitives/StringAssertionSpecs.Match.cs | 316 +++--- .../StringAssertionSpecs.MatchEquivalentOf.cs | 288 +++--- .../StringAssertionSpecs.MatchRegex.cs | 868 +++++++++-------- .../StringAssertionSpecs.StartWith.cs | 314 +++--- ...ingAssertionSpecs.StartWithEquivalentOf.cs | 314 +++--- 20 files changed, 3654 insertions(+), 3701 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Be.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Be.cs index 0e107470f2..cc752c1f95 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Be.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Be.cs @@ -9,271 +9,269 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be - - [Fact] - public void When_both_values_are_the_same_it_should_not_throw() - { - // Act / Assert - "ABC".Should().Be("ABC"); - } - - [Fact] - public void When_both_subject_and_expected_are_null_it_should_succeed() - { - // Arrange - string actualString = null; - string expectedString = null; - - // Act - Action act = () => actualString.Should().Be(expectedString); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_two_strings_differ_unexpectedly_it_should_throw() + public class Be { - // Act - Action act = () => "ADC".Should().Be("ABC", "because we {0}", "do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be \"ABC\" because we do, but \"ADC\" differs near \"DC\" (index 1)."); + [Fact] + public void When_both_values_are_the_same_it_should_not_throw() + { + // Act / Assert + "ABC".Should().Be("ABC"); + } + + [Fact] + public void When_both_subject_and_expected_are_null_it_should_succeed() + { + // Arrange + string actualString = null; + string expectedString = null; + + // Act + Action act = () => actualString.Should().Be(expectedString); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_two_strings_differ_unexpectedly_it_should_throw() + { + // Act + Action act = () => "ADC".Should().Be("ABC", "because we {0}", "do"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be \"ABC\" because we do, but \"ADC\" differs near \"DC\" (index 1)."); + } + + [Fact] + public void When_two_strings_differ_unexpectedly_containing_double_curly_closing_braces_it_should_throw() + { + // Act + const string expect = "}}"; + const string actual = "}}}}"; + Action act = () => actual.Should().Be(expect); + + // Assert + act.Should().Throw().WithMessage( + "*to be \"}}\" with a length of 2, but \"}}}}\" has a length of 4*"); + } + + [Fact] + public void When_two_strings_differ_unexpectedly_containing_double_curly_opening_braces_it_should_throw() + { + // Act + const string expect = "{{"; + const string actual = "{{{{"; + Action act = () => actual.Should().Be(expect); + + // Assert + act.Should().Throw().WithMessage( + "*to be \"{{\" with a length of 2, but \"{{{{\" has a length of 4*"); + } + + [Fact] + public void When_the_expected_string_is_shorter_than_the_actual_string_it_should_throw() + { + // Act + Action act = () => "ABC".Should().Be("AB"); + + // Assert + act.Should().Throw().WithMessage("*index 2*"); + } + + [Fact] + public void When_the_expected_string_is_longer_than_the_actual_string_it_should_throw() + { + // Act + Action act = () => "AB".Should().Be("ABC"); + + // Assert + act.Should().Throw().WithMessage("*index 1*"); + } + + [Fact] + public void When_the_expected_string_is_empty_it_should_throw() + { + // Act + Action act = () => "ABC".Should().Be(""); + + // Assert + act.Should().Throw().WithMessage("*index 0*"); + } + + [Fact] + public void When_the_subject_string_is_empty_it_should_throw() + { + // Act + Action act = () => "".Should().Be("ABC"); + + // Assert + act.Should().Throw().WithMessage("*index 0*"); + } + + [Fact] + public void When_string_is_expected_to_equal_null_it_should_throw() + { + // Act + Action act = () => "AB".Should().Be(null); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be , but found \"AB\"."); + } + + [Fact] + public void When_string_is_expected_to_be_null_it_should_throw() + { + // Act + Action act = () => "AB".Should().BeNull("we like {0}", "null"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be because we like null, but found \"AB\"."); + } + + [Fact] + public void When_the_expected_string_is_null_then_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().Be("ABC"); + + // Assert + act.Should().Throw().WithMessage( + "Expected someString to be \"ABC\", but found ."); + } + + [Fact] + public void When_the_expected_string_is_the_same_but_with_trailing_spaces_it_should_throw_with_clear_error_message() + { + // Act + Action act = () => "ABC".Should().Be("ABC ", "because I say {0}", "so"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be \"ABC \" because I say so, but it misses some extra whitespace at the end."); + } + + [Fact] + public void When_the_actual_string_is_the_same_as_the_expected_but_with_trailing_spaces_it_should_throw_with_clear_error_message() + { + // Act + Action act = () => "ABC ".Should().Be("ABC", "because I say {0}", "so"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be \"ABC\" because I say so, but it has unexpected whitespace at the end."); + } + + [Fact] + public void When_two_strings_differ_and_one_of_them_is_long_it_should_display_both_strings_on_separate_line() + { + // Act + Action act = () => "1234567890".Should().Be("0987654321"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be*\"0987654321\", but*\"1234567890\" differs near \"123\" (index 0)."); + } + + [Fact] + public void When_two_strings_differ_and_one_of_them_is_multiline_it_should_display_both_strings_on_separate_line() + { + // Act + Action act = () => "A\r\nB".Should().Be("A\r\nC"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be \r\n\"A\\r\\nC\", but \r\n\"A\\r\\nB\" differs near \"B\" (index 3)."); + } } - [Fact] - public void When_two_strings_differ_unexpectedly_containing_double_curly_closing_braces_it_should_throw() + public class NotBe { - // Act - const string expect = "}}"; - const string actual = "}}}}"; - Action act = () => actual.Should().Be(expect); - - // Assert - act.Should().Throw().WithMessage( - "*to be \"}}\" with a length of 2, but \"}}}}\" has a length of 4*"); - } - - [Fact] - public void When_two_strings_differ_unexpectedly_containing_double_curly_opening_braces_it_should_throw() - { - // Act - const string expect = "{{"; - const string actual = "{{{{"; - Action act = () => actual.Should().Be(expect); - - // Assert - act.Should().Throw().WithMessage( - "*to be \"{{\" with a length of 2, but \"{{{{\" has a length of 4*"); - } - - [Fact] - public void When_the_expected_string_is_shorter_than_the_actual_string_it_should_throw() - { - // Act - Action act = () => "ABC".Should().Be("AB"); - - // Assert - act.Should().Throw().WithMessage("*index 2*"); - } - - [Fact] - public void When_the_expected_string_is_longer_than_the_actual_string_it_should_throw() - { - // Act - Action act = () => "AB".Should().Be("ABC"); - - // Assert - act.Should().Throw().WithMessage("*index 1*"); - } - - [Fact] - public void When_the_expected_string_is_empty_it_should_throw() - { - // Act - Action act = () => "ABC".Should().Be(""); - - // Assert - act.Should().Throw().WithMessage("*index 0*"); - } - - [Fact] - public void When_the_subject_string_is_empty_it_should_throw() - { - // Act - Action act = () => "".Should().Be("ABC"); - - // Assert - act.Should().Throw().WithMessage("*index 0*"); - } - - [Fact] - public void When_string_is_expected_to_equal_null_it_should_throw() - { - // Act - Action act = () => "AB".Should().Be(null); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be , but found \"AB\"."); - } - - [Fact] - public void When_string_is_expected_to_be_null_it_should_throw() - { - // Act - Action act = () => "AB".Should().BeNull("we like {0}", "null"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be because we like null, but found \"AB\"."); - } - - [Fact] - public void When_the_expected_string_is_null_then_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().Be("ABC"); - - // Assert - act.Should().Throw().WithMessage( - "Expected someString to be \"ABC\", but found ."); - } - - [Fact] - public void When_the_expected_string_is_the_same_but_with_trailing_spaces_it_should_throw_with_clear_error_message() - { - // Act - Action act = () => "ABC".Should().Be("ABC ", "because I say {0}", "so"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be \"ABC \" because I say so, but it misses some extra whitespace at the end."); + [Fact] + public void When_different_strings_are_expected_to_differ_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string unexpected = "DEF"; + + // Act / Assert + actual.Should().NotBe(unexpected); + } + + [Fact] + public void When_equal_strings_are_expected_to_differ_it_should_throw() + { + // Act + Action act = () => "ABC".Should().NotBe("ABC", "because we don't like {0}", "ABC"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string not to be \"ABC\" because we don't like ABC."); + } + + [Fact] + public void When_non_empty_string_is_not_equal_to_empty_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string unexpected = ""; + + // Act / Assert + actual.Should().NotBe(unexpected); + } + + [Fact] + public void When_empty_string_is_not_supposed_to_be_equal_to_empty_it_should_throw() + { + // Arrange + string actual = ""; + string unexpected = ""; + + // Act + Action act = () => actual.Should().NotBe(unexpected); + + // Assert + act.Should().Throw().WithMessage( + "Expected actual not to be \"\"."); + } + + [Fact] + public void When_valid_string_is_not_supposed_to_be_null_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string unexpected = null; + + // Act / Assert + actual.Should().NotBe(unexpected); + } + + [Fact] + public void When_null_string_is_not_supposed_to_be_equal_to_null_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().NotBe(null); + + // Assert + act.Should().Throw().WithMessage( + "Expected someString not to be ."); + } + + [Fact] + public void When_null_string_is_not_supposed_to_be_null_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().NotBeNull("we don't like {0}", "null"); + + // Assert + act.Should().Throw().WithMessage( + "Expected someString not to be because we don't like null."); + } } - - [Fact] - public void When_the_actual_string_is_the_same_as_the_expected_but_with_trailing_spaces_it_should_throw_with_clear_error_message() - { - // Act - Action act = () => "ABC ".Should().Be("ABC", "because I say {0}", "so"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be \"ABC\" because I say so, but it has unexpected whitespace at the end."); - } - - [Fact] - public void When_two_strings_differ_and_one_of_them_is_long_it_should_display_both_strings_on_separate_line() - { - // Act - Action act = () => "1234567890".Should().Be("0987654321"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be*\"0987654321\", but*\"1234567890\" differs near \"123\" (index 0)."); - } - - [Fact] - public void When_two_strings_differ_and_one_of_them_is_multiline_it_should_display_both_strings_on_separate_line() - { - // Act - Action act = () => "A\r\nB".Should().Be("A\r\nC"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be \r\n\"A\\r\\nC\", but \r\n\"A\\r\\nB\" differs near \"B\" (index 3)."); - } - - #endregion - - #region Not Be - - [Fact] - public void When_different_strings_are_expected_to_differ_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - string unexpected = "DEF"; - - // Act / Assert - actual.Should().NotBe(unexpected); - } - - [Fact] - public void When_equal_strings_are_expected_to_differ_it_should_throw() - { - // Act - Action act = () => "ABC".Should().NotBe("ABC", "because we don't like {0}", "ABC"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string not to be \"ABC\" because we don't like ABC."); - } - - [Fact] - public void When_non_empty_string_is_not_equal_to_empty_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - string unexpected = ""; - - // Act / Assert - actual.Should().NotBe(unexpected); - } - - [Fact] - public void When_empty_string_is_not_supposed_to_be_equal_to_empty_it_should_throw() - { - // Arrange - string actual = ""; - string unexpected = ""; - - // Act - Action act = () => actual.Should().NotBe(unexpected); - - // Assert - act.Should().Throw().WithMessage( - "Expected actual not to be \"\"."); - } - - [Fact] - public void When_valid_string_is_not_supposed_to_be_null_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - string unexpected = null; - - // Act / Assert - actual.Should().NotBe(unexpected); - } - - [Fact] - public void When_null_string_is_not_supposed_to_be_equal_to_null_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().NotBe(null); - - // Assert - act.Should().Throw().WithMessage( - "Expected someString not to be ."); - } - - [Fact] - public void When_null_string_is_not_supposed_to_be_null_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().NotBeNull("we don't like {0}", "null"); - - // Assert - act.Should().Throw().WithMessage( - "Expected someString not to be because we don't like null."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEmpty.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEmpty.cs index 3d33cbf189..5f35433cb1 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEmpty.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEmpty.cs @@ -9,110 +9,108 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be Empty - - [Fact] - public void Should_succeed_when_asserting_empty_string_to_be_empty() - { - // Arrange - string actual = ""; - - // Act / Assert - actual.Should().BeEmpty(); - } - - [Fact] - public void Should_fail_when_asserting_non_empty_string_to_be_empty() - { - // Arrange - string actual = "ABC"; - - // Act - Action act = () => actual.Should().BeEmpty(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_non_empty_string_to_be_empty() + public class BeEmpty { - // Arrange - string actual = "ABC"; - - // Act - Action act = () => actual.Should().BeEmpty("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected actual to be empty because we want to test the failure message, but found \"ABC\"."); + [Fact] + public void Should_succeed_when_asserting_empty_string_to_be_empty() + { + // Arrange + string actual = ""; + + // Act / Assert + actual.Should().BeEmpty(); + } + + [Fact] + public void Should_fail_when_asserting_non_empty_string_to_be_empty() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => actual.Should().BeEmpty(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_non_empty_string_to_be_empty() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => actual.Should().BeEmpty("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected actual to be empty because we want to test the failure message, but found \"ABC\"."); + } + + [Fact] + public void When_checking_for_an_empty_string_and_it_is_null_it_should_throw() + { + // Arrange + string nullString = null; + + // Act + Action act = () => nullString.Should().BeEmpty("because strings should never be {0}", "null"); + + // Assert + act.Should().Throw().WithMessage( + "Expected nullString to be empty because strings should never be null, but found ."); + } } - [Fact] - public void When_checking_for_an_empty_string_and_it_is_null_it_should_throw() + public class NotBeEmpty { - // Arrange - string nullString = null; - - // Act - Action act = () => nullString.Should().BeEmpty("because strings should never be {0}", "null"); - - // Assert - act.Should().Throw().WithMessage( - "Expected nullString to be empty because strings should never be null, but found ."); + [Fact] + public void Should_succeed_when_asserting_non_empty_string_to_be_filled() + { + // Arrange + string actual = "ABC"; + + // Act / Assert + actual.Should().NotBeEmpty(); + } + + [Fact] + public void When_asserting_null_string_to_not_be_empty_it_should_succeed() + { + // Arrange + string actual = null; + + // Act / Assert + actual.Should().NotBeEmpty(); + } + + [Fact] + public void Should_fail_when_asserting_empty_string_to_be_filled() + { + // Arrange + string actual = ""; + + // Act + Action act = () => actual.Should().NotBeEmpty(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_empty_string_to_be_filled() + { + // Arrange + string actual = ""; + + // Act + Action act = () => actual.Should().NotBeEmpty("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect actual to be empty because we want to test the failure message."); + } } - - #endregion - - #region Not Be Empty - - [Fact] - public void Should_succeed_when_asserting_non_empty_string_to_be_filled() - { - // Arrange - string actual = "ABC"; - - // Act / Assert - actual.Should().NotBeEmpty(); - } - - [Fact] - public void When_asserting_null_string_to_not_be_empty_it_should_succeed() - { - // Arrange - string actual = null; - - // Act / Assert - actual.Should().NotBeEmpty(); - } - - [Fact] - public void Should_fail_when_asserting_empty_string_to_be_filled() - { - // Arrange - string actual = ""; - - // Act - Action act = () => actual.Should().NotBeEmpty(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_empty_string_to_be_filled() - { - // Arrange - string actual = ""; - - // Act - Action act = () => actual.Should().NotBeEmpty("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect actual to be empty because we want to test the failure message."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEquivalentTo.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEquivalentTo.cs index 9a8f0bad38..d2aac7da35 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEquivalentTo.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeEquivalentTo.cs @@ -10,191 +10,189 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be Equivalent To - - [Fact] - public void When_strings_are_the_same_while_ignoring_case_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - string expectedEquivalent = "abc"; - - // Act / Assert - actual.Should().BeEquivalentTo(expectedEquivalent); - } - - [Fact] - public void When_strings_differ_other_than_by_case_it_should_throw() - { - // Act - Action act = () => "ADC".Should().BeEquivalentTo("abc", "we will test {0} + {1}", 1, 2); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be equivalent to \"abc\" because we will test 1 + 2, but \"ADC\" differs near \"DC\" (index 1)."); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_non_null_string_is_expected_to_be_equivalent_to_null_it_should_throw() - { - // Act - Action act = () => "ABCDEF".Should().BeEquivalentTo(null); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be equivalent to , but found \"ABCDEF\"."); - } - - [Fact] - public void When_non_empty_string_is_expected_to_be_equivalent_to_empty_it_should_throw() - { - // Act - Action act = () => "ABC".Should().BeEquivalentTo(""); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be equivalent to \"\" with a length of 0, but \"ABC\" has a length of 3, differs near \"ABC\" (index 0)."); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_string_is_equivalent_but_too_short_it_should_throw() - { - // Act - Action act = () => "AB".Should().BeEquivalentTo("ABCD"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be equivalent to \"ABCD\" with a length of 4, but \"AB\" has a length of 2*"); - } - - [Fact] - public void When_string_equivalence_is_asserted_and_actual_value_is_null_then_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().BeEquivalentTo("abc", "we will test {0} + {1}", 1, 2); - - // Assert - act.Should().Throw() - .WithMessage("Expected someString to be equivalent to \"abc\" because we will test 1 + 2, but found ."); - } - - [Fact] - public void When_the_expected_string_is_equivalent_to_the_actual_string_but_with_trailing_spaces_it_should_throw_with_clear_error_message() - { - // Act - Action act = () => "ABC".Should().BeEquivalentTo("abc ", "because I say {0}", "so"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be equivalent to \"abc \" because I say so, but it misses some extra whitespace at the end."); - } - - [Fact] - public void When_the_actual_string_equivalent_to_the_expected_but_with_trailing_spaces_it_should_throw_with_clear_error_message() - { - // Act - Action act = () => "ABC ".Should().BeEquivalentTo("abc", "because I say {0}", "so"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to be equivalent to \"abc\" because I say so, but it has unexpected whitespace at the end."); - } - - #endregion - - #region Not Be Equivalent To - - [Fact] - public void When_strings_are_the_same_while_ignoring_case_it_should_throw() - { - // Arrange - string actual = "ABC"; - string unexpected = "abc"; - - // Act - Action action = () => actual.Should().NotBeEquivalentTo(unexpected, "because I say {0}", "so"); - - // Assert - action.Should().Throw() - .WithMessage("Expected actual not to be equivalent to \"abc\" because I say so, but they are."); - } - - [Fact] - public void When_strings_differ_other_than_by_case_it_should_not_throw() - { - // Act - Action act = () => "ADC".Should().NotBeEquivalentTo("abc"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_non_null_string_is_expected_to_be_equivalent_to_null_it_should_not_throw() - { - // Act - Action act = () => "ABCDEF".Should().NotBeEquivalentTo(null); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_non_empty_string_is_expected_to_be_equivalent_to_empty_it_should_not_throw() - { - // Act - Action act = () => "ABC".Should().NotBeEquivalentTo(""); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_is_equivalent_but_too_short_it_should_not_throw() - { - // Act - Action act = () => "AB".Should().NotBeEquivalentTo("ABCD"); - - // Assert - act.Should().NotThrow(); + public class BeEquivalentTo + { + [Fact] + public void When_strings_are_the_same_while_ignoring_case_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string expectedEquivalent = "abc"; + + // Act / Assert + actual.Should().BeEquivalentTo(expectedEquivalent); + } + + [Fact] + public void When_strings_differ_other_than_by_case_it_should_throw() + { + // Act + Action act = () => "ADC".Should().BeEquivalentTo("abc", "we will test {0} + {1}", 1, 2); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be equivalent to \"abc\" because we will test 1 + 2, but \"ADC\" differs near \"DC\" (index 1)."); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_non_null_string_is_expected_to_be_equivalent_to_null_it_should_throw() + { + // Act + Action act = () => "ABCDEF".Should().BeEquivalentTo(null); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be equivalent to , but found \"ABCDEF\"."); + } + + [Fact] + public void When_non_empty_string_is_expected_to_be_equivalent_to_empty_it_should_throw() + { + // Act + Action act = () => "ABC".Should().BeEquivalentTo(""); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be equivalent to \"\" with a length of 0, but \"ABC\" has a length of 3, differs near \"ABC\" (index 0)."); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_string_is_equivalent_but_too_short_it_should_throw() + { + // Act + Action act = () => "AB".Should().BeEquivalentTo("ABCD"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be equivalent to \"ABCD\" with a length of 4, but \"AB\" has a length of 2*"); + } + + [Fact] + public void When_string_equivalence_is_asserted_and_actual_value_is_null_then_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().BeEquivalentTo("abc", "we will test {0} + {1}", 1, 2); + + // Assert + act.Should().Throw() + .WithMessage("Expected someString to be equivalent to \"abc\" because we will test 1 + 2, but found ."); + } + + [Fact] + public void When_the_expected_string_is_equivalent_to_the_actual_string_but_with_trailing_spaces_it_should_throw_with_clear_error_message() + { + // Act + Action act = () => "ABC".Should().BeEquivalentTo("abc ", "because I say {0}", "so"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be equivalent to \"abc \" because I say so, but it misses some extra whitespace at the end."); + } + + [Fact] + public void When_the_actual_string_equivalent_to_the_expected_but_with_trailing_spaces_it_should_throw_with_clear_error_message() + { + // Act + Action act = () => "ABC ".Should().BeEquivalentTo("abc", "because I say {0}", "so"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to be equivalent to \"abc\" because I say so, but it has unexpected whitespace at the end."); + } + } + + public class NotBeEquivalentTo + { + [Fact] + public void When_strings_are_the_same_while_ignoring_case_it_should_throw() + { + // Arrange + string actual = "ABC"; + string unexpected = "abc"; + + // Act + Action action = () => actual.Should().NotBeEquivalentTo(unexpected, "because I say {0}", "so"); + + // Assert + action.Should().Throw() + .WithMessage("Expected actual not to be equivalent to \"abc\" because I say so, but they are."); + } + + [Fact] + public void When_strings_differ_other_than_by_case_it_should_not_throw() + { + // Act + Action act = () => "ADC".Should().NotBeEquivalentTo("abc"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_non_null_string_is_expected_to_be_equivalent_to_null_it_should_not_throw() + { + // Act + Action act = () => "ABCDEF".Should().NotBeEquivalentTo(null); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_non_empty_string_is_expected_to_be_equivalent_to_empty_it_should_not_throw() + { + // Act + Action act = () => "ABC".Should().NotBeEquivalentTo(""); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_is_equivalent_but_too_short_it_should_not_throw() + { + // Act + Action act = () => "AB".Should().NotBeEquivalentTo("ABCD"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_equivalence_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + { + // Arrange + string someString = null; + + // Act + Action act = () => someString.Should().NotBeEquivalentTo("abc"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_the_expected_string_is_equivalent_to_the_actual_string_but_with_trailing_spaces_it_should_not_throw() + { + // Act + Action act = () => "ABC".Should().NotBeEquivalentTo("abc "); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_the_actual_string_equivalent_to_the_expected_but_with_trailing_spaces_it_should_not_throw() + { + // Act + Action act = () => "ABC ".Should().NotBeEquivalentTo("abc"); + + // Assert + act.Should().NotThrow(); + } } - - [Fact] - public void When_string_equivalence_is_asserted_and_actual_value_is_null_then_it_should_not_throw() - { - // Arrange - string someString = null; - - // Act - Action act = () => someString.Should().NotBeEquivalentTo("abc"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_the_expected_string_is_equivalent_to_the_actual_string_but_with_trailing_spaces_it_should_not_throw() - { - // Act - Action act = () => "ABC".Should().NotBeEquivalentTo("abc "); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_the_actual_string_equivalent_to_the_expected_but_with_trailing_spaces_it_should_not_throw() - { - // Act - Action act = () => "ABC ".Should().NotBeEquivalentTo("abc"); - - // Assert - act.Should().NotThrow(); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeLowerCased.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeLowerCased.cs index ee76a7b7ba..b7664e85b7 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeLowerCased.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeLowerCased.cs @@ -9,143 +9,141 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be Lower Cased - - [Fact] - public void When_a_lower_string_is_supposed_to_be_lower_it_should_succeed() - { - // Arrange - string actual = "abc"; - - // Act / Assert - actual.Should().BeLowerCased(); - } - - [Fact] - public void When_an_empty_string_is_supposed_to_be_lower_it_should_succeed() - { - // Arrange - string actual = ""; - - // Act / Assert - actual.Should().BeLowerCased(); - } - - [Fact] - public void When_a_non_lower_string_is_supposed_to_be_lower_it_should_fail() - { - // Arrange - string actual = "ABC"; - - // Act - Action act = () => actual.Should().BeLowerCased(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_lower_case_string_with_numbers_is_supposed_to_be_in_lower_case_only_it_should_throw() - { - // Arrange - string actual = "a1"; - - // Act - Action act = () => actual.Should().BeLowerCased(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_non_lower_string_is_supposed_to_be_lower_it_should_fail_with_descriptive_message() - { - // Arrange - string actual = "ABC"; - - // Act - Action act = () => actual.Should().BeLowerCased("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected all characters in actual to be lower cased because we want to test the failure message, but found \"ABC\"."); - } - - [Fact] - public void When_checking_for_a_lower_string_and_it_is_null_it_should_throw() + public class BeLowerCased { - // Arrange - string nullString = null; - - // Act - Action act = () => nullString.Should().BeLowerCased("because strings should never be {0}", "null"); - - // Assert - act.Should().Throw().WithMessage( - "Expected all characters in nullString to be lower cased because strings should never be null, but found ."); - } - - #endregion - - #region Not Be Lower Cased - - [Fact] - public void When_a_non_lower_string_is_supposed_to_be_upper_it_should_succeed() - { - // Arrange - string actual = "ABC"; - - // Act / Assert - actual.Should().NotBeLowerCased(); - } - - [Fact] - public void When_a_null_string_is_not_supposed_to_be_lower_it_should_succeed() - { - // Arrange - string actual = null; - - // Act / Assert - actual.Should().NotBeLowerCased(); + [Fact] + public void When_a_lower_string_is_supposed_to_be_lower_it_should_succeed() + { + // Arrange + string actual = "abc"; + + // Act / Assert + actual.Should().BeLowerCased(); + } + + [Fact] + public void When_an_empty_string_is_supposed_to_be_lower_it_should_succeed() + { + // Arrange + string actual = ""; + + // Act / Assert + actual.Should().BeLowerCased(); + } + + [Fact] + public void When_a_non_lower_string_is_supposed_to_be_lower_it_should_fail() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => actual.Should().BeLowerCased(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_lower_case_string_with_numbers_is_supposed_to_be_in_lower_case_only_it_should_throw() + { + // Arrange + string actual = "a1"; + + // Act + Action act = () => actual.Should().BeLowerCased(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_non_lower_string_is_supposed_to_be_lower_it_should_fail_with_descriptive_message() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => actual.Should().BeLowerCased("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected all characters in actual to be lower cased because we want to test the failure message, but found \"ABC\"."); + } + + [Fact] + public void When_checking_for_a_lower_string_and_it_is_null_it_should_throw() + { + // Arrange + string nullString = null; + + // Act + Action act = () => nullString.Should().BeLowerCased("because strings should never be {0}", "null"); + + // Assert + act.Should().Throw().WithMessage( + "Expected all characters in nullString to be lower cased because strings should never be null, but found ."); + } } - [Fact] - public void When_a_lower_string_is_supposed_to_be_upper_it_should_throw() + public class NotBeLowerCased { - // Arrange - string actual = "abc"; - - // Act - Action act = () => actual.Should().NotBeLowerCased(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_lower_case_string_with_numbers_is_not_supposed_to_be_in_lower_case_only_it_should_succeed() - { - // Arrange - string actual = "A1"; - - // Act / Assert - actual.Should().NotBeLowerCased(); + [Fact] + public void When_a_non_lower_string_is_supposed_to_be_upper_it_should_succeed() + { + // Arrange + string actual = "ABC"; + + // Act / Assert + actual.Should().NotBeLowerCased(); + } + + [Fact] + public void When_a_null_string_is_not_supposed_to_be_lower_it_should_succeed() + { + // Arrange + string actual = null; + + // Act / Assert + actual.Should().NotBeLowerCased(); + } + + [Fact] + public void When_a_lower_string_is_supposed_to_be_upper_it_should_throw() + { + // Arrange + string actual = "abc"; + + // Act + Action act = () => actual.Should().NotBeLowerCased(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_lower_case_string_with_numbers_is_not_supposed_to_be_in_lower_case_only_it_should_succeed() + { + // Arrange + string actual = "A1"; + + // Act / Assert + actual.Should().NotBeLowerCased(); + } + + [Fact] + public void When_a_lower_string_is_not_supposed_to_be_lower_it_should_fail_with_descriptive_message() + { + // Arrange + string actual = "abc"; + + // Act + Action act = () => actual.Should().NotBeLowerCased("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect any characters in actual to be lower cased because we want to test the failure message."); + } } - - [Fact] - public void When_a_lower_string_is_not_supposed_to_be_lower_it_should_fail_with_descriptive_message() - { - // Arrange - string actual = "abc"; - - // Act - Action act = () => actual.Should().NotBeLowerCased("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect any characters in actual to be lower cased because we want to test the failure message."); - } - - #endregion (Not) Lower } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrEmpty.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrEmpty.cs index 53b03e123c..04b325e377 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrEmpty.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrEmpty.cs @@ -9,84 +9,82 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be Null Or Empty - - [Fact] - public void When_a_null_string_is_expected_to_be_null_or_empty_it_should_not_throw() + public class BeNullOrEmpty { - // Arrange - string str = null; - - // Act / Assert - str.Should().BeNullOrEmpty(); + [Fact] + public void When_a_null_string_is_expected_to_be_null_or_empty_it_should_not_throw() + { + // Arrange + string str = null; + + // Act / Assert + str.Should().BeNullOrEmpty(); + } + + [Fact] + public void When_an_empty_string_is_expected_to_be_null_or_empty_it_should_not_throw() + { + // Arrange + string str = ""; + + // Act / Assert + str.Should().BeNullOrEmpty(); + } + + [Fact] + public void When_a_valid_string_is_expected_to_be_null_or_empty_it_should_throw() + { + // Arrange + string str = "hello"; + + // Act + Action act = () => str.Should().BeNullOrEmpty("it was not initialized {0}", "yet"); + + // Assert + act.Should().Throw().WithMessage( + "Expected str to be or empty because it was not initialized yet, but found \"hello\"."); + } } - [Fact] - public void When_an_empty_string_is_expected_to_be_null_or_empty_it_should_not_throw() + public class NotBeNullOrEmpty { - // Arrange - string str = ""; - - // Act / Assert - str.Should().BeNullOrEmpty(); + [Fact] + public void When_a_valid_string_is_expected_to_be_not_null_or_empty_it_should_not_throw() + { + // Arrange + string str = "Hello World"; + + // Act / Assert + str.Should().NotBeNullOrEmpty(); + } + + [Fact] + public void When_an_empty_string_is_not_expected_to_be_null_or_empty_it_should_throw() + { + // Arrange + string str = ""; + + // Act + Action act = () => str.Should().NotBeNullOrEmpty("a valid string is expected for {0}", "str"); + + // Assert + act.Should().Throw().WithMessage( + "Expected str not to be or empty because a valid string is expected for str, but found \"\"."); + } + + [Fact] + public void When_a_null_string_is_not_expected_to_be_null_or_empty_it_should_throw() + { + // Arrange + string str = null; + + // Act + Action act = () => str.Should().NotBeNullOrEmpty("a valid string is expected for {0}", "str"); + + // Assert + act.Should().Throw().WithMessage( + "Expected str not to be or empty because a valid string is expected for str, but found ."); + } } - - [Fact] - public void When_a_valid_string_is_expected_to_be_null_or_empty_it_should_throw() - { - // Arrange - string str = "hello"; - - // Act - Action act = () => str.Should().BeNullOrEmpty("it was not initialized {0}", "yet"); - - // Assert - act.Should().Throw().WithMessage( - "Expected str to be or empty because it was not initialized yet, but found \"hello\"."); - } - - #endregion - - #region Not Be Null Or Empty - - [Fact] - public void When_a_valid_string_is_expected_to_be_not_null_or_empty_it_should_not_throw() - { - // Arrange - string str = "Hello World"; - - // Act / Assert - str.Should().NotBeNullOrEmpty(); - } - - [Fact] - public void When_an_empty_string_is_not_expected_to_be_null_or_empty_it_should_throw() - { - // Arrange - string str = ""; - - // Act - Action act = () => str.Should().NotBeNullOrEmpty("a valid string is expected for {0}", "str"); - - // Assert - act.Should().Throw().WithMessage( - "Expected str not to be or empty because a valid string is expected for str, but found \"\"."); - } - - [Fact] - public void When_a_null_string_is_not_expected_to_be_null_or_empty_it_should_throw() - { - // Arrange - string str = null; - - // Act - Action act = () => str.Should().NotBeNullOrEmpty("a valid string is expected for {0}", "str"); - - // Assert - act.Should().Throw().WithMessage( - "Expected str not to be or empty because a valid string is expected for str, but found ."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrWhiteSpace.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrWhiteSpace.cs index 6b44f69ef9..193ee242dd 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrWhiteSpace.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeNullOrWhiteSpace.cs @@ -9,83 +9,81 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be Null Or Whitespace - - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - [InlineData("\n\r")] - [Theory] - public void When_correctly_asserting_null_or_whitespace_it_should_not_throw(string actual) + public class BeNullOrWhitespace { - // Assert - actual.Should().BeNullOrWhiteSpace(); - } + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("\n\r")] + [Theory] + public void When_correctly_asserting_null_or_whitespace_it_should_not_throw(string actual) + { + // Assert + actual.Should().BeNullOrWhiteSpace(); + } - [InlineData("a")] - [InlineData(" a ")] - [Theory] - public void When_correctly_asserting_not_null_or_whitespace_it_should_not_throw(string actual) - { - // Assert - actual.Should().NotBeNullOrWhiteSpace(); - } + [InlineData("a")] + [InlineData(" a ")] + [Theory] + public void When_correctly_asserting_not_null_or_whitespace_it_should_not_throw(string actual) + { + // Assert + actual.Should().NotBeNullOrWhiteSpace(); + } - [Fact] - public void When_a_valid_string_is_expected_to_be_null_or_whitespace_it_should_throw() - { - // Act - Action act = () => - " abc ".Should().BeNullOrWhiteSpace(); + [Fact] + public void When_a_valid_string_is_expected_to_be_null_or_whitespace_it_should_throw() + { + // Act + Action act = () => + " abc ".Should().BeNullOrWhiteSpace(); - // Assert - act.Should().Throw() - .WithMessage("Expected string to be or whitespace, but found \" abc \"."); + // Assert + act.Should().Throw() + .WithMessage("Expected string to be or whitespace, but found \" abc \"."); + } } - #endregion - - #region Not Be Null Or Whitespace - - [Fact] - public void When_a_null_string_is_expected_to_not_be_null_or_whitespace_it_should_throw() + public class NotBeNullOrWhitespace { - // Arrange - string nullString = null; + [Fact] + public void When_a_null_string_is_expected_to_not_be_null_or_whitespace_it_should_throw() + { + // Arrange + string nullString = null; - // Act - Action act = () => - nullString.Should().NotBeNullOrWhiteSpace(); + // Act + Action act = () => + nullString.Should().NotBeNullOrWhiteSpace(); - // Assert - act.Should().Throw() - .WithMessage("Expected nullString not to be or whitespace, but found ."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected nullString not to be or whitespace, but found ."); + } - [Fact] - public void When_an_empty_string_is_expected_to_not_be_null_or_whitespace_it_should_throw() - { - // Act - Action act = () => - "".Should().NotBeNullOrWhiteSpace(); + [Fact] + public void When_an_empty_string_is_expected_to_not_be_null_or_whitespace_it_should_throw() + { + // Act + Action act = () => + "".Should().NotBeNullOrWhiteSpace(); - // Assert - act.Should().Throw() - .WithMessage("Expected string not to be or whitespace, but found \"\"."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected string not to be or whitespace, but found \"\"."); + } - [Fact] - public void When_a_whitespace_string_is_expected_to_not_be_null_or_whitespace_it_should_throw() - { - // Act - Action act = () => - " ".Should().NotBeNullOrWhiteSpace(); + [Fact] + public void When_a_whitespace_string_is_expected_to_not_be_null_or_whitespace_it_should_throw() + { + // Act + Action act = () => + " ".Should().NotBeNullOrWhiteSpace(); - // Assert - act.Should().Throw() - .WithMessage("Expected string not to be or whitespace, but found \" \"."); + // Assert + act.Should().Throw() + .WithMessage("Expected string not to be or whitespace, but found \" \"."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeOneOf.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeOneOf.cs index a4d51fb3a9..b716faf3be 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeOneOf.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeOneOf.cs @@ -9,49 +9,48 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be One Of - - [Fact] - public void When_a_value_is_not_one_of_the_specified_values_it_should_throw() - { - // Arrange - string value = "abc"; - - // Act - Action action = () => value.Should().BeOneOf("def", "xyz"); - - // Assert - action.Should().Throw() - .WithMessage("Expected value to be one of {\"def\", \"xyz\"}, but found \"abc\"."); - } - - [Fact] - public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() - { - // Arrange - string value = "abc"; - - // Act - Action action = () => value.Should().BeOneOf(new[] { "def", "xyz" }, "because those are the valid values"); - - // Assert - action.Should().Throw() - .WithMessage("Expected value to be one of {\"def\", \"xyz\"} because those are the valid values, but found \"abc\"."); - } - - [Fact] - public void When_a_value_is_one_of_the_specified_values_it_should_succeed() + public class BeOneOf { - // Arrange - string value = "abc"; - - // Act - Action action = () => value.Should().BeOneOf("abc", "def", "xyz"); - - // Assert - action.Should().NotThrow(); + [Fact] + public void When_a_value_is_not_one_of_the_specified_values_it_should_throw() + { + // Arrange + string value = "abc"; + + // Act + Action action = () => value.Should().BeOneOf("def", "xyz"); + + // Assert + action.Should().Throw() + .WithMessage("Expected value to be one of {\"def\", \"xyz\"}, but found \"abc\"."); + } + + [Fact] + public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() + { + // Arrange + string value = "abc"; + + // Act + Action action = () => value.Should().BeOneOf(new[] { "def", "xyz" }, "because those are the valid values"); + + // Assert + action.Should().Throw() + .WithMessage("Expected value to be one of {\"def\", \"xyz\"} because those are the valid values, but found \"abc\"."); + } + + [Fact] + public void When_a_value_is_one_of_the_specified_values_it_should_succeed() + { + // Arrange + string value = "abc"; + + // Act + Action action = () => value.Should().BeOneOf("abc", "def", "xyz"); + + // Assert + action.Should().NotThrow(); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeUpperCased.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeUpperCased.cs index 88f8193811..bc0473c074 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeUpperCased.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.BeUpperCased.cs @@ -9,133 +9,131 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Be Upper Cased - - [Fact] - public void When_an_upper_case_string_is_supposed_to_be_in_upper_case_only_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - - // Act / Assert - actual.Should().BeUpperCased(); - } - - [Fact] - public void When_a_non_upper_string_is_supposed_to_be_upper_it_should_throw() - { - // Arrange - string actual = "abc"; - - // Act - Action act = () => actual.Should().BeUpperCased(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_an_upper_case_string_with_numbers_is_supposed_to_be_in_upper_case_only_it_should_throw() - { - // Arrange - string actual = "A1"; - - // Act - Action act = () => actual.Should().BeUpperCased(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_non_upper_string_is_supposed_to_be_upper_it_should_fail_with_descriptive_message() - { - // Arrange - string actual = "abc"; - - // Act - Action act = () => actual.Should().BeUpperCased("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - @"Expected all characters in actual to be upper cased because we want to test the failure message, but found ""abc""."); - } - - [Fact] - public void When_checking_for_an_upper_string_and_it_is_null_it_should_throw() - { - // Arrange - string nullString = null; - - // Act - Action act = () => nullString.Should().BeUpperCased("because strings should never be {0}", "null"); - - // Assert - act.Should().Throw().WithMessage( - "Expected all characters in nullString to be upper cased because strings should never be null, but found ."); - } - - #endregion - - #region Not Be Upper Cased - - [Fact] - public void When_a_non_upper_string_is_supposed_to_be_non_upper_it_should_succeed() - { - // Arrange - string actual = "abc"; - - // Act / Assert - actual.Should().NotBeUpperCased(); - } - - [Fact] - public void When_a_null_string_is_not_supposed_to_be_upper_it_should_succeed() - { - // Arrange - string actual = null; - - // Act / Assert - actual.Should().NotBeUpperCased(); - } - - [Fact] - public void When_an_upper_string_is_not_supposed_to_be_upper_it_should_throw() + public class BeUpperCased { - // Arrange - string actual = "ABC"; - - // Act - Action act = () => actual.Should().NotBeUpperCased(); - - // Assert - act.Should().Throw(); + [Fact] + public void When_an_upper_case_string_is_supposed_to_be_in_upper_case_only_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + + // Act / Assert + actual.Should().BeUpperCased(); + } + + [Fact] + public void When_a_non_upper_string_is_supposed_to_be_upper_it_should_throw() + { + // Arrange + string actual = "abc"; + + // Act + Action act = () => actual.Should().BeUpperCased(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_an_upper_case_string_with_numbers_is_supposed_to_be_in_upper_case_only_it_should_throw() + { + // Arrange + string actual = "A1"; + + // Act + Action act = () => actual.Should().BeUpperCased(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_non_upper_string_is_supposed_to_be_upper_it_should_fail_with_descriptive_message() + { + // Arrange + string actual = "abc"; + + // Act + Action act = () => actual.Should().BeUpperCased("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + @"Expected all characters in actual to be upper cased because we want to test the failure message, but found ""abc""."); + } + + [Fact] + public void When_checking_for_an_upper_string_and_it_is_null_it_should_throw() + { + // Arrange + string nullString = null; + + // Act + Action act = () => nullString.Should().BeUpperCased("because strings should never be {0}", "null"); + + // Assert + act.Should().Throw().WithMessage( + "Expected all characters in nullString to be upper cased because strings should never be null, but found ."); + } } - [Fact] - public void When_an_upper_case_string_with_numbers_is_not_supposed_to_be_in_upper_case_only_it_should_succeed() + public class NotBeUpperCased { - // Arrange - string actual = "a1"; - - // Act / Assert - actual.Should().NotBeUpperCased(); + [Fact] + public void When_a_non_upper_string_is_supposed_to_be_non_upper_it_should_succeed() + { + // Arrange + string actual = "abc"; + + // Act / Assert + actual.Should().NotBeUpperCased(); + } + + [Fact] + public void When_a_null_string_is_not_supposed_to_be_upper_it_should_succeed() + { + // Arrange + string actual = null; + + // Act / Assert + actual.Should().NotBeUpperCased(); + } + + [Fact] + public void When_an_upper_string_is_not_supposed_to_be_upper_it_should_throw() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => actual.Should().NotBeUpperCased(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_an_upper_case_string_with_numbers_is_not_supposed_to_be_in_upper_case_only_it_should_succeed() + { + // Arrange + string actual = "a1"; + + // Act / Assert + actual.Should().NotBeUpperCased(); + } + + [Fact] + public void When_an_upper_string_is_not_supposed_to_be_upper_it_should_fail_with_descriptive_message() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => actual.Should().NotBeUpperCased("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect any characters in actual to be upper cased because we want to test the failure message."); + } } - - [Fact] - public void When_an_upper_string_is_not_supposed_to_be_upper_it_should_fail_with_descriptive_message() - { - // Arrange - string actual = "ABC"; - - // Act - Action act = () => actual.Should().NotBeUpperCased("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect any characters in actual to be upper cased because we want to test the failure message."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Contain.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Contain.cs index 12e0e5b699..a6b3cf3038 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Contain.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Contain.cs @@ -10,462 +10,455 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Contain - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_string_contains_the_expected_string_it_should_not_throw() - { - // Arrange - string actual = "ABCDEF"; - string expectedSubstring = "BCD"; - - // Act / Assert - actual.Should().Contain(expectedSubstring); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_string_does_not_contain_an_expected_string_it_should_throw() - { - // Act - Action act = () => "ABCDEF".Should().Contain("XYZ", "that is {0}", "required"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string \"ABCDEF\" to contain \"XYZ\" because that is required."); - } - - [Fact] - public void When_containment_is_asserted_against_null_it_should_throw() - { - // Act - Action act = () => "a".Should().Contain(null); - - // Assert - act - .Should().Throw() - .WithMessage("Cannot assert string containment against .*") - .WithParameterName("expected"); - } - - [Fact] - public void When_containment_is_asserted_against_an_empty_string_it_should_throw() - { - // Act - Action act = () => "a".Should().Contain(""); - - // Assert - act - .Should().Throw() - .WithMessage("Cannot assert string containment against an empty string.*") - .WithParameterName("expected"); - } - - [Fact] - public void When_string_containment_is_asserted_and_actual_value_is_null_then_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().Contain("XYZ", "that is {0}", "required"); - - // Assert - act.Should().Throw().WithMessage( - "Expected someString to contain \"XYZ\" because that is required."); - } - - #region Exactly - - [Fact] - public void When_string_containment_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() - { - // Arrange - string actual = "ABCDEF"; - string expectedSubstring = "XYS"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Once(), "that is {0}", "required"); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEF\" to contain \"XYS\" exactly 1 time because that is required, but found it 0 times."); - } - - [Fact] - public void When_containment_once_is_asserted_against_null_it_should_throw_earlier() - { - // Arrange - string actual = "a"; - string expectedSubstring = null; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Once()); - - // Assert - act - .Should().Throw() - .WithMessage("Cannot assert string containment against .*"); - } - - [Fact] - public void When_string_containment_once_is_asserted_and_actual_value_is_null_then_it_should_throw() - { - // Arrange - string actual = null; - string expectedSubstring = "XYZ"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * to contain \"XYZ\" exactly 1 time, but found it 0 times."); - } - - [Fact] - public void When_string_containment_exactly_is_asserted_and_expected_value_is_negative_it_should_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Times(-1)); - - // Assert - act.Should().Throw() - .WithMessage("Expected count cannot be negative.*"); - } - - [Fact] - public void When_string_containment_exactly_is_asserted_and_actual_value_contains_the_expected_string_exactly_expected_times_it_should_not_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Times(2)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_exactly_is_asserted_and_actual_value_contains_the_expected_string_but_not_exactly_expected_times_it_should_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Times(3)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" exactly 3 times, but found it 2 times."); - } - - #endregion - - #region AtLeast - - [Fact] - public void When_string_containment_at_least_is_asserted_and_actual_value_contains_the_expected_string_at_least_expected_times_it_should_not_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Times(2)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_at_least_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_least_expected_times_it_should_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Times(3)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" at least 3 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_at_least_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw_earlier() - { - // Arrange - string actual = "ABCDEF"; - string expectedSubstring = "XYS"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEF\" to contain \"XYS\" at least 1 time, but found it 0 times."); - } - - [Fact] - public void When_string_containment_at_least_once_is_asserted_and_actual_value_is_null_then_it_should_throw() - { - // Arrange - string actual = null; - string expectedSubstring = "XYZ"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * to contain \"XYZ\" at least 1 time, but found it 0 times."); - } - - #endregion - - #region MoreThan - - [Fact] - public void When_string_containment_more_than_is_asserted_and_actual_value_contains_the_expected_string_more_than_expected_times_it_should_not_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Times(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_more_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_more_than_expected_times_it_should_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Times(2)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" more than 2 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_more_than_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() - { - // Arrange - string actual = "ABCDEF"; - string expectedSubstring = "XYS"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEF\" to contain \"XYS\" more than 1 time, but found it 0 times."); - } - - [Fact] - public void When_string_containment_more_than_once_is_asserted_and_actual_value_is_null_then_it_should_throw() - { - // Arrange - string actual = null; - string expectedSubstring = "XYZ"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * to contain \"XYZ\" more than 1 time, but found it 0 times."); - } - - #endregion - - #region AtMost - - [Fact] - public void When_string_containment_at_most_is_asserted_and_actual_value_contains_the_expected_string_at_most_expected_times_it_should_not_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Times(2)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_at_most_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_most_expected_times_it_should_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Times(1)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" at most 1 time, but found it 2 times."); - } - - [Fact] - public void When_string_containment_at_most_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_not_throw() - { - // Arrange - string actual = "ABCDEF"; - string expectedSubstring = "XYS"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Once()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_at_most_once_is_asserted_and_actual_value_is_null_then_it_should_not_throw() - { - // Arrange - string actual = null; - string expectedSubstring = "XYZ"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Once()); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region LessThan - - [Fact] - public void When_string_containment_less_than_is_asserted_and_actual_value_contains_the_expected_string_less_than_expected_times_it_should_not_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Times(3)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_less_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_less_than_expected_times_it_should_throw() - { - // Arrange - string actual = "ABCDEBCDF"; - string expectedSubstring = "BCD"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Times(2)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" less than 2 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_less_than_twice_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_not_throw() - { - // Arrange - string actual = "ABCDEF"; - string expectedSubstring = "XYS"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Twice()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_less_than_once_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + public class Contain { - // Arrange - string actual = null; - string expectedSubstring = "XYZ"; - - // Act - Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Twice()); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #endregion - - #region Not Contain - - [Fact] - public void When_string_does_not_contain_the_unexpected_string_it_should_succeed() - { - // Act - Action act = () => "a".Should().NotContain("A"); - - // Assert - act.Should().NotThrow(); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_string_contains_the_expected_string_it_should_not_throw() + { + // Arrange + string actual = "ABCDEF"; + string expectedSubstring = "BCD"; + + // Act / Assert + actual.Should().Contain(expectedSubstring); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_string_does_not_contain_an_expected_string_it_should_throw() + { + // Act + Action act = () => "ABCDEF".Should().Contain("XYZ", "that is {0}", "required"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string \"ABCDEF\" to contain \"XYZ\" because that is required."); + } + + [Fact] + public void When_containment_is_asserted_against_null_it_should_throw() + { + // Act + Action act = () => "a".Should().Contain(null); + + // Assert + act + .Should().Throw() + .WithMessage("Cannot assert string containment against .*") + .WithParameterName("expected"); + } + + [Fact] + public void When_containment_is_asserted_against_an_empty_string_it_should_throw() + { + // Act + Action act = () => "a".Should().Contain(""); + + // Assert + act + .Should().Throw() + .WithMessage("Cannot assert string containment against an empty string.*") + .WithParameterName("expected"); + } + + [Fact] + public void When_string_containment_is_asserted_and_actual_value_is_null_then_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().Contain("XYZ", "that is {0}", "required"); + + // Assert + act.Should().Throw().WithMessage( + "Expected someString to contain \"XYZ\" because that is required."); + } + + public class ContainExactly + { + [Fact] + public void When_string_containment_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() + { + // Arrange + string actual = "ABCDEF"; + string expectedSubstring = "XYS"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Once(), "that is {0}", "required"); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEF\" to contain \"XYS\" exactly 1 time because that is required, but found it 0 times."); + } + + [Fact] + public void When_containment_once_is_asserted_against_null_it_should_throw_earlier() + { + // Arrange + string actual = "a"; + string expectedSubstring = null; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Once()); + + // Assert + act + .Should().Throw() + .WithMessage("Cannot assert string containment against .*"); + } + + [Fact] + public void When_string_containment_once_is_asserted_and_actual_value_is_null_then_it_should_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XYZ"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * to contain \"XYZ\" exactly 1 time, but found it 0 times."); + } + + [Fact] + public void When_string_containment_exactly_is_asserted_and_expected_value_is_negative_it_should_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Times(-1)); + + // Assert + act.Should().Throw() + .WithMessage("Expected count cannot be negative.*"); + } + + [Fact] + public void When_string_containment_exactly_is_asserted_and_actual_value_contains_the_expected_string_exactly_expected_times_it_should_not_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Times(2)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_exactly_is_asserted_and_actual_value_contains_the_expected_string_but_not_exactly_expected_times_it_should_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, Exactly.Times(3)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" exactly 3 times, but found it 2 times."); + } + } + + public class ContainAtLeast + { + [Fact] + public void When_string_containment_at_least_is_asserted_and_actual_value_contains_the_expected_string_at_least_expected_times_it_should_not_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Times(2)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_at_least_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_least_expected_times_it_should_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Times(3)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" at least 3 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_at_least_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw_earlier() + { + // Arrange + string actual = "ABCDEF"; + string expectedSubstring = "XYS"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEF\" to contain \"XYS\" at least 1 time, but found it 0 times."); + } + + [Fact] + public void When_string_containment_at_least_once_is_asserted_and_actual_value_is_null_then_it_should_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XYZ"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtLeast.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * to contain \"XYZ\" at least 1 time, but found it 0 times."); + } + } + + public class ContainMoreThan + { + [Fact] + public void When_string_containment_more_than_is_asserted_and_actual_value_contains_the_expected_string_more_than_expected_times_it_should_not_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Times(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_more_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_more_than_expected_times_it_should_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Times(2)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" more than 2 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_more_than_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() + { + // Arrange + string actual = "ABCDEF"; + string expectedSubstring = "XYS"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEF\" to contain \"XYS\" more than 1 time, but found it 0 times."); + } + + [Fact] + public void When_string_containment_more_than_once_is_asserted_and_actual_value_is_null_then_it_should_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XYZ"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, MoreThan.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * to contain \"XYZ\" more than 1 time, but found it 0 times."); + } + } + + public class ContainAtMost + { + [Fact] + public void When_string_containment_at_most_is_asserted_and_actual_value_contains_the_expected_string_at_most_expected_times_it_should_not_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Times(2)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_at_most_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_most_expected_times_it_should_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Times(1)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" at most 1 time, but found it 2 times."); + } + + [Fact] + public void When_string_containment_at_most_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_not_throw() + { + // Arrange + string actual = "ABCDEF"; + string expectedSubstring = "XYS"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Once()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_at_most_once_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XYZ"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, AtMost.Once()); + + // Assert + act.Should().NotThrow(); + } + } + + public class ContainsLessThan + { + [Fact] + public void When_string_containment_less_than_is_asserted_and_actual_value_contains_the_expected_string_less_than_expected_times_it_should_not_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Times(3)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_less_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_less_than_expected_times_it_should_throw() + { + // Arrange + string actual = "ABCDEBCDF"; + string expectedSubstring = "BCD"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Times(2)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"ABCDEBCDF\" to contain \"BCD\" less than 2 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_less_than_twice_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_not_throw() + { + // Arrange + string actual = "ABCDEF"; + string expectedSubstring = "XYS"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Twice()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_less_than_once_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XYZ"; + + // Act + Action act = () => actual.Should().Contain(expectedSubstring, LessThan.Twice()); + + // Assert + act.Should().NotThrow(); + } + } } - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_string_contains_unexpected_fragment_it_should_throw() + public class NotContain { - // Act - Action act = () => "abcd".Should().NotContain("bc", "it was not expected {0}", "today"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect string \"abcd\" to contain \"bc\" because it was not expected today."); + [Fact] + public void When_string_does_not_contain_the_unexpected_string_it_should_succeed() + { + // Act + Action act = () => "a".Should().NotContain("A"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_string_contains_unexpected_fragment_it_should_throw() + { + // Act + Action act = () => "abcd".Should().NotContain("bc", "it was not expected {0}", "today"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect string \"abcd\" to contain \"bc\" because it was not expected today."); + } + + [Fact] + public void When_exclusion_is_asserted_against_null_it_should_throw() + { + // Act + Action act = () => "a".Should().NotContain(null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert string containment against .*") + .WithParameterName("unexpected"); + } + + [Fact] + public void When_exclusion_is_asserted_against_an_empty_string_it_should_throw() + { + // Act + Action act = () => "a".Should().NotContain(""); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert string containment against an empty string.*") + .WithParameterName("unexpected"); + } } - - [Fact] - public void When_exclusion_is_asserted_against_null_it_should_throw() - { - // Act - Action act = () => "a".Should().NotContain(null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert string containment against .*") - .WithParameterName("unexpected"); - } - - [Fact] - public void When_exclusion_is_asserted_against_an_empty_string_it_should_throw() - { - // Act - Action act = () => "a".Should().NotContain(""); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert string containment against an empty string.*") - .WithParameterName("unexpected"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAll.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAll.cs index f8daca9dbe..f94c23c7b5 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAll.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAll.cs @@ -9,239 +9,237 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region ContainAll - - [Fact] - public void When_containment_of_all_strings_in_a_null_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().ContainAll(null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*null*") - .WithParameterName("values"); - } - - [Fact] - public void When_containment_of_all_strings_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().ContainAll(); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*empty*") - .WithParameterName("values"); - } - - [Fact] - public void When_containment_of_all_strings_in_a_collection_is_asserted_and_all_strings_are_present_it_should_succeed() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().ContainAll(red, green, yellow); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_containment_of_all_strings_in_a_collection_is_asserted_and_equivalent_but_not_exact_matches_exist_for_all_it_should_throw() - { - // Arrange - const string redLowerCase = "red"; - const string redUpperCase = "RED"; - const string greenWithoutWhitespace = "green"; - const string greenWithWhitespace = " green "; - var testString = $"{redLowerCase} {greenWithoutWhitespace}"; - - // Act - Action act = () => testString.Should().ContainAll(redUpperCase, greenWithWhitespace); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain*{redUpperCase}*{greenWithWhitespace}*"); - } - - [Fact] - public void When_containment_of_all_strings_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_throw() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string blue = "blue"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().ContainAll(yellow, blue); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain*{yellow}*{blue}*"); - } - - [Fact] - public void When_containment_of_all_strings_in_a_collection_is_asserted_with_reason_and_assertion_fails_then_failure_message_should_contain_reason() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string blue = "blue"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().ContainAll(new[] { yellow, blue }, "some {0} reason", "special"); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain*{yellow}*{blue}*because some special reason*"); - } - - [Fact] - public void When_containment_of_all_strings_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_throw() + public class ContainAll { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string blue = "blue"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().ContainAll(red, blue, green); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain*{blue}*"); + [Fact] + public void When_containment_of_all_strings_in_a_null_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().ContainAll(null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*null*") + .WithParameterName("values"); + } + + [Fact] + public void When_containment_of_all_strings_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().ContainAll(); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*empty*") + .WithParameterName("values"); + } + + [Fact] + public void When_containment_of_all_strings_in_a_collection_is_asserted_and_all_strings_are_present_it_should_succeed() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().ContainAll(red, green, yellow); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_containment_of_all_strings_in_a_collection_is_asserted_and_equivalent_but_not_exact_matches_exist_for_all_it_should_throw() + { + // Arrange + const string redLowerCase = "red"; + const string redUpperCase = "RED"; + const string greenWithoutWhitespace = "green"; + const string greenWithWhitespace = " green "; + var testString = $"{redLowerCase} {greenWithoutWhitespace}"; + + // Act + Action act = () => testString.Should().ContainAll(redUpperCase, greenWithWhitespace); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain*{redUpperCase}*{greenWithWhitespace}*"); + } + + [Fact] + public void When_containment_of_all_strings_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_throw() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string blue = "blue"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().ContainAll(yellow, blue); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain*{yellow}*{blue}*"); + } + + [Fact] + public void When_containment_of_all_strings_in_a_collection_is_asserted_with_reason_and_assertion_fails_then_failure_message_should_contain_reason() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string blue = "blue"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().ContainAll(new[] { yellow, blue }, "some {0} reason", "special"); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain*{yellow}*{blue}*because some special reason*"); + } + + [Fact] + public void When_containment_of_all_strings_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_throw() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string blue = "blue"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().ContainAll(red, blue, green); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain*{blue}*"); + } } - #endregion - - #region NotContainAll - - [Fact] - public void When_exclusion_of_all_strings_in_null_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().NotContainAll(null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*null*") - .WithParameterName("values"); - } - - [Fact] - public void When_exclusion_of_all_strings_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() + public class NotContainAll { - // Act - Action act = () => "a".Should().NotContainAll(); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*empty*") - .WithParameterName("values"); - } - - [Fact] - public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_all_strings_in_collection_are_present_it_should_throw() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().NotContainAll(red, green, yellow); - - // Assert - act - .Should().Throw() - .WithMessage($"*not*{testString}*contain all*{red}*{green}*{yellow}*"); + [Fact] + public void When_exclusion_of_all_strings_in_null_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().NotContainAll(null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*null*") + .WithParameterName("values"); + } + + [Fact] + public void When_exclusion_of_all_strings_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().NotContainAll(); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*empty*") + .WithParameterName("values"); + } + + [Fact] + public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_all_strings_in_collection_are_present_it_should_throw() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().NotContainAll(red, green, yellow); + + // Assert + act + .Should().Throw() + .WithMessage($"*not*{testString}*contain all*{red}*{green}*{yellow}*"); + } + + [Fact] + public void When_exclusion_of_all_strings_is_asserted_with_reason_and_assertion_fails_then_error_message_contains_reason() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().NotContainAll(new[] { red, green, yellow }, "some {0} reason", "special"); + + // Assert + act + .Should().Throw() + .WithMessage($"*not*{testString}*contain all*{red}*{green}*{yellow}*because*some special reason*"); + } + + [Fact] + public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_only_some_of_the_strings_in_collection_are_present_it_should_succeed() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string purple = "purple"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().NotContainAll(red, green, yellow, purple); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_none_of_the_strings_in_the_collection_are_present_it_should_succeed() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string purple = "purple"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().NotContainAll(yellow, purple); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_equivalent_but_not_exact_strings_are_present_in_collection_it_should_succeed() + { + // Arrange + const string redWithoutWhitespace = "red"; + const string redWithWhitespace = " red "; + const string lowerCaseGreen = "green"; + const string upperCaseGreen = "GREEN"; + var testString = $"{redWithoutWhitespace} {lowerCaseGreen}"; + + // Act + Action act = () => testString.Should().NotContainAll(redWithWhitespace, upperCaseGreen); + + // Assert + act.Should().NotThrow(); + } } - - [Fact] - public void When_exclusion_of_all_strings_is_asserted_with_reason_and_assertion_fails_then_error_message_contains_reason() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().NotContainAll(new[] { red, green, yellow }, "some {0} reason", "special"); - - // Assert - act - .Should().Throw() - .WithMessage($"*not*{testString}*contain all*{red}*{green}*{yellow}*because*some special reason*"); - } - - [Fact] - public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_only_some_of_the_strings_in_collection_are_present_it_should_succeed() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string purple = "purple"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().NotContainAll(red, green, yellow, purple); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_none_of_the_strings_in_the_collection_are_present_it_should_succeed() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string purple = "purple"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().NotContainAll(yellow, purple); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_exclusion_of_all_strings_in_a_collection_is_asserted_and_equivalent_but_not_exact_strings_are_present_in_collection_it_should_succeed() - { - // Arrange - const string redWithoutWhitespace = "red"; - const string redWithWhitespace = " red "; - const string lowerCaseGreen = "green"; - const string upperCaseGreen = "GREEN"; - var testString = $"{redWithoutWhitespace} {lowerCaseGreen}"; - - // Act - Action act = () => testString.Should().NotContainAll(redWithWhitespace, upperCaseGreen); - - // Assert - act.Should().NotThrow(); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAny.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAny.cs index b9b46fe59b..4841286ceb 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAny.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainAny.cs @@ -9,237 +9,236 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region ContainAny - - [Fact] - public void When_containment_of_any_string_in_a_null_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().ContainAny(null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*null*") - .WithParameterName("values"); - } - - [Fact] - public void When_containment_of_any_string_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().ContainAny(); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*empty*") - .WithParameterName("values"); - } - - [Fact] - public void When_containment_of_any_string_in_a_collection_is_asserted_and_all_of_the_strings_are_present_it_should_succeed() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().ContainAny(red, green, yellow); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_containment_of_any_string_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_succeed() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string blue = "blue"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().ContainAny(red, blue, green); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_containment_of_any_string_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_throw() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string blue = "blue"; - const string purple = "purple"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().ContainAny(blue, purple); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain at least one of*{blue}*{purple}*"); - } - - [Fact] - public void When_containment_of_any_string_in_a_collection_is_asserted_and_there_are_equivalent_but_not_exact_matches_it_should_throw() + public class ContainAny { - // Arrange - const string redLowerCase = "red"; - const string redUpperCase = "RED"; - const string greenWithoutWhitespace = "green"; - const string greenWithWhitespace = " green"; - var testString = $"{redLowerCase} {greenWithoutWhitespace}"; - - // Act - Action act = () => testString.Should().ContainAny(redUpperCase, greenWithWhitespace); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain at least one of*{redUpperCase}*{greenWithWhitespace}*"); + [Fact] + public void When_containment_of_any_string_in_a_null_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().ContainAny(null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*null*") + .WithParameterName("values"); + } + + [Fact] + public void When_containment_of_any_string_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().ContainAny(); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*empty*") + .WithParameterName("values"); + } + + [Fact] + public void When_containment_of_any_string_in_a_collection_is_asserted_and_all_of_the_strings_are_present_it_should_succeed() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().ContainAny(red, green, yellow); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_containment_of_any_string_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_succeed() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string blue = "blue"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().ContainAny(red, blue, green); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_containment_of_any_string_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_throw() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string blue = "blue"; + const string purple = "purple"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().ContainAny(blue, purple); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain at least one of*{blue}*{purple}*"); + } + + [Fact] + public void When_containment_of_any_string_in_a_collection_is_asserted_and_there_are_equivalent_but_not_exact_matches_it_should_throw() + { + // Arrange + const string redLowerCase = "red"; + const string redUpperCase = "RED"; + const string greenWithoutWhitespace = "green"; + const string greenWithWhitespace = " green"; + var testString = $"{redLowerCase} {greenWithoutWhitespace}"; + + // Act + Action act = () => testString.Should().ContainAny(redUpperCase, greenWithWhitespace); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain at least one of*{redUpperCase}*{greenWithWhitespace}*"); + } + + [Fact] + public void When_containment_of_any_string_in_a_collection_is_asserted_with_reason_and_assertion_fails_then_failure_message_contains_reason() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string blue = "blue"; + const string purple = "purple"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().ContainAny(new[] { blue, purple }, "some {0} reason", "special"); + + // Assert + act + .Should().Throw() + .WithMessage($"*{testString}*contain at least one of*{blue}*{purple}*because some special reason*"); + } } - [Fact] - public void When_containment_of_any_string_in_a_collection_is_asserted_with_reason_and_assertion_fails_then_failure_message_contains_reason() + public class NotContainAny { - // Arrange - const string red = "red"; - const string green = "green"; - const string blue = "blue"; - const string purple = "purple"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().ContainAny(new[] { blue, purple }, "some {0} reason", "special"); - - // Assert - act - .Should().Throw() - .WithMessage($"*{testString}*contain at least one of*{blue}*{purple}*because some special reason*"); + [Fact] + public void When_exclusion_of_any_string_in_null_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().NotContainAny(null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*null*") + .WithParameterName("values"); + } + + [Fact] + public void When_exclusion_of_any_string_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() + { + // Act + Action act = () => "a".Should().NotContainAny(); + + // Assert + act.Should().Throw() + .WithMessage("Cannot*containment*empty*") + .WithParameterName("values"); + } + + [Fact] + public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_all_of_the_strings_are_present_it_should_throw() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().NotContainAny(red, green, yellow); + + // Assert + act + .Should().Throw() + .WithMessage($"*not*{testString}*contain any*{red}*{green}*{yellow}*"); + } + + [Fact] + public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_throw() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string purple = "purple"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().NotContainAny(red, purple, green); + + // Assert + act + .Should().Throw() + .WithMessage($"*not*{testString}*contain any*{red}*{green}*"); + } + + [Fact] + public void When_exclusion_of_any_strings_is_asserted_with_reason_and_assertion_fails_then_error_message_contains_reason() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + var testString = $"{red} {green} {yellow}"; + + // Act + Action act = () => testString.Should().NotContainAny(new[] { red }, "some {0} reason", "special"); + + // Assert + act + .Should().Throw() + .WithMessage($"*not*{testString}*contain any*{red}*because*some special reason*"); + } + + [Fact] + public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_there_are_equivalent_but_not_exact_matches_it_should_succeed() + { + // Arrange + const string redLowerCase = "red"; + const string redUpperCase = "RED"; + const string greenWithoutWhitespace = "green"; + const string greenWithWhitespace = " green "; + var testString = $"{redLowerCase} {greenWithoutWhitespace}"; + + // Act + Action act = () => testString.Should().NotContainAny(redUpperCase, greenWithWhitespace); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_succeed() + { + // Arrange + const string red = "red"; + const string green = "green"; + const string yellow = "yellow"; + const string purple = "purple"; + var testString = $"{red} {green}"; + + // Act + Action act = () => testString.Should().NotContainAny(yellow, purple); + + // Assert + act.Should().NotThrow(); + } } - - #endregion - - #region NotContainAny - [Fact] - public void When_exclusion_of_any_string_in_null_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().NotContainAny(null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*null*") - .WithParameterName("values"); - } - - [Fact] - public void When_exclusion_of_any_string_in_an_empty_collection_is_asserted_it_should_throw_an_argument_exception() - { - // Act - Action act = () => "a".Should().NotContainAny(); - - // Assert - act.Should().Throw() - .WithMessage("Cannot*containment*empty*") - .WithParameterName("values"); - } - - [Fact] - public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_all_of_the_strings_are_present_it_should_throw() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().NotContainAny(red, green, yellow); - - // Assert - act - .Should().Throw() - .WithMessage($"*not*{testString}*contain any*{red}*{green}*{yellow}*"); - } - - [Fact] - public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_only_some_of_the_strings_are_present_it_should_throw() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string purple = "purple"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().NotContainAny(red, purple, green); - - // Assert - act - .Should().Throw() - .WithMessage($"*not*{testString}*contain any*{red}*{green}*"); - } - - [Fact] - public void When_exclusion_of_any_strings_is_asserted_with_reason_and_assertion_fails_then_error_message_contains_reason() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - var testString = $"{red} {green} {yellow}"; - - // Act - Action act = () => testString.Should().NotContainAny(new[] { red }, "some {0} reason", "special"); - - // Assert - act - .Should().Throw() - .WithMessage($"*not*{testString}*contain any*{red}*because*some special reason*"); - } - - [Fact] - public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_there_are_equivalent_but_not_exact_matches_it_should_succeed() - { - // Arrange - const string redLowerCase = "red"; - const string redUpperCase = "RED"; - const string greenWithoutWhitespace = "green"; - const string greenWithWhitespace = " green "; - var testString = $"{redLowerCase} {greenWithoutWhitespace}"; - - // Act - Action act = () => testString.Should().NotContainAny(redUpperCase, greenWithWhitespace); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_exclusion_of_any_string_in_a_collection_is_asserted_and_none_of_the_strings_are_present_it_should_succeed() - { - // Arrange - const string red = "red"; - const string green = "green"; - const string yellow = "yellow"; - const string purple = "purple"; - var testString = $"{red} {green}"; - - // Act - Action act = () => testString.Should().NotContainAny(yellow, purple); - - // Assert - act.Should().NotThrow(); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs index bca60d6387..28f06caec2 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs @@ -9,449 +9,442 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Contain Equivalent Of - - [InlineData("aa", "A")] - [InlineData("aCCa", "acca")] - [Theory] - public void Should_pass_when_contains_equivalent_of(string actual, string equivalentSubstring) - { - // Assert - actual.Should().ContainEquivalentOf(equivalentSubstring); - } - - [Fact] - public void Should_fail_contain_equivalent_of_when_not_contains() - { - // Act - Action act = () => - "a".Should().ContainEquivalentOf("aa"); - - // Assert - act.Should().Throw() - .WithMessage("Expected string \"a\" to contain the equivalent of \"aa\"."); - } - - [Fact] - public void Should_throw_when_null_equivalent_is_expected() - { - // Act - Action act = () => - "a".Should().ContainEquivalentOf(null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert string containment against .*") - .WithParameterName("expected"); - } - - [Fact] - public void Should_throw_when_empty_equivalent_is_expected() - { - // Act - Action act = () => - "a".Should().ContainEquivalentOf(""); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert string containment against an empty string.*") - .WithParameterName("expected"); - } - - #region Exactly - - [Fact] - public void When_containment_equivalent_of_once_is_asserted_against_null_it_should_throw_earlier() - { - // Arrange - string actual = "a"; - string expectedSubstring = null; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once()); - - // Assert - act - .Should().Throw() - .WithMessage("Cannot assert string containment against .*"); - } - - [Fact] - public void When_string_containment_equivalent_of_exactly_once_is_asserted_and_actual_value_is_null_then_it_should_throw_earlier() - { - // Arrange - string actual = null; - string expectedSubstring = "XyZ"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once(), "that is {0}", "required"); - - // Assert - act.Should().Throw() - .WithMessage("Expected * to contain equivalent of \"XyZ\" exactly 1 time because that is required, but found it 0 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_exactly_is_asserted_and_actual_value_contains_the_expected_string_exactly_expected_times_it_should_not_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Times(2)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_equivalent_of_exactly_is_asserted_and_actual_value_contains_the_expected_string_but_not_exactly_expected_times_it_should_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Times(3)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" exactly 3 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_exactly_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() - { - // Arrange - string actual = "abCDEf"; - string expectedSubstring = "xyS"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEf\" to contain equivalent of \"xyS\" exactly 1 time, but found it 0 times."); - } - - [Fact] - public void When_containment_equivalent_of_exactly_once_is_asserted_against_an_empty_string_it_should_throw_earlier() - { - // Arrange - string actual = "a"; - string expectedSubstring = ""; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once()); - - // Assert - act - .Should().Throw() - .WithMessage("Cannot assert string containment against an empty string.*"); - } - - #endregion - - #region AtLeast - - [Fact] - public void When_string_containment_equivalent_of_at_least_is_asserted_and_actual_value_contains_the_expected_string_at_least_expected_times_it_should_not_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Times(2)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_equivalent_of_at_least_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_least_expected_times_it_should_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Times(3)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" at least 3 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_at_least_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw_earlier() - { - // Arrange - string actual = "abCDEf"; - string expectedSubstring = "xyS"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEf\" to contain equivalent of \"xyS\" at least 1 time, but found it 0 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_at_least_once_is_asserted_and_actual_value_is_null_then_it_should_throw_earlier() - { - // Arrange - string actual = null; - string expectedSubstring = "XyZ"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * to contain equivalent of \"XyZ\" at least 1 time, but found it 0 times."); - } - - #endregion - - #region MoreThan - - [Fact] - public void When_string_containment_equivalent_of_more_than_is_asserted_and_actual_value_contains_the_expected_string_more_than_expected_times_it_should_not_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Times(1)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_equivalent_of_more_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_more_than_expected_times_it_should_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Times(2)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" more than 2 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_more_than_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw_earlier() - { - // Arrange - string actual = "abCDEf"; - string expectedSubstring = "xyS"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEf\" to contain equivalent of \"xyS\" more than 1 time, but found it 0 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_more_than_once_is_asserted_and_actual_value_is_null_then_it_should_throw_earlier() - { - // Arrange - string actual = null; - string expectedSubstring = "XyZ"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Once()); - - // Assert - act.Should().Throw() - .WithMessage("Expected * to contain equivalent of \"XyZ\" more than 1 time, but found it 0 times."); - } - - #endregion - - #region AtMost - - [Fact] - public void When_string_containment_equivalent_of_at_most_is_asserted_and_actual_value_contains_the_expected_string_at_most_expected_times_it_should_not_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Times(2)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_equivalent_of_at_most_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_most_expected_times_it_should_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Times(1)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" at most 1 time, but found it 2 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_at_most_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_not_throw() - { - // Arrange - string actual = "abCDEf"; - string expectedSubstring = "xyS"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Once()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_equivalent_of_at_most_once_is_asserted_and_actual_value_is_null_then_it_should_not_throw() - { - // Arrange - string actual = null; - string expectedSubstring = "XyZ"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Once()); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region LessThan - - [Fact] - public void When_string_containment_equivalent_of_less_than_is_asserted_and_actual_value_contains_the_expected_string_less_than_expected_times_it_should_not_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Times(3)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_string_containment_equivalent_of_less_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_less_than_expected_times_it_should_throw() - { - // Arrange - string actual = "abCDEBcDF"; - string expectedSubstring = "Bcd"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Times(2)); - - // Assert - act.Should().Throw() - .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" less than 2 times, but found it 2 times."); - } - - [Fact] - public void When_string_containment_equivalent_of_less_than_twice_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() + public class ContainEquivalentOf { - // Arrange - string actual = "abCDEf"; - string expectedSubstring = "xyS"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Twice()); - - // Assert - act.Should().NotThrow(); + [InlineData("aa", "A")] + [InlineData("aCCa", "acca")] + [Theory] + public void Should_pass_when_contains_equivalent_of(string actual, string equivalentSubstring) + { + // Assert + actual.Should().ContainEquivalentOf(equivalentSubstring); + } + + [Fact] + public void Should_fail_contain_equivalent_of_when_not_contains() + { + // Act + Action act = () => + "a".Should().ContainEquivalentOf("aa"); + + // Assert + act.Should().Throw() + .WithMessage("Expected string \"a\" to contain the equivalent of \"aa\"."); + } + + [Fact] + public void Should_throw_when_null_equivalent_is_expected() + { + // Act + Action act = () => + "a".Should().ContainEquivalentOf(null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert string containment against .*") + .WithParameterName("expected"); + } + + [Fact] + public void Should_throw_when_empty_equivalent_is_expected() + { + // Act + Action act = () => + "a".Should().ContainEquivalentOf(""); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert string containment against an empty string.*") + .WithParameterName("expected"); + } + + public class ContainEquivalentOfExactly + { + [Fact] + public void When_containment_equivalent_of_once_is_asserted_against_null_it_should_throw_earlier() + { + // Arrange + string actual = "a"; + string expectedSubstring = null; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once()); + + // Assert + act + .Should().Throw() + .WithMessage("Cannot assert string containment against .*"); + } + + [Fact] + public void When_string_containment_equivalent_of_exactly_once_is_asserted_and_actual_value_is_null_then_it_should_throw_earlier() + { + // Arrange + string actual = null; + string expectedSubstring = "XyZ"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once(), "that is {0}", "required"); + + // Assert + act.Should().Throw() + .WithMessage("Expected * to contain equivalent of \"XyZ\" exactly 1 time because that is required, but found it 0 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_exactly_is_asserted_and_actual_value_contains_the_expected_string_exactly_expected_times_it_should_not_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Times(2)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_exactly_is_asserted_and_actual_value_contains_the_expected_string_but_not_exactly_expected_times_it_should_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Times(3)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" exactly 3 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_exactly_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() + { + // Arrange + string actual = "abCDEf"; + string expectedSubstring = "xyS"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEf\" to contain equivalent of \"xyS\" exactly 1 time, but found it 0 times."); + } + + [Fact] + public void When_containment_equivalent_of_exactly_once_is_asserted_against_an_empty_string_it_should_throw_earlier() + { + // Arrange + string actual = "a"; + string expectedSubstring = ""; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, Exactly.Once()); + + // Assert + act + .Should().Throw() + .WithMessage("Cannot assert string containment against an empty string.*"); + } + } } - [Fact] - public void When_string_containment_equivalent_of_less_than_twice_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + public class ContainEquivalentOfAtLeast { - // Arrange - string actual = null; - string expectedSubstring = "XyZ"; - - // Act - Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Twice()); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_string_containment_equivalent_of_at_least_is_asserted_and_actual_value_contains_the_expected_string_at_least_expected_times_it_should_not_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Times(2)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_at_least_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_least_expected_times_it_should_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Times(3)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" at least 3 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_at_least_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw_earlier() + { + // Arrange + string actual = "abCDEf"; + string expectedSubstring = "xyS"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEf\" to contain equivalent of \"xyS\" at least 1 time, but found it 0 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_at_least_once_is_asserted_and_actual_value_is_null_then_it_should_throw_earlier() + { + // Arrange + string actual = null; + string expectedSubstring = "XyZ"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtLeast.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * to contain equivalent of \"XyZ\" at least 1 time, but found it 0 times."); + } } - #endregion - - #endregion - - #region Not Contain Equivalent Of - - [Fact] - public void Should_fail_when_asserting_string_does_not_contain_equivalent_of_null() + public class ContainEquivalentOfMoreThan { - // Act - Action act = () => - "a".Should().NotContainEquivalentOf(null); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect string to contain equivalent of but found \"a\"."); + [Fact] + public void When_string_containment_equivalent_of_more_than_is_asserted_and_actual_value_contains_the_expected_string_more_than_expected_times_it_should_not_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Times(1)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_more_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_more_than_expected_times_it_should_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Times(2)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" more than 2 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_more_than_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw_earlier() + { + // Arrange + string actual = "abCDEf"; + string expectedSubstring = "xyS"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEf\" to contain equivalent of \"xyS\" more than 1 time, but found it 0 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_more_than_once_is_asserted_and_actual_value_is_null_then_it_should_throw_earlier() + { + // Arrange + string actual = null; + string expectedSubstring = "XyZ"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, MoreThan.Once()); + + // Assert + act.Should().Throw() + .WithMessage("Expected * to contain equivalent of \"XyZ\" more than 1 time, but found it 0 times."); + } } - [Fact] - public void Should_fail_when_asserting_string_does_not_contain_equivalent_of_empty() + public class ContainEquivalentOfAtMost { - // Act - Action act = () => - "a".Should().NotContainEquivalentOf(""); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect string to contain equivalent of \"\" but found \"a\"."); + [Fact] + public void When_string_containment_equivalent_of_at_most_is_asserted_and_actual_value_contains_the_expected_string_at_most_expected_times_it_should_not_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Times(2)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_at_most_is_asserted_and_actual_value_contains_the_expected_string_but_not_at_most_expected_times_it_should_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Times(1)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" at most 1 time, but found it 2 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_at_most_once_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_not_throw() + { + // Arrange + string actual = "abCDEf"; + string expectedSubstring = "xyS"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Once()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_at_most_once_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XyZ"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, AtMost.Once()); + + // Assert + act.Should().NotThrow(); + } } - - [Fact] - public void Should_fail_when_asserting_string_does_not_contain_equivalent_of_another_string_but_it_does() + + public class ContainEquivalentOfLessThan { - // Act - Action act = () => - "Hello, world!".Should().NotContainEquivalentOf(", worLD!"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect string to contain equivalent of \", worLD!\" but found \"Hello, world!\"."); + [Fact] + public void When_string_containment_equivalent_of_less_than_is_asserted_and_actual_value_contains_the_expected_string_less_than_expected_times_it_should_not_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Times(3)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_less_than_is_asserted_and_actual_value_contains_the_expected_string_but_not_less_than_expected_times_it_should_throw() + { + // Arrange + string actual = "abCDEBcDF"; + string expectedSubstring = "Bcd"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Times(2)); + + // Assert + act.Should().Throw() + .WithMessage("Expected * \"abCDEBcDF\" to contain equivalent of \"Bcd\" less than 2 times, but found it 2 times."); + } + + [Fact] + public void When_string_containment_equivalent_of_less_than_twice_is_asserted_and_actual_value_does_not_contain_the_expected_string_it_should_throw() + { + // Arrange + string actual = "abCDEf"; + string expectedSubstring = "xyS"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Twice()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_string_containment_equivalent_of_less_than_twice_is_asserted_and_actual_value_is_null_then_it_should_not_throw() + { + // Arrange + string actual = null; + string expectedSubstring = "XyZ"; + + // Act + Action act = () => actual.Should().ContainEquivalentOf(expectedSubstring, LessThan.Twice()); + + // Assert + act.Should().NotThrow(); + } } - [Fact] - public void Should_succeed_when_asserting_string_does_not_contain_equivalent_of_another_string() + public class NotContainEquivalentOf { - // Act - Action act = () => - "aAa".Should().NotContainEquivalentOf("aa "); - - // Assert - act.Should().NotThrow(); + [Fact] + public void Should_fail_when_asserting_string_does_not_contain_equivalent_of_null() + { + // Act + Action act = () => + "a".Should().NotContainEquivalentOf(null); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect string to contain equivalent of but found \"a\"."); + } + + [Fact] + public void Should_fail_when_asserting_string_does_not_contain_equivalent_of_empty() + { + // Act + Action act = () => + "a".Should().NotContainEquivalentOf(""); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect string to contain equivalent of \"\" but found \"a\"."); + } + + [Fact] + public void Should_fail_when_asserting_string_does_not_contain_equivalent_of_another_string_but_it_does() + { + // Act + Action act = () => + "Hello, world!".Should().NotContainEquivalentOf(", worLD!"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect string to contain equivalent of \", worLD!\" but found \"Hello, world!\"."); + } + + [Fact] + public void Should_succeed_when_asserting_string_does_not_contain_equivalent_of_another_string() + { + // Act + Action act = () => + "aAa".Should().NotContainEquivalentOf("aa "); + + // Assert + act.Should().NotThrow(); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWith.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWith.cs index c6edc78319..de11ec42fc 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWith.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWith.cs @@ -10,178 +10,176 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region End With - - [Fact] - public void When_asserting_string_ends_with_a_suffix_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - string expectedSuffix = "BC"; - - // Act / Assert - actual.Should().EndWith(expectedSuffix); - } - - [Fact] - public void When_asserting_string_ends_with_the_same_value_it_should_not_throw() + public class EndWith { - // Arrange - string actual = "ABC"; - string expectedSuffix = "ABC"; - - // Act / Assert - actual.Should().EndWith(expectedSuffix); - } - - [Fact] - public void When_string_does_not_end_with_expected_phrase_it_should_throw() - { - // Act - Action act = () => + [Fact] + public void When_asserting_string_ends_with_a_suffix_it_should_not_throw() { - using var a = new AssertionScope(); - "ABC".Should().EndWith("AB", "it should"); - }; + // Arrange + string actual = "ABC"; + string expectedSuffix = "BC"; - // Assert - act.Should().Throw().WithMessage( - "Expected string \"ABC\" to end with \"AB\" because it should."); - } + // Act / Assert + actual.Should().EndWith(expectedSuffix); + } - [Fact] - public void When_string_ending_is_compared_with_null_it_should_throw() - { - // Act - Action act = () => "ABC".Should().EndWith(null); + [Fact] + public void When_asserting_string_ends_with_the_same_value_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string expectedSuffix = "ABC"; - // Assert - act.Should().Throw().WithMessage( - "Cannot compare string end with .*"); - } + // Act / Assert + actual.Should().EndWith(expectedSuffix); + } - [Fact] - public void When_string_ending_is_compared_with_empty_string_it_should_not_throw() - { - // Act - Action act = () => "ABC".Should().EndWith(""); + [Fact] + public void When_string_does_not_end_with_expected_phrase_it_should_throw() + { + // Act + Action act = () => + { + using var a = new AssertionScope(); + "ABC".Should().EndWith("AB", "it should"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected string \"ABC\" to end with \"AB\" because it should."); + } + + [Fact] + public void When_string_ending_is_compared_with_null_it_should_throw() + { + // Act + Action act = () => "ABC".Should().EndWith(null); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot compare string end with .*"); + } - [Fact] - public void When_string_ending_is_compared_with_string_that_is_longer_it_should_throw() - { - // Act - Action act = () => "ABC".Should().EndWith("00ABC"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to end with " + - "\"00ABC\", but " + - "\"ABC\" is too short."); - } + [Fact] + public void When_string_ending_is_compared_with_empty_string_it_should_not_throw() + { + // Act + Action act = () => "ABC".Should().EndWith(""); - [Fact] - public void When_string_ending_is_compared_and_actual_value_is_null_then_it_should_throw() - { - // Arrange - string someString = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => + [Fact] + public void When_string_ending_is_compared_with_string_that_is_longer_it_should_throw() { - using var _ = new AssertionScope(); - someString.Should().EndWith("ABC"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected someString to end with \"ABC\"."); + // Act + Action act = () => "ABC".Should().EndWith("00ABC"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to end with " + + "\"00ABC\", but " + + "\"ABC\" is too short."); + } + + [Fact] + public void When_string_ending_is_compared_and_actual_value_is_null_then_it_should_throw() + { + // Arrange + string someString = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someString.Should().EndWith("ABC"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected someString to end with \"ABC\"."); + } } - #endregion - - #region Not End With - - [Fact] - public void When_asserting_string_does_not_end_with_a_value_and_it_does_not_it_should_succeed() + public class NotEndWith { - // Arrange - string value = "ABC"; + [Fact] + public void When_asserting_string_does_not_end_with_a_value_and_it_does_not_it_should_succeed() + { + // Arrange + string value = "ABC"; - // Act - Action action = () => - value.Should().NotEndWith("AB"); + // Act + Action action = () => + value.Should().NotEndWith("AB"); - // Assert - action.Should().NotThrow(); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_asserting_string_does_not_end_with_a_value_but_it_does_it_should_fail_with_a_descriptive_message() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotEndWith("BC", "because of some {0}", "reason"); + [Fact] + public void When_asserting_string_does_not_end_with_a_value_but_it_does_it_should_fail_with_a_descriptive_message() + { + // Arrange + string value = "ABC"; - // Assert - action.Should().Throw().WithMessage( - "Expected value \"ABC\" not to end with \"BC\" because of some reason."); - } + // Act + Action action = () => + value.Should().NotEndWith("BC", "because of some {0}", "reason"); - [Fact] - public void When_asserting_string_does_not_end_with_a_value_that_is_null_it_should_throw() - { - // Arrange - string value = "ABC"; + // Assert + action.Should().Throw().WithMessage( + "Expected value \"ABC\" not to end with \"BC\" because of some reason."); + } - // Act - Action action = () => - value.Should().NotEndWith(null); + [Fact] + public void When_asserting_string_does_not_end_with_a_value_that_is_null_it_should_throw() + { + // Arrange + string value = "ABC"; - // Assert - action.Should().Throw().WithMessage( - "Cannot compare end of string with .*"); - } + // Act + Action action = () => + value.Should().NotEndWith(null); - [Fact] - public void When_asserting_string_does_not_end_with_a_value_that_is_empty_it_should_throw() - { - // Arrange - string value = "ABC"; + // Assert + action.Should().Throw().WithMessage( + "Cannot compare end of string with .*"); + } - // Act - Action action = () => - value.Should().NotEndWith(""); + [Fact] + public void When_asserting_string_does_not_end_with_a_value_that_is_empty_it_should_throw() + { + // Arrange + string value = "ABC"; - // Assert - action.Should().Throw().WithMessage( - "Expected value \"ABC\" not to end with \"\"."); - } + // Act + Action action = () => + value.Should().NotEndWith(""); - [Fact] - public void When_asserting_string_does_not_end_with_a_value_and_actual_value_is_null_it_should_throw() - { - // Arrange - string someString = null; + // Assert + action.Should().Throw().WithMessage( + "Expected value \"ABC\" not to end with \"\"."); + } - // Act - Action act = () => + [Fact] + public void When_asserting_string_does_not_end_with_a_value_and_actual_value_is_null_it_should_throw() { - using var _ = new AssertionScope(); - someString.Should().NotEndWith("ABC", "some {0}", "reason"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected someString that does not end with \"ABC\"*some reason*, but found ."); + // Arrange + string someString = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someString.Should().NotEndWith("ABC", "some {0}", "reason"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected someString that does not end with \"ABC\"*some reason*, but found ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWithEquivalentOf.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWithEquivalentOf.cs index 8687d2471d..ba0e860185 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWithEquivalentOf.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.EndWithEquivalentOf.cs @@ -10,174 +10,172 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region End With Equivalent - - [Fact] - public void When_suffix_of_string_differs_by_case_only_it_should_not_throw() - { - // Arrange - string actual = "ABC"; - string expectedSuffix = "bC"; - - // Act / Assert - actual.Should().EndWithEquivalentOf(expectedSuffix); - } - - [Fact] - public void When_end_of_string_differs_by_case_only_it_should_not_throw() + public class EndWithEquivalent { - // Arrange - string actual = "ABC"; - string expectedSuffix = "AbC"; + [Fact] + public void When_suffix_of_string_differs_by_case_only_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string expectedSuffix = "bC"; - // Act / Assert - actual.Should().EndWithEquivalentOf(expectedSuffix); - } + // Act / Assert + actual.Should().EndWithEquivalentOf(expectedSuffix); + } - [Fact] - public void When_end_of_string_does_not_meet_equivalent_it_should_throw() - { - // Act - Action act = () => "ABC".Should().EndWithEquivalentOf("ab", "because it should end"); + [Fact] + public void When_end_of_string_differs_by_case_only_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string expectedSuffix = "AbC"; - // Assert - act.Should().Throw().WithMessage( - "Expected string that ends with equivalent of \"ab\" because it should end, but found \"ABC\"."); - } + // Act / Assert + actual.Should().EndWithEquivalentOf(expectedSuffix); + } - [Fact] - public void When_end_of_string_is_compared_with_equivalent_of_null_it_should_throw() - { - // Act - Action act = () => "ABC".Should().EndWithEquivalentOf(null); + [Fact] + public void When_end_of_string_does_not_meet_equivalent_it_should_throw() + { + // Act + Action act = () => "ABC".Should().EndWithEquivalentOf("ab", "because it should end"); - // Assert - act.Should().Throw().WithMessage( - "Cannot compare string end equivalence with .*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected string that ends with equivalent of \"ab\" because it should end, but found \"ABC\"."); + } - [Fact] - public void When_end_of_string_is_compared_with_equivalent_of_empty_string_it_should_not_throw() - { - // Act - Action act = () => "ABC".Should().EndWithEquivalentOf(""); + [Fact] + public void When_end_of_string_is_compared_with_equivalent_of_null_it_should_throw() + { + // Act + Action act = () => "ABC".Should().EndWithEquivalentOf(null); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot compare string end equivalence with .*"); + } - [Fact] - public void When_string_ending_is_compared_with_equivalent_of_string_that_is_longer_it_should_throw() - { - // Act - Action act = () => "ABC".Should().EndWithEquivalentOf("00abc"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to end with equivalent of " + - "\"00abc\", but " + - "\"ABC\" is too short."); - } + [Fact] + public void When_end_of_string_is_compared_with_equivalent_of_empty_string_it_should_not_throw() + { + // Act + Action act = () => "ABC".Should().EndWithEquivalentOf(""); - [Fact] - public void When_string_ending_is_compared_with_equivalent_and_actual_value_is_null_then_it_should_throw() - { - // Arrange - string someString = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => + [Fact] + public void When_string_ending_is_compared_with_equivalent_of_string_that_is_longer_it_should_throw() { - using var _ = new AssertionScope(); - someString.Should().EndWithEquivalentOf("abC"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected someString that ends with equivalent of \"abC\", but found ."); + // Act + Action act = () => "ABC".Should().EndWithEquivalentOf("00abc"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to end with equivalent of " + + "\"00abc\", but " + + "\"ABC\" is too short."); + } + + [Fact] + public void When_string_ending_is_compared_with_equivalent_and_actual_value_is_null_then_it_should_throw() + { + // Arrange + string someString = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someString.Should().EndWithEquivalentOf("abC"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected someString that ends with equivalent of \"abC\", but found ."); + } } - #endregion - - #region Not End With Equivalent - - [Fact] - public void When_asserting_string_does_not_end_with_equivalent_of_a_value_and_it_does_not_it_should_succeed() + public class NotEndWithEquivalent { - // Arrange - string value = "ABC"; + [Fact] + public void When_asserting_string_does_not_end_with_equivalent_of_a_value_and_it_does_not_it_should_succeed() + { + // Arrange + string value = "ABC"; - // Act - Action action = () => - value.Should().NotEndWithEquivalentOf("aB"); + // Act + Action action = () => + value.Should().NotEndWithEquivalentOf("aB"); - // Assert - action.Should().NotThrow(); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_asserting_string_does_not_end_with_equivalent_of_a_value_but_it_does_it_should_fail_with_a_descriptive_message() - { - // Arrange - string value = "ABC"; + [Fact] + public void When_asserting_string_does_not_end_with_equivalent_of_a_value_but_it_does_it_should_fail_with_a_descriptive_message() + { + // Arrange + string value = "ABC"; - // Act - Action action = () => - value.Should().NotEndWithEquivalentOf("Bc", "because of some {0}", "reason"); + // Act + Action action = () => + value.Should().NotEndWithEquivalentOf("Bc", "because of some {0}", "reason"); - // Assert - action.Should().Throw().WithMessage( - "Expected value that does not end with equivalent of \"Bc\" because of some reason, but found \"ABC\"."); - } + // Assert + action.Should().Throw().WithMessage( + "Expected value that does not end with equivalent of \"Bc\" because of some reason, but found \"ABC\"."); + } - [Fact] - public void When_asserting_string_does_not_end_with_equivalent_of_a_value_that_is_null_it_should_throw() - { - // Arrange - string value = "ABC"; + [Fact] + public void When_asserting_string_does_not_end_with_equivalent_of_a_value_that_is_null_it_should_throw() + { + // Arrange + string value = "ABC"; - // Act - Action action = () => - value.Should().NotEndWithEquivalentOf(null); + // Act + Action action = () => + value.Should().NotEndWithEquivalentOf(null); - // Assert - action.Should().Throw().WithMessage( - "Cannot compare end of string with .*"); - } + // Assert + action.Should().Throw().WithMessage( + "Cannot compare end of string with .*"); + } - [Fact] - public void When_asserting_string_does_not_end_with_equivalent_of_a_value_that_is_empty_it_should_throw() - { - // Arrange - string value = "ABC"; + [Fact] + public void When_asserting_string_does_not_end_with_equivalent_of_a_value_that_is_empty_it_should_throw() + { + // Arrange + string value = "ABC"; - // Act - Action action = () => - value.Should().NotEndWithEquivalentOf(""); + // Act + Action action = () => + value.Should().NotEndWithEquivalentOf(""); - // Assert - action.Should().Throw().WithMessage( - "Expected value that does not end with equivalent of \"\", but found \"ABC\"."); - } + // Assert + action.Should().Throw().WithMessage( + "Expected value that does not end with equivalent of \"\", but found \"ABC\"."); + } - [Fact] - public void When_asserting_string_does_not_end_with_equivalent_of_a_value_and_actual_value_is_null_it_should_throw() - { - // Arrange - string someString = null; - - // Act - Action act = () => + [Fact] + public void When_asserting_string_does_not_end_with_equivalent_of_a_value_and_actual_value_is_null_it_should_throw() { - using var _ = new AssertionScope(); - someString.Should().NotEndWithEquivalentOf("Abc", "some {0}", "reason"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected someString that does not end with equivalent of \"Abc\"*some reason*, but found ."); + // Arrange + string someString = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + someString.Should().NotEndWithEquivalentOf("Abc", "some {0}", "reason"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected someString that does not end with equivalent of \"Abc\"*some reason*, but found ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.HaveLength.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.HaveLength.cs index 9ae8c4129b..8f20fe9d3f 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.HaveLength.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.HaveLength.cs @@ -10,54 +10,53 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region HaveLength - - [Fact] - public void Should_succeed_when_asserting_string_length_to_be_equal_to_the_same_value() - { - // Arrange - string actual = "ABC"; - - // Act / Assert - actual.Should().HaveLength(3); - } - - [Fact] - public void When_asserting_string_length_on_null_string_it_should_fail() + public class HaveLength { - // Arrange - string actual = null; - - // Act - Action act = () => + [Fact] + public void Should_succeed_when_asserting_string_length_to_be_equal_to_the_same_value() { - using var _ = new AssertionScope(); - actual.Should().HaveLength(0, "we want to test the failure {0}", "message"); - }; + // Arrange + string actual = "ABC"; - // Assert - act.Should().Throw() - .WithMessage("Expected actual with length 0 *failure message*, but found ."); - } - - [Fact] - public void Should_fail_when_asserting_string_length_to_be_equal_to_different_value() - { - // Arrange - string actual = "ABC"; + // Act / Assert + actual.Should().HaveLength(3); + } - // Act - Action act = () => + [Fact] + public void When_asserting_string_length_on_null_string_it_should_fail() { - using var _ = new AssertionScope(); - actual.Should().HaveLength(1, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected actual with length 1 *failure message*, but found string \"ABC\" with length 3."); + // Arrange + string actual = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + actual.Should().HaveLength(0, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected actual with length 0 *failure message*, but found ."); + } + + [Fact] + public void Should_fail_when_asserting_string_length_to_be_equal_to_different_value() + { + // Arrange + string actual = "ABC"; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + actual.Should().HaveLength(1, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected actual with length 1 *failure message*, but found string \"ABC\" with length 3."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs index 6ae41f3094..2c980b7788 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.Match.cs @@ -9,169 +9,167 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Match - - [Fact] - public void When_a_string_does_not_match_a_wildcard_pattern_it_should_throw() + public class Match { - // Arrange - string subject = "hello world!"; - - // Act - Action act = () => subject.Should().Match("h*earth!", "that's the universal greeting"); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match*\"h*earth!\" because that's the universal greeting, but*\"hello world!\" does not."); - } - - [Fact] - public void When_a_string_does_match_a_wildcard_pattern_it_should_not_throw() - { - // Arrange - string subject = "hello world!"; - - // Act - Action act = () => subject.Should().Match("h*world?"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_a_string_does_not_match_a_wildcard_pattern_it_should_throw() + { + // Arrange + string subject = "hello world!"; + + // Act + Action act = () => subject.Should().Match("h*earth!", "that's the universal greeting"); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match*\"h*earth!\" because that's the universal greeting, but*\"hello world!\" does not."); + } + + [Fact] + public void When_a_string_does_match_a_wildcard_pattern_it_should_not_throw() + { + // Arrange + string subject = "hello world!"; + + // Act + Action act = () => subject.Should().Match("h*world?"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_string_does_not_match_a_wildcard_pattern_with_escaped_markers_it_should_throw() + { + // Arrange + string subject = "What! Are you deaf!"; + + // Act + Action act = () => subject.Should().Match(@"What\? Are you deaf\?"); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match*\"What\\? Are you deaf\\?\", but*\"What! Are you deaf!\" does not."); + } + + [Fact] + public void When_a_string_does_match_a_wildcard_pattern_but_differs_in_casing_it_should_throw() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().Match("*World*"); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match*\"*World*\", but*\"hello world\" does not."); + } + + [Fact] + public void When_a_string_is_matched_against_null_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().Match(null); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against . Provide a wildcard pattern or use the BeNull method.*") + .WithParameterName("wildcardPattern"); + } + + [Fact] + public void Null_does_not_match_to_any_string() + { + // Arrange + string subject = null; + + // Act + Action act = () => subject.Should().Match("*"); + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match *, but found ."); + } + + [Fact] + public void When_a_string_is_matched_against_an_empty_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().Match(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the BeEmpty method.*") + .WithParameterName("wildcardPattern"); + } } - [Fact] - public void When_a_string_does_not_match_a_wildcard_pattern_with_escaped_markers_it_should_throw() + public class NotMatch { - // Arrange - string subject = "What! Are you deaf!"; - - // Act - Action act = () => subject.Should().Match(@"What\? Are you deaf\?"); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match*\"What\\? Are you deaf\\?\", but*\"What! Are you deaf!\" does not."); + [Fact] + public void When_a_string_does_not_match_a_pattern_and_it_shouldnt_it_should_not_throw() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().NotMatch("*World*"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_string_does_match_a_pattern_but_it_shouldnt_it_should_throw() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().NotMatch("*world*", "because that's illegal"); + + // Assert + act + .Should().Throw().WithMessage( + "Did not expect subject to match*\"*world*\" because that's illegal, but*\"hello world\" matches."); + } + + [Fact] + public void When_a_string_is_negatively_matched_against_null_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().NotMatch(null); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against . Provide a wildcard pattern or use the NotBeNull method.*") + .WithParameterName("wildcardPattern"); + } + + [Fact] + public void When_a_string_is_negatively_matched_against_an_empty_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().NotMatch(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the NotBeEmpty method.*") + .WithParameterName("wildcardPattern"); + } } - - [Fact] - public void When_a_string_does_match_a_wildcard_pattern_but_differs_in_casing_it_should_throw() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().Match("*World*"); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match*\"*World*\", but*\"hello world\" does not."); - } - - [Fact] - public void When_a_string_is_matched_against_null_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().Match(null); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against . Provide a wildcard pattern or use the BeNull method.*") - .WithParameterName("wildcardPattern"); - } - - [Fact] - public void Null_does_not_match_to_any_string() - { - // Arrange - string subject = null; - - // Act - Action act = () => subject.Should().Match("*"); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match *, but found ."); - } - - [Fact] - public void When_a_string_is_matched_against_an_empty_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().Match(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the BeEmpty method.*") - .WithParameterName("wildcardPattern"); - } - - #endregion - - #region Not Match - - [Fact] - public void When_a_string_does_not_match_a_pattern_and_it_shouldnt_it_should_not_throw() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().NotMatch("*World*"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_string_does_match_a_pattern_but_it_shouldnt_it_should_throw() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().NotMatch("*world*", "because that's illegal"); - - // Assert - act - .Should().Throw().WithMessage( - "Did not expect subject to match*\"*world*\" because that's illegal, but*\"hello world\" matches."); - } - - [Fact] - public void When_a_string_is_negatively_matched_against_null_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().NotMatch(null); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against . Provide a wildcard pattern or use the NotBeNull method.*") - .WithParameterName("wildcardPattern"); - } - - [Fact] - public void When_a_string_is_negatively_matched_against_an_empty_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().NotMatch(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the NotBeEmpty method.*") - .WithParameterName("wildcardPattern"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchEquivalentOf.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchEquivalentOf.cs index 128f1b8469..b904025f94 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchEquivalentOf.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchEquivalentOf.cs @@ -9,155 +9,153 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Match Equivalent Of - - [Fact] - public void When_a_string_does_not_match_the_equivalent_of_a_wildcard_pattern_it_should_throw() - { - // Arrange - string subject = "hello world!"; - - // Act - Action act = () => subject.Should().MatchEquivalentOf("h*earth!", "that's the universal greeting"); - - // Assert - act.Should().Throw().WithMessage( - "Expected subject to match the equivalent of*\"h*earth!\" " + - "because that's the universal greeting, but*\"hello world!\" does not."); - } - - [Fact] - public void When_a_string_does_match_the_equivalent_of_a_wildcard_pattern_it_should_not_throw() - { - // Arrange - string subject = "hello world!"; - - // Act - Action act = () => subject.Should().MatchEquivalentOf("h*WORLD?"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_string_with_newline_matches_the_equivalent_of_a_wildcard_pattern_it_should_not_throw() - { - // Arrange - string subject = "hello\r\nworld!"; - - // Act - Action act = () => subject.Should().MatchEquivalentOf("helloworld!"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_string_is_matched_against_the_equivalent_of_null_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().MatchEquivalentOf(null); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against . Provide a wildcard pattern or use the BeNull method.*") - .WithParameterName("wildcardPattern"); - } - - [Fact] - public void When_a_string_is_matched_against_the_equivalent_of_an_empty_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().MatchEquivalentOf(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the BeEmpty method.*") - .WithParameterName("wildcardPattern"); - } - - #endregion - - #region Not Match Equivalent Of - - [Fact] - public void When_a_string_is_not_equivalent_to_a_pattern_and_that_is_expected_it_should_not_throw() - { - // Arrange - string subject = "Hello Earth"; - - // Act - Action act = () => subject.Should().NotMatchEquivalentOf("*World*"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_string_does_match_the_equivalent_of_a_pattern_but_it_shouldnt_it_should_throw() - { - // Arrange - string subject = "hello WORLD"; - - // Act - Action act = () => subject.Should().NotMatchEquivalentOf("*world*", "because that's illegal"); - - // Assert - act - .Should().Throw() - .WithMessage("Did not expect subject to match the equivalent of*\"*world*\" because that's illegal, " + - "but*\"hello WORLD\" matches."); - } - - [Fact] - public void When_a_string_with_newlines_does_match_the_equivalent_of_a_pattern_but_it_shouldnt_it_should_throw() - { - // Arrange - string subject = "hello\r\nworld!"; - - // Act - Action act = () => subject.Should().NotMatchEquivalentOf("helloworld!"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_a_string_is_negatively_matched_against_the_equivalent_of_null_pattern_it_should_throw_with_a_clear_explanation() + public class MatchEquivalentOf { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().NotMatchEquivalentOf(null); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against . Provide a wildcard pattern or use the NotBeNull method.*") - .WithParameterName("wildcardPattern"); + [Fact] + public void When_a_string_does_not_match_the_equivalent_of_a_wildcard_pattern_it_should_throw() + { + // Arrange + string subject = "hello world!"; + + // Act + Action act = () => subject.Should().MatchEquivalentOf("h*earth!", "that's the universal greeting"); + + // Assert + act.Should().Throw().WithMessage( + "Expected subject to match the equivalent of*\"h*earth!\" " + + "because that's the universal greeting, but*\"hello world!\" does not."); + } + + [Fact] + public void When_a_string_does_match_the_equivalent_of_a_wildcard_pattern_it_should_not_throw() + { + // Arrange + string subject = "hello world!"; + + // Act + Action act = () => subject.Should().MatchEquivalentOf("h*WORLD?"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_string_with_newline_matches_the_equivalent_of_a_wildcard_pattern_it_should_not_throw() + { + // Arrange + string subject = "hello\r\nworld!"; + + // Act + Action act = () => subject.Should().MatchEquivalentOf("helloworld!"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_string_is_matched_against_the_equivalent_of_null_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().MatchEquivalentOf(null); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against . Provide a wildcard pattern or use the BeNull method.*") + .WithParameterName("wildcardPattern"); + } + + [Fact] + public void When_a_string_is_matched_against_the_equivalent_of_an_empty_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().MatchEquivalentOf(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the BeEmpty method.*") + .WithParameterName("wildcardPattern"); + } } - [Fact] - public void When_a_string_is_negatively_matched_against_the_equivalent_of_an_empty_string_it_should_throw_with_a_clear_explanation() + public class NotMatchEquivalentOf { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().NotMatchEquivalentOf(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the NotBeEmpty method.*") - .WithParameterName("wildcardPattern"); + [Fact] + public void When_a_string_is_not_equivalent_to_a_pattern_and_that_is_expected_it_should_not_throw() + { + // Arrange + string subject = "Hello Earth"; + + // Act + Action act = () => subject.Should().NotMatchEquivalentOf("*World*"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_string_does_match_the_equivalent_of_a_pattern_but_it_shouldnt_it_should_throw() + { + // Arrange + string subject = "hello WORLD"; + + // Act + Action act = () => subject.Should().NotMatchEquivalentOf("*world*", "because that's illegal"); + + // Assert + act + .Should().Throw() + .WithMessage("Did not expect subject to match the equivalent of*\"*world*\" because that's illegal, " + + "but*\"hello WORLD\" matches."); + } + + [Fact] + public void When_a_string_with_newlines_does_match_the_equivalent_of_a_pattern_but_it_shouldnt_it_should_throw() + { + // Arrange + string subject = "hello\r\nworld!"; + + // Act + Action act = () => subject.Should().NotMatchEquivalentOf("helloworld!"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_a_string_is_negatively_matched_against_the_equivalent_of_null_pattern_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().NotMatchEquivalentOf(null); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against . Provide a wildcard pattern or use the NotBeNull method.*") + .WithParameterName("wildcardPattern"); + } + + [Fact] + public void When_a_string_is_negatively_matched_against_the_equivalent_of_an_empty_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; + + // Act + Action act = () => subject.Should().NotMatchEquivalentOf(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a wildcard pattern or use the NotBeEmpty method.*") + .WithParameterName("wildcardPattern"); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs index 3ac1cb5705..e84f9342aa 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs @@ -12,531 +12,529 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Match Regex - - [Fact] - public void When_a_string_matches_a_regular_expression_string_it_should_not_throw() - { - // Arrange - string subject = "hello world!"; - - // Act - // ReSharper disable once StringLiteralTypo - Action act = () => subject.Should().MatchRegex("h.*\\sworld.$"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_a_string_does_not_match_a_regular_expression_string_it_should_throw() + public class MatchRegex { - // Arrange - string subject = "hello world!"; - - // Act - Action act = () => subject.Should().MatchRegex("h.*\\sworld?$", "that's the universal greeting"); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match regex*\"h.*\\sworld?$\" because that's the universal greeting, but*\"hello world!\" does not match."); - } - - [Fact] - public void When_a_null_string_is_matched_against_a_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = null; - - // Act - Action act = () => subject.Should().MatchRegex(".*", "because it should be a string"); - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match regex*\".*\" because it should be a string, but it was ."); - } - - [Fact] - public void When_a_string_is_matched_against_a_null_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world!"; - - // Act - Action act = () => subject.Should().MatchRegex((string)null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot match string against . Provide a regex pattern or use the BeNull method.*") - .WithParameterName("regularExpression"); - } - - [Fact] - public void When_a_string_is_matched_against_an_invalid_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world!"; - string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors - - // Act - Action act = () => subject.Should().MatchRegex(invalidRegex); - - // Assert - act.Should().Throw() - .WithMessage("Cannot match subject against \".**\" because it is not a valid regular expression.*"); - } - - [Fact] - public void When_a_string_is_matched_against_an_invalid_regex_string_it_should_only_have_one_failure_message() - { - // Arrange - string subject = "hello world!"; - string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors - - // Act - Action act = () => + [Fact] + public void When_a_string_matches_a_regular_expression_string_it_should_not_throw() { - using var _ = new AssertionScope(); - subject.Should().MatchRegex(invalidRegex); - }; - - // Assert - act.Should().Throw() - .Which.Message.Should().Contain("is not a valid regular expression") - .And.NotContain("does not match"); - } + // Arrange + string subject = "hello world!"; - [Fact] - public void When_a_string_is_matched_against_an_empty_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; - - // Act - Action act = () => subject.Should().MatchRegex(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method.*") - .WithParameterName("regularExpression"); - } + // Act + // ReSharper disable once StringLiteralTypo + Action act = () => subject.Should().MatchRegex("h.*\\sworld.$"); - [Fact] - public void When_a_string_matches_a_regular_expression_it_should_not_throw() - { - // Arrange - string subject = "hello world!"; + // Assert + act.Should().NotThrow(); + } - // Act - // ReSharper disable once StringLiteralTypo - Action act = () => subject.Should().MatchRegex(new Regex("h.*\\sworld.$")); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_a_string_does_not_match_a_regular_expression_string_it_should_throw() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().MatchRegex("h.*\\sworld?$", "that's the universal greeting"); - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_a_string_does_not_match_a_regular_expression_it_should_throw() - { - // Arrange - string subject = "hello world!"; + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match regex*\"h.*\\sworld?$\" because that's the universal greeting, but*\"hello world!\" does not match."); + } - // Act - Action act = () => subject.Should().MatchRegex(new Regex("h.*\\sworld?$"), "that's the universal greeting"); + [Fact] + public void When_a_null_string_is_matched_against_a_regex_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = null; - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match regex*\"h.*\\sworld?$\" because that's the universal greeting, but*\"hello world!\" does not match."); - } + // Act + Action act = () => subject.Should().MatchRegex(".*", "because it should be a string"); - [Fact] - public void When_a_null_string_is_matched_against_a_regex_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = null; + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match regex*\".*\" because it should be a string, but it was ."); + } - // Act - Action act = () => + [Fact] + public void When_a_string_is_matched_against_a_null_regex_string_it_should_throw_with_a_clear_explanation() { - using var _ = new AssertionScope(); - subject.Should().MatchRegex(new Regex(".*"), "because it should be a string"); - }; + // Arrange + string subject = "hello world!"; - // Assert - act.Should().Throw() - .WithMessage("Expected subject to match regex*\".*\" because it should be a string, but it was ."); - } + // Act + Action act = () => subject.Should().MatchRegex((string)null); - [Fact] - public void When_a_string_is_matched_against_a_null_regex_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world!"; + // Assert + act.Should().Throw() + .WithMessage("Cannot match string against . Provide a regex pattern or use the BeNull method.*") + .WithParameterName("regularExpression"); + } - // Act - Action act = () => subject.Should().MatchRegex((Regex)null); + [Fact] + public void When_a_string_is_matched_against_an_invalid_regex_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world!"; + string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors - // Assert - act.Should().Throw() - .WithMessage("Cannot match string against . Provide a regex pattern or use the BeNull method.*") - .WithParameterName("regularExpression"); - } + // Act + Action act = () => subject.Should().MatchRegex(invalidRegex); - [Fact] - public void When_a_string_is_matched_against_an_empty_regex_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; + // Assert + act.Should().Throw() + .WithMessage("Cannot match subject against \".**\" because it is not a valid regular expression.*"); + } - // Act - Action act = () => subject.Should().MatchRegex(new Regex(string.Empty)); + [Fact] + public void When_a_string_is_matched_against_an_invalid_regex_string_it_should_only_have_one_failure_message() + { + // Arrange + string subject = "hello world!"; + string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().MatchRegex(invalidRegex); + }; + + // Assert + act.Should().Throw() + .Which.Message.Should().Contain("is not a valid regular expression") + .And.NotContain("does not match"); + } + + [Fact] + public void When_a_string_is_matched_against_an_empty_regex_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method.*") - .WithParameterName("regularExpression"); - } + // Act + Action act = () => subject.Should().MatchRegex(string.Empty); - [Fact] - public void When_a_string_is_matched_and_the_count_of_matches_fits_into_the_expected_it_passes() - { - // Arrange - string subject = "hello world"; + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method.*") + .WithParameterName("regularExpression"); + } - // Act - Action act = () => subject.Should().MatchRegex(new Regex("hello.*"), AtLeast.Once()); + [Fact] + public void When_a_string_matches_a_regular_expression_it_should_not_throw() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().NotThrow(); - } + // Act + // ReSharper disable once StringLiteralTypo + Action act = () => subject.Should().MatchRegex(new Regex("h.*\\sworld.$")); - [Fact] - public void When_a_string_is_matched_and_the_count_of_matches_do_not_fit_the_expected_it_fails() - { - // Arrange - string subject = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt " + - "ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et " + - "ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => subject.Should().MatchRegex("Lorem.*", Exactly.Twice()); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_a_string_does_not_match_a_regular_expression_it_should_throw() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().Throw() - .WithMessage($"Expected subject to match regex*\"Lorem.*\" exactly 2 times, but found it 1 time."); - } + // Act + Action act = () => subject.Should().MatchRegex(new Regex("h.*\\sworld?$"), "that's the universal greeting"); - [Fact] - public void When_a_string_is_matched_and_the_expected_count_is_zero_and_string_not_matches_it_passes() - { - // Arrange - string subject = "a"; + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match regex*\"h.*\\sworld?$\" because that's the universal greeting, but*\"hello world!\" does not match."); + } - // Act - Action act = () => subject.Should().MatchRegex("b", Exactly.Times(0)); + [Fact] + public void When_a_null_string_is_matched_against_a_regex_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().MatchRegex(new Regex(".*"), "because it should be a string"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to match regex*\".*\" because it should be a string, but it was ."); + } + + [Fact] + public void When_a_string_is_matched_against_a_null_regex_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().MatchRegex((Regex)null); - [Fact] - public void When_a_string_is_matched_and_the_expected_count_is_zero_and_string_matches_it_fails() - { - // Arrange - string subject = "a"; + // Assert + act.Should().Throw() + .WithMessage("Cannot match string against . Provide a regex pattern or use the BeNull method.*") + .WithParameterName("regularExpression"); + } - // Act - Action act = () => subject.Should().MatchRegex("a", Exactly.Times(0)); + [Fact] + public void When_a_string_is_matched_against_an_empty_regex_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; - // Assert - act.Should().Throw() - .WithMessage($"Expected subject to match regex*\"a\" exactly 0 times, but found it 1 time."); - } + // Act + Action act = () => subject.Should().MatchRegex(new Regex(string.Empty)); - [Fact] - public void When_the_subject_is_null_it_fails() - { - // Arrange - string subject = null; + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method.*") + .WithParameterName("regularExpression"); + } - // Act - Action act = () => + [Fact] + public void When_a_string_is_matched_and_the_count_of_matches_fits_into_the_expected_it_passes() { - using var _ = new AssertionScope(); - subject.Should().MatchRegex(".*", Exactly.Times(0), "because it should be a string"); - }; + // Arrange + string subject = "hello world"; - // Assert - act.Should().ThrowExactly() - .WithMessage("Expected subject to match regex*\".*\" because it should be a string, but it was ."); - } + // Act + Action act = () => subject.Should().MatchRegex(new Regex("hello.*"), AtLeast.Once()); - [Fact] - public void When_the_subject_is_empty_and_expected_count_is_zero_it_passes() - { - // Arrange - string subject = string.Empty; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => + [Fact] + public void When_a_string_is_matched_and_the_count_of_matches_do_not_fit_the_expected_it_fails() { - using var _ = new AssertionScope(); - subject.Should().MatchRegex("a", Exactly.Times(0)); - }; + // Arrange + string subject = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt " + + "ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et " + + "ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().MatchRegex("Lorem.*", Exactly.Twice()); - [Fact] - public void When_the_subject_is_empty_and_expected_count_is_more_than_zero_it_fails() - { - // Arrange - string subject = string.Empty; + // Assert + act.Should().Throw() + .WithMessage($"Expected subject to match regex*\"Lorem.*\" exactly 2 times, but found it 1 time."); + } - // Act - Action act = () => + [Fact] + public void When_a_string_is_matched_and_the_expected_count_is_zero_and_string_not_matches_it_passes() { - using var _ = new AssertionScope(); - subject.Should().MatchRegex(".+", AtLeast.Once()); - }; + // Arrange + string subject = "a"; - // Assert - act.Should().Throw() - .WithMessage($"Expected subject to match regex* at least 1 time, but found it 0 times.*"); - } - - [Fact] - public void When_regex_is_null_it_fails_and_ignores_occurrences() - { - // Arrange - string subject = "a"; + // Act + Action act = () => subject.Should().MatchRegex("b", Exactly.Times(0)); - // Act - Action act = () => subject.Should().MatchRegex((Regex)null, Exactly.Times(0)); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against . Provide a regex pattern or use the BeNull method.*") - .WithParameterName("regularExpression"); - } + [Fact] + public void When_a_string_is_matched_and_the_expected_count_is_zero_and_string_matches_it_fails() + { + // Arrange + string subject = "a"; - [Fact] - public void When_regex_is_empty_it_fails_and_ignores_occurrences() - { - // Arrange - string subject = "a"; + // Act + Action act = () => subject.Should().MatchRegex("a", Exactly.Times(0)); - // Act - Action act = () => subject.Should().MatchRegex(string.Empty, Exactly.Times(0)); + // Assert + act.Should().Throw() + .WithMessage($"Expected subject to match regex*\"a\" exactly 0 times, but found it 1 time."); + } - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method.*") - .WithParameterName("regularExpression"); - } + [Fact] + public void When_the_subject_is_null_it_fails() + { + // Arrange + string subject = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().MatchRegex(".*", Exactly.Times(0), "because it should be a string"); + }; + + // Assert + act.Should().ThrowExactly() + .WithMessage("Expected subject to match regex*\".*\" because it should be a string, but it was ."); + } + + [Fact] + public void When_the_subject_is_empty_and_expected_count_is_zero_it_passes() + { + // Arrange + string subject = string.Empty; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().MatchRegex("a", Exactly.Times(0)); + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_the_subject_is_empty_and_expected_count_is_more_than_zero_it_fails() + { + // Arrange + string subject = string.Empty; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().MatchRegex(".+", AtLeast.Once()); + }; + + // Assert + act.Should().Throw() + .WithMessage($"Expected subject to match regex* at least 1 time, but found it 0 times.*"); + } + + [Fact] + public void When_regex_is_null_it_fails_and_ignores_occurrences() + { + // Arrange + string subject = "a"; - [Fact] - public void When_regex_is_invalid_it_fails_and_ignores_occurrences() - { - // Arrange - string subject = "a"; + // Act + Action act = () => subject.Should().MatchRegex((Regex)null, Exactly.Times(0)); - // Act - Action act = () => subject.Should().MatchRegex(".**", Exactly.Times(0)); + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against . Provide a regex pattern or use the BeNull method.*") + .WithParameterName("regularExpression"); + } - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match subject against \".**\" because it is not a valid regular expression.*"); - } + [Fact] + public void When_regex_is_empty_it_fails_and_ignores_occurrences() + { + // Arrange + string subject = "a"; - #endregion + // Act + Action act = () => subject.Should().MatchRegex(string.Empty, Exactly.Times(0)); - #region Not Match Regex + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty string. Provide a regex pattern or use the BeEmpty method.*") + .WithParameterName("regularExpression"); + } - [Fact] - public void When_a_string_does_not_match_a_regular_expression_string_and_it_shouldnt_it_should_not_throw() - { - // Arrange - string subject = "hello world!"; + [Fact] + public void When_regex_is_invalid_it_fails_and_ignores_occurrences() + { + // Arrange + string subject = "a"; - // Act - Action act = () => subject.Should().NotMatchRegex(".*earth.*"); + // Act + Action act = () => subject.Should().MatchRegex(".**", Exactly.Times(0)); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match subject against \".**\" because it is not a valid regular expression.*"); + } } - [Fact] - public void When_a_string_matches_a_regular_expression_string_but_it_shouldnt_it_should_throw() + public class NotMatchRegex { - // Arrange - string subject = "hello world!"; + [Fact] + public void When_a_string_does_not_match_a_regular_expression_string_and_it_shouldnt_it_should_not_throw() + { + // Arrange + string subject = "hello world!"; - // Act - Action act = () => subject.Should().NotMatchRegex(".*world.*", "because that's illegal"); + // Act + Action act = () => subject.Should().NotMatchRegex(".*earth.*"); - // Assert - act.Should().Throw() - .WithMessage("Did not expect subject to match regex*\".*world.*\" because that's illegal, but*\"hello world!\" matches."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_null_string_is_negatively_matched_against_a_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = null; - - // Act - Action act = () => subject.Should().NotMatchRegex(".*", "because it should not be a string"); + [Fact] + public void When_a_string_matches_a_regular_expression_string_but_it_shouldnt_it_should_throw() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().Throw() - .WithMessage("Expected subject to not match regex*\".*\" because it should not be a string, but it was ."); - } + // Act + Action act = () => subject.Should().NotMatchRegex(".*world.*", "because that's illegal"); - [Fact] - public void When_a_string_is_negatively_matched_against_a_null_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world!"; + // Assert + act.Should().Throw() + .WithMessage("Did not expect subject to match regex*\".*world.*\" because that's illegal, but*\"hello world!\" matches."); + } - // Act - Action act = () => subject.Should().NotMatchRegex((string)null); + [Fact] + public void When_a_null_string_is_negatively_matched_against_a_regex_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = null; - // Assert - act.Should().Throw() - .WithMessage("Cannot match string against . Provide a regex pattern or use the NotBeNull method.*") - .WithParameterName("regularExpression"); - } + // Act + Action act = () => subject.Should().NotMatchRegex(".*", "because it should not be a string"); - [Fact] - public void When_a_string_is_negatively_matched_against_an_invalid_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world!"; - string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors + // Assert + act.Should().Throw() + .WithMessage("Expected subject to not match regex*\".*\" because it should not be a string, but it was ."); + } - // Act - Action act = () => subject.Should().NotMatchRegex(invalidRegex); + [Fact] + public void When_a_string_is_negatively_matched_against_a_null_regex_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().Throw() - .WithMessage("Cannot match subject against \".**\" because it is not a valid regular expression.*"); - } + // Act + Action act = () => subject.Should().NotMatchRegex((string)null); - [Fact] - public void When_a_string_is_negatively_matched_against_an_invalid_regex_string_it_only_contain_one_failure_message() - { - // Arrange - string subject = "hello world!"; - string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors + // Assert + act.Should().Throw() + .WithMessage("Cannot match string against . Provide a regex pattern or use the NotBeNull method.*") + .WithParameterName("regularExpression"); + } - // Act - Action act = () => + [Fact] + public void When_a_string_is_negatively_matched_against_an_invalid_regex_string_it_should_throw_with_a_clear_explanation() { - using var _ = new AssertionScope(); - subject.Should().NotMatchRegex(invalidRegex); - }; + // Arrange + string subject = "hello world!"; + string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors - // Assert - act.Should().Throw() - .Which.Message.Should().Contain("is not a valid regular expression") - .And.NotContain("matches"); - } + // Act + Action act = () => subject.Should().NotMatchRegex(invalidRegex); - [Fact] - public void When_a_string_is_negatively_matched_against_an_empty_regex_string_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; + // Assert + act.Should().Throw() + .WithMessage("Cannot match subject against \".**\" because it is not a valid regular expression.*"); + } - // Act - Action act = () => subject.Should().NotMatchRegex(string.Empty); + [Fact] + public void When_a_string_is_negatively_matched_against_an_invalid_regex_string_it_only_contain_one_failure_message() + { + // Arrange + string subject = "hello world!"; + string invalidRegex = ".**"; // Use local variable for this invalid regex to avoid static R# analysis errors + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().NotMatchRegex(invalidRegex); + }; + + // Assert + act.Should().Throw() + .Which.Message.Should().Contain("is not a valid regular expression") + .And.NotContain("matches"); + } + + [Fact] + public void When_a_string_is_negatively_matched_against_an_empty_regex_string_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty regex pattern. Provide a regex pattern or use the NotBeEmpty method.*") - .WithParameterName("regularExpression"); - } + // Act + Action act = () => subject.Should().NotMatchRegex(string.Empty); - [Fact] - public void When_a_string_does_not_match_a_regular_expression_and_it_shouldnt_it_should_not_throw() - { - // Arrange - string subject = "hello world!"; + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty regex pattern. Provide a regex pattern or use the NotBeEmpty method.*") + .WithParameterName("regularExpression"); + } - // Act - Action act = () => subject.Should().NotMatchRegex(new Regex(".*earth.*")); + [Fact] + public void When_a_string_does_not_match_a_regular_expression_and_it_shouldnt_it_should_not_throw() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().NotMatchRegex(new Regex(".*earth.*")); - [Fact] - public void When_a_string_matches_a_regular_expression_but_it_shouldnt_it_should_throw() - { - // Arrange - string subject = "hello world!"; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => subject.Should().NotMatchRegex(new Regex(".*world.*"), "because that's illegal"); + [Fact] + public void When_a_string_matches_a_regular_expression_but_it_shouldnt_it_should_throw() + { + // Arrange + string subject = "hello world!"; - // Assert - act.Should().Throw() - .WithMessage("Did not expect subject to match regex*\".*world.*\" because that's illegal, but*\"hello world!\" matches."); - } + // Act + Action act = () => subject.Should().NotMatchRegex(new Regex(".*world.*"), "because that's illegal"); - [Fact] - public void When_a_null_string_is_negatively_matched_against_a_regex_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = null; + // Assert + act.Should().Throw() + .WithMessage("Did not expect subject to match regex*\".*world.*\" because that's illegal, but*\"hello world!\" matches."); + } - // Act - Action act = () => + [Fact] + public void When_a_null_string_is_negatively_matched_against_a_regex_it_should_throw_with_a_clear_explanation() { - using var _ = new AssertionScope(); - subject.Should().NotMatchRegex(new Regex(".*"), "because it should not be a string"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected subject to not match regex*\".*\" because it should not be a string, but it was ."); - } - - [Fact] - public void When_a_string_is_negatively_matched_against_a_null_regex_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world!"; + // Arrange + string subject = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + subject.Should().NotMatchRegex(new Regex(".*"), "because it should not be a string"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected subject to not match regex*\".*\" because it should not be a string, but it was ."); + } + + [Fact] + public void When_a_string_is_negatively_matched_against_a_null_regex_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world!"; - // Act - Action act = () => subject.Should().NotMatchRegex((Regex)null); + // Act + Action act = () => subject.Should().NotMatchRegex((Regex)null); - // Assert - act.Should().Throw() - .WithMessage("Cannot match string against . Provide a regex pattern or use the NotBeNull method.*") - .WithParameterName("regularExpression"); - } + // Assert + act.Should().Throw() + .WithMessage("Cannot match string against . Provide a regex pattern or use the NotBeNull method.*") + .WithParameterName("regularExpression"); + } - [Fact] - public void When_a_string_is_negatively_matched_against_an_empty_regex_it_should_throw_with_a_clear_explanation() - { - // Arrange - string subject = "hello world"; + [Fact] + public void When_a_string_is_negatively_matched_against_an_empty_regex_it_should_throw_with_a_clear_explanation() + { + // Arrange + string subject = "hello world"; - // Act - Action act = () => subject.Should().NotMatchRegex(new Regex(string.Empty)); + // Act + Action act = () => subject.Should().NotMatchRegex(new Regex(string.Empty)); - // Assert - act.Should().ThrowExactly() - .WithMessage("Cannot match string against an empty regex pattern. Provide a regex pattern or use the NotBeEmpty method.*") - .WithParameterName("regularExpression"); + // Assert + act.Should().ThrowExactly() + .WithMessage("Cannot match string against an empty regex pattern. Provide a regex pattern or use the NotBeEmpty method.*") + .WithParameterName("regularExpression"); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWith.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWith.cs index 6f29dbbbe9..abea632f32 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWith.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWith.cs @@ -10,168 +10,166 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Start With - - [Fact] - public void When_asserting_string_starts_with_the_same_value_it_should_not_throw() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().StartWith("AB"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_string_does_not_start_with_expected_phrase_it_should_throw() - { - // Act - Action act = () => "ABC".Should().StartWith("ABB", "it should {0}", "start"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to start with \"ABB\" because it should start," + - " but \"ABC\" differs near \"C\" (index 2)."); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_string_does_not_start_with_expected_phrase_and_one_of_them_is_long_it_should_display_both_strings_on_separate_line() - { - // Act - Action act = () => "ABCDEFGHI".Should().StartWith("ABCDDFGHI", "it should {0}", "start"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to start with " + - "*\"ABCDDFGHI\" because it should start, but " + - "*\"ABCDEFGHI\" differs near \"EFG\" (index 4)."); - } - - [Fact] - public void When_string_start_is_compared_with_null_it_should_throw() - { - // Act - Action act = () => "ABC".Should().StartWith(null); - - // Assert - act.Should().Throw().WithMessage( - "Cannot compare start of string with .*"); - } - - [Fact] - public void When_string_start_is_compared_with_empty_string_it_should_not_throw() - { - // Act - Action act = () => "ABC".Should().StartWith(""); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_string_start_is_compared_with_string_that_is_longer_it_should_throw() - { - // Act - Action act = () => "ABC".Should().StartWith("ABCDEF"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to start with \"ABCDEF\", but \"ABC\" is too short."); - } - - [Fact] - public void When_string_start_is_compared_and_actual_value_is_null_then_it_should_throw() + public class StartWith { - // Act - string someString = null; - Action act = () => someString.Should().StartWith("ABC"); - - // Assert - act.Should().Throw() - .WithMessage("Expected someString to start with \"ABC\", but found ."); + [Fact] + public void When_asserting_string_starts_with_the_same_value_it_should_not_throw() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().StartWith("AB"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_string_does_not_start_with_expected_phrase_it_should_throw() + { + // Act + Action act = () => "ABC".Should().StartWith("ABB", "it should {0}", "start"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to start with \"ABB\" because it should start," + + " but \"ABC\" differs near \"C\" (index 2)."); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_string_does_not_start_with_expected_phrase_and_one_of_them_is_long_it_should_display_both_strings_on_separate_line() + { + // Act + Action act = () => "ABCDEFGHI".Should().StartWith("ABCDDFGHI", "it should {0}", "start"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to start with " + + "*\"ABCDDFGHI\" because it should start, but " + + "*\"ABCDEFGHI\" differs near \"EFG\" (index 4)."); + } + + [Fact] + public void When_string_start_is_compared_with_null_it_should_throw() + { + // Act + Action act = () => "ABC".Should().StartWith(null); + + // Assert + act.Should().Throw().WithMessage( + "Cannot compare start of string with .*"); + } + + [Fact] + public void When_string_start_is_compared_with_empty_string_it_should_not_throw() + { + // Act + Action act = () => "ABC".Should().StartWith(""); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_string_start_is_compared_with_string_that_is_longer_it_should_throw() + { + // Act + Action act = () => "ABC".Should().StartWith("ABCDEF"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to start with \"ABCDEF\", but \"ABC\" is too short."); + } + + [Fact] + public void When_string_start_is_compared_and_actual_value_is_null_then_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().StartWith("ABC"); + + // Assert + act.Should().Throw() + .WithMessage("Expected someString to start with \"ABC\", but found ."); + } } - #endregion - - #region Not Start With - - [Fact] - public void When_asserting_string_does_not_start_with_a_value_and_it_does_not_it_should_succeed() + public class NotStartWith { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWith("DE"); - - // Assert - action.Should().NotThrow(); + [Fact] + public void When_asserting_string_does_not_start_with_a_value_and_it_does_not_it_should_succeed() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWith("DE"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_string_does_not_start_with_a_value_but_it_does_it_should_fail_with_a_descriptive_message() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWith("AB", "because of some reason"); + + // Assert + action.Should().Throw().WithMessage( + "Expected value that does not start with \"AB\" because of some reason, but found \"ABC\"."); + } + + [Fact] + public void When_asserting_string_does_not_start_with_a_value_that_is_null_it_should_throw() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWith(null); + + // Assert + action.Should().Throw().WithMessage( + "Cannot compare start of string with .*"); + } + + [Fact] + public void When_asserting_string_does_not_start_with_a_value_that_is_empty_it_should_throw() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWith(""); + + // Assert + action.Should().Throw().WithMessage( + "Expected value that does not start with \"\", but found \"ABC\"."); + } + + [Fact] + public void When_asserting_string_does_not_start_with_a_value_and_actual_value_is_null_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().NotStartWith("ABC"); + + // Assert + act.Should().Throw().WithMessage( + "Expected someString that does not start with \"ABC\", but found ."); + } } - - [Fact] - public void When_asserting_string_does_not_start_with_a_value_but_it_does_it_should_fail_with_a_descriptive_message() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWith("AB", "because of some reason"); - - // Assert - action.Should().Throw().WithMessage( - "Expected value that does not start with \"AB\" because of some reason, but found \"ABC\"."); - } - - [Fact] - public void When_asserting_string_does_not_start_with_a_value_that_is_null_it_should_throw() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWith(null); - - // Assert - action.Should().Throw().WithMessage( - "Cannot compare start of string with .*"); - } - - [Fact] - public void When_asserting_string_does_not_start_with_a_value_that_is_empty_it_should_throw() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWith(""); - - // Assert - action.Should().Throw().WithMessage( - "Expected value that does not start with \"\", but found \"ABC\"."); - } - - [Fact] - public void When_asserting_string_does_not_start_with_a_value_and_actual_value_is_null_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().NotStartWith("ABC"); - - // Assert - act.Should().Throw().WithMessage( - "Expected someString that does not start with \"ABC\", but found ."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWithEquivalentOf.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWithEquivalentOf.cs index c2923890cc..85cdcb0923 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWithEquivalentOf.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.StartWithEquivalentOf.cs @@ -10,168 +10,166 @@ namespace FluentAssertions.Specs.Primitives /// public partial class StringAssertionSpecs { - #region Start With Equivalent - - [Fact] - public void When_start_of_string_differs_by_case_only_it_should_not_throw() + public class StartWithEquivalent { - // Arrange - string actual = "ABC"; - string expectedPrefix = "Ab"; - - // Act / Assert - actual.Should().StartWithEquivalentOf(expectedPrefix); + [Fact] + public void When_start_of_string_differs_by_case_only_it_should_not_throw() + { + // Arrange + string actual = "ABC"; + string expectedPrefix = "Ab"; + + // Act / Assert + actual.Should().StartWithEquivalentOf(expectedPrefix); + } + + [Fact] + public void When_start_of_string_does_not_meet_equivalent_it_should_throw() + { + // Act + Action act = () => "ABC".Should().StartWithEquivalentOf("bc", "because it should start"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to start with equivalent of \"bc\" because it should start, but \"ABC\" differs near \"ABC\" (index 0)."); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_start_of_string_does_not_meet_equivalent_and_one_of_them_is_long_it_should_display_both_strings_on_separate_line() + { + // Act + Action act = () => "ABCDEFGHI".Should().StartWithEquivalentOf("abcddfghi", "it should {0}", "start"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to start with equivalent of " + + "*\"abcddfghi\" because it should start, but " + + "*\"ABCDEFGHI\" differs near \"EFG\" (index 4)."); + } + + [Fact] + public void When_start_of_string_is_compared_with_equivalent_of_null_it_should_throw() + { + // Act + Action act = () => "ABC".Should().StartWithEquivalentOf(null); + + // Assert + act.Should().Throw().WithMessage( + "Cannot compare string start equivalence with .*"); + } + + [Fact] + public void When_start_of_string_is_compared_with_equivalent_of_empty_string_it_should_not_throw() + { + // Act + Action act = () => "ABC".Should().StartWithEquivalentOf(""); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_start_of_string_is_compared_with_equivalent_of_string_that_is_longer_it_should_throw() + { + // Act + Action act = () => "ABC".Should().StartWithEquivalentOf("abcdef"); + + // Assert + act.Should().Throw().WithMessage( + "Expected string to start with equivalent of " + + "\"abcdef\", but " + + "\"ABC\" is too short."); + } + + [Fact] + public void When_string_start_is_compared_with_equivalent_and_actual_value_is_null_then_it_should_throw() + { + // Act + string someString = null; + Action act = () => someString.Should().StartWithEquivalentOf("AbC"); + + // Assert + act.Should().Throw() + .WithMessage("Expected someString to start with equivalent of \"AbC\", but found ."); + } } - [Fact] - public void When_start_of_string_does_not_meet_equivalent_it_should_throw() + public class NotStartWithEquivalent { - // Act - Action act = () => "ABC".Should().StartWithEquivalentOf("bc", "because it should start"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to start with equivalent of \"bc\" because it should start, but \"ABC\" differs near \"ABC\" (index 0)."); + [Fact] + public void When_asserting_string_does_not_start_with_equivalent_of_a_value_and_it_does_not_it_should_succeed() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWithEquivalentOf("Bc"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_string_does_not_start_with_equivalent_of_a_value_but_it_does_it_should_fail_with_a_descriptive_message() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWithEquivalentOf("aB", "because of some reason"); + + // Assert + action.Should().Throw().WithMessage( + "Expected value that does not start with equivalent of \"aB\" because of some reason, but found \"ABC\"."); + } + + [Fact] + public void When_asserting_string_does_not_start_with_equivalent_of_a_value_that_is_null_it_should_throw() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWithEquivalentOf(null); + + // Assert + action.Should().Throw().WithMessage( + "Cannot compare start of string with .*"); + } + + [Fact] + public void When_asserting_string_does_not_start_with_equivalent_of_a_value_that_is_empty_it_should_throw() + { + // Arrange + string value = "ABC"; + + // Act + Action action = () => + value.Should().NotStartWithEquivalentOf(""); + + // Assert + action.Should().Throw().WithMessage( + "Expected value that does not start with equivalent of \"\", but found \"ABC\"."); + } + + [Fact] + public void When_asserting_string_does_not_start_with_equivalent_of_a_value_and_actual_value_is_null_it_should_throw() + { + // Arrange + string someString = null; + + // Act + Action act = () => someString.Should().NotStartWithEquivalentOf("ABC"); + + // Assert + act.Should().Throw().WithMessage( + "Expected someString that does not start with equivalent of \"ABC\", but found ."); + } } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_start_of_string_does_not_meet_equivalent_and_one_of_them_is_long_it_should_display_both_strings_on_separate_line() - { - // Act - Action act = () => "ABCDEFGHI".Should().StartWithEquivalentOf("abcddfghi", "it should {0}", "start"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to start with equivalent of " + - "*\"abcddfghi\" because it should start, but " + - "*\"ABCDEFGHI\" differs near \"EFG\" (index 4)."); - } - - [Fact] - public void When_start_of_string_is_compared_with_equivalent_of_null_it_should_throw() - { - // Act - Action act = () => "ABC".Should().StartWithEquivalentOf(null); - - // Assert - act.Should().Throw().WithMessage( - "Cannot compare string start equivalence with .*"); - } - - [Fact] - public void When_start_of_string_is_compared_with_equivalent_of_empty_string_it_should_not_throw() - { - // Act - Action act = () => "ABC".Should().StartWithEquivalentOf(""); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_start_of_string_is_compared_with_equivalent_of_string_that_is_longer_it_should_throw() - { - // Act - Action act = () => "ABC".Should().StartWithEquivalentOf("abcdef"); - - // Assert - act.Should().Throw().WithMessage( - "Expected string to start with equivalent of " + - "\"abcdef\", but " + - "\"ABC\" is too short."); - } - - [Fact] - public void When_string_start_is_compared_with_equivalent_and_actual_value_is_null_then_it_should_throw() - { - // Act - string someString = null; - Action act = () => someString.Should().StartWithEquivalentOf("AbC"); - - // Assert - act.Should().Throw() - .WithMessage("Expected someString to start with equivalent of \"AbC\", but found ."); - } - - #endregion - - #region Not Start With Equivalent - - [Fact] - public void When_asserting_string_does_not_start_with_equivalent_of_a_value_and_it_does_not_it_should_succeed() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWithEquivalentOf("Bc"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_string_does_not_start_with_equivalent_of_a_value_but_it_does_it_should_fail_with_a_descriptive_message() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWithEquivalentOf("aB", "because of some reason"); - - // Assert - action.Should().Throw().WithMessage( - "Expected value that does not start with equivalent of \"aB\" because of some reason, but found \"ABC\"."); - } - - [Fact] - public void When_asserting_string_does_not_start_with_equivalent_of_a_value_that_is_null_it_should_throw() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWithEquivalentOf(null); - - // Assert - action.Should().Throw().WithMessage( - "Cannot compare start of string with .*"); - } - - [Fact] - public void When_asserting_string_does_not_start_with_equivalent_of_a_value_that_is_empty_it_should_throw() - { - // Arrange - string value = "ABC"; - - // Act - Action action = () => - value.Should().NotStartWithEquivalentOf(""); - - // Assert - action.Should().Throw().WithMessage( - "Expected value that does not start with equivalent of \"\", but found \"ABC\"."); - } - - [Fact] - public void When_asserting_string_does_not_start_with_equivalent_of_a_value_and_actual_value_is_null_it_should_throw() - { - // Arrange - string someString = null; - - // Act - Action act = () => someString.Should().NotStartWithEquivalentOf("ABC"); - - // Assert - act.Should().Throw().WithMessage( - "Expected someString that does not start with equivalent of \"ABC\", but found ."); - } - - #endregion } } From 09dc7fd1e0316e5f4e251c5dcdd68901f9e4a054 Mon Sep 17 00:00:00 2001 From: Andrew Lock Date: Thu, 21 Apr 2022 09:18:35 +0100 Subject: [PATCH 33/48] Update docxml comments on BeInRange It wasn't clear whether the values where inclusive or exclusive --- Src/FluentAssertions/Numeric/NumericAssertions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/FluentAssertions/Numeric/NumericAssertions.cs b/Src/FluentAssertions/Numeric/NumericAssertions.cs index 62d06e1d7d..9a6284149f 100644 --- a/Src/FluentAssertions/Numeric/NumericAssertions.cs +++ b/Src/FluentAssertions/Numeric/NumericAssertions.cs @@ -292,10 +292,10 @@ public AndConstraint BeLessThan(T expected, string because = "", pa /// Where the range is continuous or incremental depends on the actual type of the value. /// /// - /// The minimum valid value of the range. + /// The minimum valid value of the range (inclusive). /// /// - /// The maximum valid value of the range. + /// The maximum valid value of the range (inclusive). /// /// /// A formatted phrase as is supported by explaining why the assertion From 36341636cc80958c448871712c29b7367a3f3979 Mon Sep 17 00:00:00 2001 From: Jonas Nyrup Date: Mon, 18 Apr 2022 21:17:21 +0200 Subject: [PATCH 34/48] Try to stabilize UIFact tests by running them sequentially --- .../AsyncFunctionExceptionAssertionSpecs.cs | 159 +++++++++-------- .../Execution/CallerIdentifierSpecs.cs | 30 ++-- .../Specialized/TaskAssertionSpecs.cs | 77 +++++---- .../Specialized/TaskOfTAssertionSpecs.cs | 161 ++++++++++-------- .../UIFactsDefinition.cs | 8 + 5 files changed, 243 insertions(+), 192 deletions(-) create mode 100644 Tests/FluentAssertions.Specs/UIFactsDefinition.cs diff --git a/Tests/FluentAssertions.Specs/Exceptions/AsyncFunctionExceptionAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Exceptions/AsyncFunctionExceptionAssertionSpecs.cs index f454271169..0b686b1da3 100644 --- a/Tests/FluentAssertions.Specs/Exceptions/AsyncFunctionExceptionAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Exceptions/AsyncFunctionExceptionAssertionSpecs.cs @@ -84,17 +84,21 @@ public async Task When_async_method_throws_an_empty_AggregateException_it_should await act2.Should().ThrowAsync(); } - [UIFact] - public async Task When_async_method_throws_an_empty_AggregateException_on_UI_thread_it_should_fail() + [Collection("UIFacts")] + public partial class UIFacts { - // Arrange - Func act = () => throw new AggregateException(); + [UIFact] + public async Task When_async_method_throws_an_empty_AggregateException_on_UI_thread_it_should_fail() + { + // Arrange + Func act = () => throw new AggregateException(); - // Act - Func act2 = () => act.Should().NotThrowAsync(); + // Act + Func act2 = () => act.Should().NotThrowAsync(); - // Assert - await act2.Should().ThrowAsync(); + // Assert + await act2.Should().ThrowAsync(); + } } [Fact] @@ -107,14 +111,17 @@ public async Task When_async_method_throws_a_nested_AggregateException_it_should await act.Should().ThrowAsync().WithMessage("That was wrong."); } - [UIFact] - public async Task When_async_method_throws_a_nested_AggregateException_on_UI_thread_it_should_provide_the_message() + public partial class UIFacts { - // Arrange - Func act = () => throw new AggregateException(new ArgumentException("That was wrong.")); + [UIFact] + public async Task When_async_method_throws_a_nested_AggregateException_on_UI_thread_it_should_provide_the_message() + { + // Arrange + Func act = () => throw new AggregateException(new ArgumentException("That was wrong.")); - // Act & Assert - await act.Should().ThrowAsync().WithMessage("That was wrong."); + // Act & Assert + await act.Should().ThrowAsync().WithMessage("That was wrong."); + } } [Fact] @@ -499,17 +506,20 @@ public async Task When_async_method_does_not_throw_async_exception_and_that_was_ await action.Should().NotThrowAsync(); } - [UIFact] - public async Task When_async_method_does_not_throw_async_exception_on_UI_thread_and_that_was_expected_it_should_succeed() + public partial class UIFacts { - // Arrange - var asyncObject = new AsyncClass(); + [UIFact] + public async Task When_async_method_does_not_throw_async_exception_on_UI_thread_and_that_was_expected_it_should_succeed() + { + // Arrange + var asyncObject = new AsyncClass(); - // Act - Func action = () => asyncObject.SucceedAsync(); + // Act + Func action = () => asyncObject.SucceedAsync(); - // Assert - await action.Should().NotThrowAsync(); + // Assert + await action.Should().NotThrowAsync(); + } } [Fact] @@ -605,17 +615,20 @@ public async Task When_subject_throws_expected_async_exact_exception_it_should_s await action.Should().ThrowExactlyAsync("because {0} should do that", "IFoo.Do"); } - [UIFact] - public async Task When_subject_throws_on_UI_thread_expected_async_exact_exception_it_should_succeed() + public partial class UIFacts { - // Arrange - var asyncObject = new AsyncClass(); + [UIFact] + public async Task When_subject_throws_on_UI_thread_expected_async_exact_exception_it_should_succeed() + { + // Arrange + var asyncObject = new AsyncClass(); - // Act - Func action = () => asyncObject.ThrowAsync(); + // Act + Func action = () => asyncObject.ThrowAsync(); - // Assert - await action.Should().ThrowExactlyAsync("because {0} should do that", "IFoo.Do"); + // Assert + await action.Should().ThrowExactlyAsync("because {0} should do that", "IFoo.Do"); + } } [Fact] @@ -1205,34 +1218,37 @@ await action.Should().ThrowAsync() .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); } - [UIFact] - public async Task When_no_exception_should_be_thrown_on_UI_thread_for_async_func_after_wait_time_but_it_was_it_should_throw() + public partial class UIFacts { - // Arrange - var waitTime = 2.Seconds(); - var pollInterval = 10.Milliseconds(); + [UIFact] + public async Task When_no_exception_should_be_thrown_on_UI_thread_for_async_func_after_wait_time_but_it_was_it_should_throw() + { + // Arrange + var waitTime = 2.Seconds(); + var pollInterval = 10.Milliseconds(); - var clock = new FakeClock(); - var timer = clock.StartTimer(); - clock.CompleteAfter(waitTime); + var clock = new FakeClock(); + var timer = clock.StartTimer(); + clock.CompleteAfter(waitTime); - Func throwLongerThanWaitTime = async () => - { - if (timer.Elapsed <= waitTime.Multiply(1.5)) + Func throwLongerThanWaitTime = async () => { - throw new ArgumentException("An exception was forced"); - } + if (timer.Elapsed <= waitTime.Multiply(1.5)) + { + throw new ArgumentException("An exception was forced"); + } - await Task.Yield(); - }; + await Task.Yield(); + }; - // Act - Func action = () => throwLongerThanWaitTime.Should(clock) - .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); + // Act + Func action = () => throwLongerThanWaitTime.Should(clock) + .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); - // Assert - await action.Should().ThrowAsync() - .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); + // Assert + await action.Should().ThrowAsync() + .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); + } } [Fact] @@ -1263,32 +1279,35 @@ public async Task When_no_exception_should_be_thrown_for_async_func_after_wait_t await act.Should().NotThrowAsync(); } - [UIFact] - public async Task When_no_exception_should_be_thrown_on_UI_thread_for_async_func_after_wait_time_and_none_was_it_should_not_throw() + public partial class UIFacts { - // Arrange - var waitTime = 6.Seconds(); - var pollInterval = 10.Milliseconds(); + [UIFact] + public async Task When_no_exception_should_be_thrown_on_UI_thread_for_async_func_after_wait_time_and_none_was_it_should_not_throw() + { + // Arrange + var waitTime = 6.Seconds(); + var pollInterval = 10.Milliseconds(); - var clock = new FakeClock(); - var timer = clock.StartTimer(); - clock.Delay(waitTime); + var clock = new FakeClock(); + var timer = clock.StartTimer(); + clock.Delay(waitTime); - Func throwShorterThanWaitTime = async () => - { - if (timer.Elapsed <= waitTime.Divide(12)) + Func throwShorterThanWaitTime = async () => { - throw new ArgumentException("An exception was forced"); - } + if (timer.Elapsed <= waitTime.Divide(12)) + { + throw new ArgumentException("An exception was forced"); + } - await Task.Yield(); - }; + await Task.Yield(); + }; - // Act - Func act = () => throwShorterThanWaitTime.Should(clock).NotThrowAfterAsync(waitTime, pollInterval); + // Act + Func act = () => throwShorterThanWaitTime.Should(clock).NotThrowAfterAsync(waitTime, pollInterval); - // Assert - await act.Should().NotThrowAsync(); + // Assert + await act.Should().NotThrowAsync(); + } } #endregion } diff --git a/Tests/FluentAssertions.Specs/Execution/CallerIdentifierSpecs.cs b/Tests/FluentAssertions.Specs/Execution/CallerIdentifierSpecs.cs index 61dbaac438..b463e4c6b9 100644 --- a/Tests/FluentAssertions.Specs/Execution/CallerIdentifierSpecs.cs +++ b/Tests/FluentAssertions.Specs/Execution/CallerIdentifierSpecs.cs @@ -455,20 +455,24 @@ public void When_the_method_has_Should_prefix_it_should_read_whole_method() .WithMessage("Expected foo.ShouldReturnSomeBool() to be false*"); } - [UIFact] - public async Task Caller_identification_should_also_work_for_statements_following_async_code() + [Collection("UIFacts")] + public partial class UIFacts { - // Arrange - const string someText = "Hello"; - Func task = async () => await Task.Yield(); - - // Act - await task.Should().NotThrowAsync(); - Action act = () => someText.Should().Be("Hi"); - - // Assert - act.Should().Throw() - .WithMessage("*someText*", "it should capture the variable name"); + [UIFact] + public async Task Caller_identification_should_also_work_for_statements_following_async_code() + { + // Arrange + const string someText = "Hello"; + Func task = async () => await Task.Yield(); + + // Act + await task.Should().NotThrowAsync(); + Action act = () => someText.Should().Be("Hi"); + + // Assert + act.Should().Throw() + .WithMessage("*someText*", "it should capture the variable name"); + } } [Fact] diff --git a/Tests/FluentAssertions.Specs/Specialized/TaskAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/TaskAssertionSpecs.cs index 3f6f5237f9..defe801a43 100644 --- a/Tests/FluentAssertions.Specs/Specialized/TaskAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/TaskAssertionSpecs.cs @@ -79,20 +79,24 @@ public async Task Sync_work_in_async_method_is_taken_into_account() await action.Should().ThrowAsync(); } - [UIFact] - public async Task When_task_completes_on_UI_thread_fast_async_it_should_succeed() + [Collection("UIFacts")] + public partial class UIFacts { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); + [UIFact] + public async Task When_task_completes_on_UI_thread_fast_async_it_should_succeed() + { + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - // Act - Func action = () => taskFactory.Awaiting(t => (Task)t.Task).Should(timer).CompleteWithinAsync(100.Milliseconds()); - taskFactory.SetResult(true); - timer.Complete(); + // Act + Func action = () => taskFactory.Awaiting(t => (Task)t.Task).Should(timer).CompleteWithinAsync(100.Milliseconds()); + taskFactory.SetResult(true); + timer.Complete(); - // Assert - await action.Should().NotThrowAsync(); + // Assert + await action.Should().NotThrowAsync(); + } } [Fact] @@ -110,37 +114,40 @@ public async Task When_task_completes_slow_async_it_should_fail() await action.Should().ThrowAsync(); } - [UIFact] - public async Task When_task_completes_on_UI_thread_slow_async_it_should_fail() + public partial class UIFacts { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); + [UIFact] + public async Task When_task_completes_on_UI_thread_slow_async_it_should_fail() + { + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - // Act - Func action = () => taskFactory.Awaiting(t => (Task)t.Task).Should(timer).CompleteWithinAsync(100.Milliseconds()); - timer.Complete(); + // Act + Func action = () => taskFactory.Awaiting(t => (Task)t.Task).Should(timer).CompleteWithinAsync(100.Milliseconds()); + timer.Complete(); - // Assert - await action.Should().ThrowAsync(); - } + // Assert + await action.Should().ThrowAsync(); + } - [UIFact] - public async Task When_task_is_checking_synchronization_context_on_UI_thread_it_should_succeed() - { - // Arrange - Func task = CheckContextAsync; + [UIFact] + public async Task When_task_is_checking_synchronization_context_on_UI_thread_it_should_succeed() + { + // Arrange + Func task = CheckContextAsync; - // Act - Func action = () => this.Awaiting(x => task()).Should().CompleteWithinAsync(1.Seconds()); + // Act + Func action = () => this.Awaiting(x => task()).Should().CompleteWithinAsync(1.Seconds()); - // Assert - await action.Should().NotThrowAsync(); + // Assert + await action.Should().NotThrowAsync(); - async Task CheckContextAsync() - { - await Task.Delay(1); - SynchronizationContext.Current.Should().NotBeNull(); + async Task CheckContextAsync() + { + await Task.Delay(1); + SynchronizationContext.Current.Should().NotBeNull(); + } } } } diff --git a/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs index 64291955ee..d713c177f0 100644 --- a/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs @@ -190,27 +190,31 @@ public async Task When_task_does_not_throw_async_it_should_succeed() await action.Should().NotThrowAsync(); } - [UIFact] - public async Task When_task_does_not_throw_async_on_UI_thread_it_should_succeed() + [Collection("UIFacts")] + public partial class UIFacts { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); - - // Act - Func action = async () => + [UIFact] + public async Task When_task_does_not_throw_async_on_UI_thread_it_should_succeed() { - Func> func = () => taskFactory.Task; + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - (await func.Should(timer).NotThrowAsync()) - .Which.Should().Be(42); - }; + // Act + Func action = async () => + { + Func> func = () => taskFactory.Task; - taskFactory.SetResult(42); - timer.Complete(); + (await func.Should(timer).NotThrowAsync()) + .Which.Should().Be(42); + }; - // Assert - await action.Should().NotThrowAsync(); + taskFactory.SetResult(42); + timer.Complete(); + + // Assert + await action.Should().NotThrowAsync(); + } } [Fact] @@ -231,22 +235,25 @@ public async Task When_task_throws_async_it_should_fail() await action.Should().ThrowAsync(); } - [UIFact] - public async Task When_task_throws_async_on_UI_thread_it_should_fail() + public partial class UIFacts { - // Arrange - var timer = new FakeClock(); - - // Act - Func action = () => + [UIFact] + public async Task When_task_throws_async_on_UI_thread_it_should_fail() { - Func> func = () => throw new AggregateException(); + // Arrange + var timer = new FakeClock(); - return func.Should(timer).NotThrowAsync(); - }; + // Act + Func action = () => + { + Func> func = () => throw new AggregateException(); - // Assert - await action.Should().ThrowAsync(); + return func.Should(timer).NotThrowAsync(); + }; + + // Assert + await action.Should().ThrowAsync(); + } } [Fact] @@ -351,35 +358,38 @@ await action.Should().ThrowAsync() .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); } - [UIFact] - public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_but_it_was_it_should_throw() + public partial class UIFacts { - // Arrange - var waitTime = 2.Seconds(); - var pollInterval = 10.Milliseconds(); + [UIFact] + public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_but_it_was_it_should_throw() + { + // Arrange + var waitTime = 2.Seconds(); + var pollInterval = 10.Milliseconds(); - var clock = new FakeClock(); - var timer = clock.StartTimer(); - clock.CompleteAfter(waitTime); + var clock = new FakeClock(); + var timer = clock.StartTimer(); + clock.CompleteAfter(waitTime); - Func> throwLongerThanWaitTime = async () => - { - if (timer.Elapsed <= waitTime.Multiply(1.5)) + Func> throwLongerThanWaitTime = async () => { - throw new ArgumentException("An exception was forced"); - } + if (timer.Elapsed <= waitTime.Multiply(1.5)) + { + throw new ArgumentException("An exception was forced"); + } - await Task.Yield(); - return 42; - }; + await Task.Yield(); + return 42; + }; - // Act - Func action = () => throwLongerThanWaitTime.Should(clock) - .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); + // Act + Func action = () => throwLongerThanWaitTime.Should(clock) + .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); - // Assert - await action.Should().ThrowAsync() - .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); + // Assert + await action.Should().ThrowAsync() + .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); + } } [Fact] @@ -415,37 +425,40 @@ public async Task When_no_exception_should_be_thrown_async_after_wait_time_and_n await act.Should().NotThrowAsync(); } - [UIFact] - public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_and_none_was_it_should_not_throw() + public partial class UIFacts { - // Arrange - var waitTime = 6.Seconds(); - var pollInterval = 10.Milliseconds(); + [UIFact] + public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_and_none_was_it_should_not_throw() + { + // Arrange + var waitTime = 6.Seconds(); + var pollInterval = 10.Milliseconds(); - var clock = new FakeClock(); - var timer = clock.StartTimer(); - clock.Delay(waitTime); + var clock = new FakeClock(); + var timer = clock.StartTimer(); + clock.Delay(waitTime); - Func> throwShorterThanWaitTime = async () => - { - if (timer.Elapsed <= waitTime.Divide(12)) + Func> throwShorterThanWaitTime = async () => { - throw new ArgumentException("An exception was forced"); - } + if (timer.Elapsed <= waitTime.Divide(12)) + { + throw new ArgumentException("An exception was forced"); + } - await Task.Yield(); - return 42; - }; + await Task.Yield(); + return 42; + }; - // Act - Func act = async () => - { - (await throwShorterThanWaitTime.Should(clock).NotThrowAfterAsync(waitTime, pollInterval)) - .Which.Should().Be(42); - }; + // Act + Func act = async () => + { + (await throwShorterThanWaitTime.Should(clock).NotThrowAfterAsync(waitTime, pollInterval)) + .Which.Should().Be(42); + }; - // Assert - await act.Should().NotThrowAsync(); + // Assert + await act.Should().NotThrowAsync(); + } } #endregion diff --git a/Tests/FluentAssertions.Specs/UIFactsDefinition.cs b/Tests/FluentAssertions.Specs/UIFactsDefinition.cs new file mode 100644 index 0000000000..40bbd58db4 --- /dev/null +++ b/Tests/FluentAssertions.Specs/UIFactsDefinition.cs @@ -0,0 +1,8 @@ +using Xunit; + +namespace FluentAssertions.Specs +{ + // Try to stabilize UIFact tests + [CollectionDefinition("UIFacts", DisableParallelization = true)] + public class UIFactsDefinition { } +} From 17fedb165a5039fb3853e0133c461f209dbd7ddf Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Tue, 19 Apr 2022 17:24:07 +0200 Subject: [PATCH 35/48] Seperate all `Collection` assertions into nested classes --- ...lectionAssertionSpecs.AllBeAssignableTo.cs | 255 +- .../CollectionAssertionSpecs.AllBeOfType.cs | 223 +- .../CollectionAssertionSpecs.BeEmpty.cs | 272 +- ...CollectionAssertionSpecs.BeEquivalentTo.cs | 536 ++- ...ectionAssertionSpecs.BeInAscendingOrder.cs | 242 +- ...ctionAssertionSpecs.BeInDescendingOrder.cs | 152 +- .../CollectionAssertionSpecs.BeNull.cs | 82 +- .../CollectionAssertionSpecs.BeNullOrEmpty.cs | 208 +- .../CollectionAssertionSpecs.BeSubsetOf.cs | 256 +- .../CollectionAssertionSpecs.Contain.cs | 690 ++- ...ctionAssertionSpecs.ContainEquivalentOf.cs | 652 ++- ...CollectionAssertionSpecs.ContainInOrder.cs | 416 +- ...AssertionSpecs.ContainItemsAssignableTo.cs | 101 +- .../CollectionAssertionSpecs.EndWith.cs | 349 +- .../CollectionAssertionSpecs.Equal.cs | 672 ++- .../CollectionAssertionSpecs.HaveCount.cs | 362 +- ...tionAssertionSpecs.HaveCountGreaterThan.cs | 89 +- ...tionSpecs.HaveCountGreaterThanOrEqualTo.cs | 89 +- ...lectionAssertionSpecs.HaveCountLessThan.cs | 89 +- ...sertionSpecs.HaveCountLessThanOrEqualTo.cs | 89 +- .../CollectionAssertionSpecs.HaveElementAt.cs | 143 +- ...tionAssertionSpecs.HaveElementPreceding.cs | 217 +- ...ionAssertionSpecs.HaveElementSucceeding.cs | 213 +- .../CollectionAssertionSpecs.HaveSameCount.cs | 288 +- .../CollectionAssertionSpecs.IntersectWith.cs | 184 +- ...ollectionAssertionSpecs.NotContainNulls.cs | 273 +- .../CollectionAssertionSpecs.OnlyContain.cs | 147 +- ...ctionAssertionSpecs.OnlyHaveUniqueItems.cs | 259 +- .../CollectionAssertionSpecs.Satisfy.cs | 355 +- ...ctionAssertionSpecs.SatisfyRespectively.cs | 297 +- .../CollectionAssertionSpecs.StartWith.cs | 327 +- .../GenericDictionaryAssertionSpecs.cs | 4213 ++++++++--------- 32 files changed, 6349 insertions(+), 6391 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeAssignableTo.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeAssignableTo.cs index 26cd0a4f0c..f142c0baf5 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeAssignableTo.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeAssignableTo.cs @@ -11,161 +11,160 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region All Be Assignable To - - [Fact] - public void When_the_types_in_a_collection_is_matched_against_a_null_type_it_should_throw() + public class AllBeAssignableTo { - // Arrange - var collection = new int[0]; + [Fact] + public void When_the_types_in_a_collection_is_matched_against_a_null_type_it_should_throw() + { + // Arrange + var collection = new int[0]; - // Act - Action act = () => collection.Should().AllBeAssignableTo(null); + // Act + Action act = () => collection.Should().AllBeAssignableTo(null); - // Assert - act.Should().Throw() - .WithParameterName("expectedType"); - } - - [Fact] - public void When_collection_is_null_then_all_be_assignable_to_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw() + .WithParameterName("expectedType"); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_all_be_assignable_to_should_fail() { - using var _ = new AssertionScope(); - collection.Should().AllBeAssignableTo(typeof(object), "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); - } - - [Fact] - public void When_all_of_the_types_in_a_collection_match_expected_type_it_should_succeed() - { - // Arrange - var collection = new int[] { 1, 2, 3 }; + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().AllBeAssignableTo(typeof(object), "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); + } + + [Fact] + public void When_all_of_the_types_in_a_collection_match_expected_type_it_should_succeed() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; - // Act / Assert - collection.Should().AllBeAssignableTo(); - } + // Act / Assert + collection.Should().AllBeAssignableTo(); + } - [Fact] - public void When_matching_a_collection_against_a_type_it_should_return_the_casted_items() - { - // Arrange - var collection = new int[] { 1, 2, 3 }; + [Fact] + public void When_matching_a_collection_against_a_type_it_should_return_the_casted_items() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; - // Act / Assert - collection.Should().AllBeAssignableTo() - .Which.Should().Equal(1, 2, 3); - } + // Act / Assert + collection.Should().AllBeAssignableTo() + .Which.Should().Equal(1, 2, 3); + } - [Fact] - public void When_all_of_the_types_in_a_collection_match_the_type_or_subtype_it_should_succeed() - { - // Arrange - var collection = new object[] { new Exception(), new ArgumentException() }; + [Fact] + public void When_all_of_the_types_in_a_collection_match_the_type_or_subtype_it_should_succeed() + { + // Arrange + var collection = new object[] { new Exception(), new ArgumentException() }; - // Act / Assert - collection.Should().AllBeAssignableTo(); - } + // Act / Assert + collection.Should().AllBeAssignableTo(); + } - [Fact] - public void When_one_of_the_types_does_not_match_it_should_throw_with_a_clear_explanation() - { - // Arrange - var collection = new object[] { 1, "2", 3 }; + [Fact] + public void When_one_of_the_types_does_not_match_it_should_throw_with_a_clear_explanation() + { + // Arrange + var collection = new object[] { 1, "2", 3 }; - // Act - Action act = () => collection.Should().AllBeAssignableTo("because they are of different type"); + // Act + Action act = () => collection.Should().AllBeAssignableTo("because they are of different type"); - // Assert - act.Should().Throw().WithMessage( - "Expected type to be \"System.Int32\" because they are of different type, but found \"[System.Int32, System.String, System.Int32]\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected type to be \"System.Int32\" because they are of different type, but found \"[System.Int32, System.String, System.Int32]\"."); + } - [Fact] - public void When_one_of_the_elements_is_null_it_should_throw_with_a_clear_explanation() - { - // Arrange - var collection = new object[] { 1, null, 3 }; + [Fact] + public void When_one_of_the_elements_is_null_it_should_throw_with_a_clear_explanation() + { + // Arrange + var collection = new object[] { 1, null, 3 }; - // Act - Action act = () => collection.Should().AllBeAssignableTo("because they are of different type"); + // Act + Action act = () => collection.Should().AllBeAssignableTo("because they are of different type"); - // Assert - act.Should().Throw().WithMessage( - "Expected type to be \"System.Int32\" because they are of different type, but found a null element."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected type to be \"System.Int32\" because they are of different type, but found a null element."); + } - [Fact] - public void When_collection_is_of_matching_types_it_should_succeed() - { - // Arrange - var collection = new Type[] { typeof(Exception), typeof(ArgumentException) }; + [Fact] + public void When_collection_is_of_matching_types_it_should_succeed() + { + // Arrange + var collection = new Type[] { typeof(Exception), typeof(ArgumentException) }; - // Act / Assert - collection.Should().AllBeAssignableTo(); - } + // Act / Assert + collection.Should().AllBeAssignableTo(); + } - [Fact] - public void When_collection_of_types_contains_one_type_that_does_not_match_it_should_throw_with_a_clear_explanation() - { - // Arrange - var collection = new Type[] { typeof(int), typeof(string), typeof(int) }; + [Fact] + public void When_collection_of_types_contains_one_type_that_does_not_match_it_should_throw_with_a_clear_explanation() + { + // Arrange + var collection = new Type[] { typeof(int), typeof(string), typeof(int) }; - // Act - Action act = () => collection.Should().AllBeAssignableTo("because they are of different type"); + // Act + Action act = () => collection.Should().AllBeAssignableTo("because they are of different type"); - // Assert - act.Should().Throw().WithMessage( - "Expected type to be \"System.Int32\" because they are of different type, but found \"[System.Int32, System.String, System.Int32]\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected type to be \"System.Int32\" because they are of different type, but found \"[System.Int32, System.String, System.Int32]\"."); + } - [Fact] - public void When_collection_of_types_and_objects_are_all_of_matching_types_it_should_succeed() - { - // Arrange - var collection = new object[] { typeof(int), 2, typeof(int) }; + [Fact] + public void When_collection_of_types_and_objects_are_all_of_matching_types_it_should_succeed() + { + // Arrange + var collection = new object[] { typeof(int), 2, typeof(int) }; - // Act / Assert - collection.Should().AllBeAssignableTo(); - } + // Act / Assert + collection.Should().AllBeAssignableTo(); + } - [Fact] - public void When_collection_of_different_types_and_objects_are_all_assignable_to_type_it_should_succeed() - { - // Arrange - var collection = new object[] { typeof(Exception), new ArgumentException() }; - - // Act / Assert - collection.Should().AllBeAssignableTo(); - } + [Fact] + public void When_collection_of_different_types_and_objects_are_all_assignable_to_type_it_should_succeed() + { + // Arrange + var collection = new object[] { typeof(Exception), new ArgumentException() }; - [Fact] - public void When_collection_is_null_then_all_be_assignable_toOfT_should_fail() - { - // Arrange - IEnumerable collection = null; + // Act / Assert + collection.Should().AllBeAssignableTo(); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_all_be_assignable_toOfT_should_fail() { - using var _ = new AssertionScope(); - collection.Should().AllBeAssignableTo("we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().AllBeAssignableTo("we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeOfType.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeOfType.cs index bb400381bd..5d8dc2b3b8 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeOfType.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.AllBeOfType.cs @@ -11,141 +11,140 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region All Be Of Type - - [Fact] - public void When_the_types_in_a_collection_is_matched_against_a_null_type_exactly_it_should_throw() + public class AllBeOfType { - // Arrange - var collection = new int[0]; + [Fact] + public void When_the_types_in_a_collection_is_matched_against_a_null_type_exactly_it_should_throw() + { + // Arrange + var collection = new int[0]; - // Act - Action act = () => collection.Should().AllBeOfType(null); + // Act + Action act = () => collection.Should().AllBeOfType(null); - // Assert - act.Should().Throw() - .WithParameterName("expectedType"); - } - - [Fact] - public void When_collection_is_null_then_all_be_of_type_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw() + .WithParameterName("expectedType"); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_all_be_of_type_should_fail() { - using var _ = new AssertionScope(); - collection.Should().AllBeOfType(typeof(object), "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); - } - - [Fact] - public void When_all_of_the_types_in_a_collection_match_expected_type_exactly_it_should_succeed() - { - // Arrange - var collection = new int[] { 1, 2, 3 }; + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().AllBeOfType(typeof(object), "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); + } + + [Fact] + public void When_all_of_the_types_in_a_collection_match_expected_type_exactly_it_should_succeed() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; - // Act / Assert - collection.Should().AllBeOfType(); - } + // Act / Assert + collection.Should().AllBeOfType(); + } - [Fact] - public void When_matching_a_collection_against_an_exact_type_it_should_return_the_casted_items() - { - // Arrange - var collection = new int[] { 1, 2, 3 }; + [Fact] + public void When_matching_a_collection_against_an_exact_type_it_should_return_the_casted_items() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; - // Act / Assert - collection.Should().AllBeOfType() - .Which.Should().Equal(1, 2, 3); - } + // Act / Assert + collection.Should().AllBeOfType() + .Which.Should().Equal(1, 2, 3); + } - [Fact] - public void When_one_of_the_types_does_not_match_exactly_it_should_throw_with_a_clear_explanation() - { - // Arrange - var collection = new object[] { new Exception(), new ArgumentException() }; + [Fact] + public void When_one_of_the_types_does_not_match_exactly_it_should_throw_with_a_clear_explanation() + { + // Arrange + var collection = new object[] { new Exception(), new ArgumentException() }; - // Act - Action act = () => collection.Should().AllBeOfType("because they are of different type"); + // Act + Action act = () => collection.Should().AllBeOfType("because they are of different type"); - // Assert - act.Should().Throw().WithMessage( - "Expected type to be \"System.Exception\" because they are of different type, but found \"[System.Exception, System.ArgumentException]\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected type to be \"System.Exception\" because they are of different type, but found \"[System.Exception, System.ArgumentException]\"."); + } - [Fact] - public void When_one_of_the_elements_is_null_for_an_exact_match_it_should_throw_with_a_clear_explanation() - { - // Arrange - var collection = new object[] { 1, null, 3 }; - - // Act - Action act = () => collection.Should().AllBeOfType("because they are of different type"); + [Fact] + public void When_one_of_the_elements_is_null_for_an_exact_match_it_should_throw_with_a_clear_explanation() + { + // Arrange + var collection = new object[] { 1, null, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected type to be \"System.Int32\" because they are of different type, but found a null element."); - } + // Act + Action act = () => collection.Should().AllBeOfType("because they are of different type"); - [Fact] - public void When_collection_of_types_match_expected_type_exactly_it_should_succeed() - { - // Arrange - var collection = new Type[] { typeof(int), typeof(int), typeof(int) }; + // Assert + act.Should().Throw().WithMessage( + "Expected type to be \"System.Int32\" because they are of different type, but found a null element."); + } - // Act / Assert - collection.Should().AllBeOfType(); - } + [Fact] + public void When_collection_of_types_match_expected_type_exactly_it_should_succeed() + { + // Arrange + var collection = new Type[] { typeof(int), typeof(int), typeof(int) }; - [Fact] - public void When_collection_of_types_and_objects_match_type_exactly_it_should_succeed() - { - // Arrange - var collection = new object[] { typeof(ArgumentException), new ArgumentException() }; + // Act / Assert + collection.Should().AllBeOfType(); + } - // Act / Assert - collection.Should().AllBeOfType(); - } + [Fact] + public void When_collection_of_types_and_objects_match_type_exactly_it_should_succeed() + { + // Arrange + var collection = new object[] { typeof(ArgumentException), new ArgumentException() }; - [Fact] - public void When_collection_of_types_and_objects_do_not_match_type_exactly_it_should_throw() - { - // Arrange - var collection = new object[] { typeof(Exception), new ArgumentException() }; + // Act / Assert + collection.Should().AllBeOfType(); + } - // Act - Action act = () => collection.Should().AllBeOfType(); + [Fact] + public void When_collection_of_types_and_objects_do_not_match_type_exactly_it_should_throw() + { + // Arrange + var collection = new object[] { typeof(Exception), new ArgumentException() }; - // Assert - act.Should().Throw().WithMessage( - "Expected type to be \"System.ArgumentException\", but found \"[System.Exception, System.ArgumentException]\"."); - } + // Act + Action act = () => collection.Should().AllBeOfType(); - [Fact] - public void When_collection_is_null_then_all_be_of_typeOfT_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected type to be \"System.ArgumentException\", but found \"[System.Exception, System.ArgumentException]\"."); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_all_be_of_typeOfT_should_fail() { - using var _ = new AssertionScope(); - collection.Should().AllBeOfType("we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().AllBeOfType("we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be \"*.Object\" *failure message*, but found collection is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEmpty.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEmpty.cs index 40f58cb55c..7f17a10cbf 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEmpty.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEmpty.cs @@ -12,177 +12,175 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be Empty - - [Fact] - public void When_collection_is_empty_as_expected_it_should_not_throw() - { - // Arrange - var collection = new int[0]; - - // Act / Assert - collection.Should().BeEmpty(); - } - - [Fact] - public void When_collection_is_not_empty_unexpectedly_it_should_throw() + public class BeEmpty { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().BeEmpty("that's what we expect"); - - // Assert - act.Should().Throw() - .WithMessage("*to be empty because that's what we expect, but found*1*2*3*"); - } + [Fact] + public void When_collection_is_empty_as_expected_it_should_not_throw() + { + // Arrange + var collection = new int[0]; - [Fact] - public void When_asserting_collection_with_items_is_not_empty_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Act / Assert + collection.Should().BeEmpty(); + } - // Act / Assert - collection.Should().NotBeEmpty(); - } + [Fact] + public void When_collection_is_not_empty_unexpectedly_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_asserting_collection_with_items_is_not_empty_it_should_enumerate_the_collection_only_once() - { - // Arrange - var trackingEnumerable = new TrackingTestEnumerable(1, 2, 3); + // Act + Action act = () => collection.Should().BeEmpty("that's what we expect"); - // Act - trackingEnumerable.Should().NotBeEmpty(); + // Assert + act.Should().Throw() + .WithMessage("*to be empty because that's what we expect, but found*1*2*3*"); + } - // Assert - trackingEnumerable.Enumerator.LoopCount.Should().Be(1); - } + [Fact] + public void When_asserting_collection_with_items_is_not_empty_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_asserting_collection_without_items_is_not_empty_it_should_fail() - { - // Arrange - var collection = new int[0]; + // Act / Assert + collection.Should().NotBeEmpty(); + } - // Act - Action act = () => collection.Should().NotBeEmpty(); + [Fact] + public void When_asserting_collection_with_items_is_not_empty_it_should_enumerate_the_collection_only_once() + { + // Arrange + var trackingEnumerable = new TrackingTestEnumerable(1, 2, 3); - // Assert - act.Should().Throw(); - } + // Act + trackingEnumerable.Should().NotBeEmpty(); - [Fact] - public void When_asserting_collection_without_items_is_not_empty_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new int[0]; + // Assert + trackingEnumerable.Enumerator.LoopCount.Should().Be(1); + } - // Act - Action act = () => collection.Should().NotBeEmpty("because we want to test the failure {0}", "message"); + [Fact] + public void When_asserting_collection_without_items_is_not_empty_it_should_fail() + { + // Arrange + var collection = new int[0]; - // Assert - act.Should().Throw() - .WithMessage("Expected collection not to be empty because we want to test the failure message."); - } + // Act + Action act = () => collection.Should().NotBeEmpty(); - [Fact] - public void When_asserting_collection_to_be_empty_but_collection_is_null_it_should_throw() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw(); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_without_items_is_not_empty_it_should_fail_with_descriptive_message_() { - using var _ = new AssertionScope(); - collection.Should().BeEmpty("we want to test the failure {0}", "message"); - }; + // Arrange + var collection = new int[0]; - // Assert - act.Should().Throw() - .WithMessage("Expected collection to be empty *failure message*, but found ."); - } + // Act + Action act = () => collection.Should().NotBeEmpty("because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_collection_to_be_empty_it_should_enumerate_only_once() - { - // Arrange - var collection = new CountingGenericEnumerable(new int[0]); + // Assert + act.Should().Throw() + .WithMessage("Expected collection not to be empty because we want to test the failure message."); + } - // Act - collection.Should().BeEmpty(); + [Fact] + public void When_asserting_collection_to_be_empty_but_collection_is_null_it_should_throw() + { + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().BeEmpty("we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected collection to be empty *failure message*, but found ."); + } + + [Fact] + public void When_asserting_collection_to_be_empty_it_should_enumerate_only_once() + { + // Arrange + var collection = new CountingGenericEnumerable(new int[0]); - // Assert - collection.GetEnumeratorCallCount.Should().Be(1); - } + // Act + collection.Should().BeEmpty(); - [Fact] - public void When_asserting_collection_to_not_be_empty_but_collection_is_null_it_should_throw() - { - // Arrange - IEnumerable collection = null; + // Assert + collection.GetEnumeratorCallCount.Should().Be(1); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_to_not_be_empty_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotBeEmpty("we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected collection not to be empty *failure message*, but found ."); - } - - [Fact] - public void When_asserting_an_infinite_collection_to_be_empty_it_should_throw_correctly() - { - // Arrange - var collection = new InfiniteEnumerable(); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotBeEmpty("we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected collection not to be empty *failure message*, but found ."); + } + + [Fact] + public void When_asserting_an_infinite_collection_to_be_empty_it_should_throw_correctly() + { + // Arrange + var collection = new InfiniteEnumerable(); - // Act - Action act = () => collection.Should().BeEmpty(); + // Act + Action act = () => collection.Should().BeEmpty(); - // Assert - act.Should().Throw(); + // Assert + act.Should().Throw(); + } } - #endregion - - #region Not Be Empty - - [Fact] - public void When_asserting_collection_to_be_not_empty_but_collection_is_null_it_should_throw() + public class NotBeEmpty { - // Arrange - int[] collection = null; + [Fact] + public void When_asserting_collection_to_be_not_empty_but_collection_is_null_it_should_throw() + { + // Arrange + int[] collection = null; - // Act - Action act = () => collection.Should().NotBeEmpty("because we want to test the behaviour with a null subject"); + // Act + Action act = () => collection.Should().NotBeEmpty("because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to be empty because we want to test the behaviour with a null subject, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to be empty because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_asserting_collection_to_be_not_empty_it_should_enumerate_only_once() - { - // Arrange - var collection = new CountingGenericEnumerable(new[] { 42 }); + [Fact] + public void When_asserting_collection_to_be_not_empty_it_should_enumerate_only_once() + { + // Arrange + var collection = new CountingGenericEnumerable(new[] { 42 }); - // Act - collection.Should().NotBeEmpty(); + // Act + collection.Should().NotBeEmpty(); - // Assert - collection.GetEnumeratorCallCount.Should().Be(1); + // Assert + collection.GetEnumeratorCallCount.Should().Be(1); + } } - #endregion - private class InfiniteEnumerable : IEnumerable { public IEnumerator GetEnumerator() => new InfiniteEnumerator(); diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEquivalentTo.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEquivalentTo.cs index 7ea0200520..96f34e03e7 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEquivalentTo.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeEquivalentTo.cs @@ -12,330 +12,328 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be Equivalent To - - [Fact] - public void When_two_collections_contain_the_same_elements_it_should_treat_them_as_equivalent() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 3, 1, 2 }; - - // Act / Assert - collection1.Should().BeEquivalentTo(collection2); - } - - [Fact] - public void When_a_collection_contains_same_elements_it_should_treat_it_as_equivalent() + public class BeEquivalentTo { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_two_collections_contain_the_same_elements_it_should_treat_them_as_equivalent() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 3, 1, 2 }; - // Act / Assert - collection.Should().BeEquivalentTo(new[] { 3, 1, 2 }); - } + // Act / Assert + collection1.Should().BeEquivalentTo(collection2); + } - [Fact] - public void When_character_collections_are_equivalent_it_should_not_throw() - { - // Arrange - char[] list1 = "abc123ab".ToCharArray(); - char[] list2 = "abc123ab".ToCharArray(); - - // Act / Assert - list1.Should().BeEquivalentTo(list2); - } + [Fact] + public void When_a_collection_contains_same_elements_it_should_treat_it_as_equivalent() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collections_are_not_equivalent_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2 }; + // Act / Assert + collection.Should().BeEquivalentTo(new[] { 3, 1, 2 }); + } - // Act - Action act = () => collection1.Should().BeEquivalentTo(collection2, "we treat {0} alike", "all"); + [Fact] + public void When_character_collections_are_equivalent_it_should_not_throw() + { + // Arrange + char[] list1 = "abc123ab".ToCharArray(); + char[] list2 = "abc123ab".ToCharArray(); - // Assert - act.Should().Throw().WithMessage( - "Expected*collection*2 item(s)*we treat all alike, but *1 item(s) more than*"); - } + // Act / Assert + list1.Should().BeEquivalentTo(list2); + } - [Fact] - public void When_collections_with_duplicates_are_not_equivalent_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3, 1 }; - var collection2 = new[] { 1, 2, 3, 3 }; - - // Act - Action act = () => collection1.Should().BeEquivalentTo(collection2); + [Fact] + public void When_collections_are_not_equivalent_it_should_throw() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection1[3]*to be 3, but found 1*"); - } + // Act + Action act = () => collection1.Should().BeEquivalentTo(collection2, "we treat {0} alike", "all"); - [Fact] - public void When_testing_for_equivalence_against_empty_collection_it_should_throw() - { - // Arrange - var subject = new[] { 1, 2, 3 }; - var otherCollection = new int[0]; + // Assert + act.Should().Throw().WithMessage( + "Expected*collection*2 item(s)*we treat all alike, but *1 item(s) more than*"); + } - // Act - Action act = () => subject.Should().BeEquivalentTo(otherCollection); + [Fact] + public void When_collections_with_duplicates_are_not_equivalent_it_should_throw() + { + // Arrange + var collection1 = new[] { 1, 2, 3, 1 }; + var collection2 = new[] { 1, 2, 3, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected subject to be a collection with 0 item(s), but*contains 3 item(s)*"); - } + // Act + Action act = () => collection1.Should().BeEquivalentTo(collection2); - [Fact] - public void When_two_collections_are_both_empty_it_should_treat_them_as_equivalent() - { - // Arrange - var subject = new int[0]; - var otherCollection = new int[0]; + // Assert + act.Should().Throw().WithMessage( + "Expected collection1[3]*to be 3, but found 1*"); + } - // Act - Action act = () => subject.Should().BeEquivalentTo(otherCollection); + [Fact] + public void When_testing_for_equivalence_against_empty_collection_it_should_throw() + { + // Arrange + var subject = new[] { 1, 2, 3 }; + var otherCollection = new int[0]; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().BeEquivalentTo(otherCollection); - [Fact] - public void When_testing_for_equivalence_against_null_collection_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - int[] collection2 = null; + // Assert + act.Should().Throw().WithMessage( + "Expected subject to be a collection with 0 item(s), but*contains 3 item(s)*"); + } - // Act - Action act = () => collection1.Should().BeEquivalentTo(collection2); + [Fact] + public void When_two_collections_are_both_empty_it_should_treat_them_as_equivalent() + { + // Arrange + var subject = new int[0]; + var otherCollection = new int[0]; - // Assert - act.Should().Throw().WithMessage( - "Expected**but found {1, 2, 3}*"); - } + // Act + Action act = () => subject.Should().BeEquivalentTo(otherCollection); - [Fact] - public void When_asserting_collections_to_be_equivalent_but_subject_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; - var collection1 = new[] { 1, 2, 3 }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = - () => collection.Should().BeEquivalentTo(collection1, "because we want to test the behaviour with a null subject"); + [Fact] + public void When_testing_for_equivalence_against_null_collection_it_should_throw() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + int[] collection2 = null; - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to be *"); - } + // Act + Action act = () => collection1.Should().BeEquivalentTo(collection2); - [Fact] - public void Default_immutable_arrays_should_be_equivalent() - { - // Arrange - ImmutableArray collection = default; - ImmutableArray collection1 = default; + // Assert + act.Should().Throw().WithMessage( + "Expected**but found {1, 2, 3}*"); + } - // Act / Assert - collection.Should().BeEquivalentTo(collection1); - } + [Fact] + public void When_asserting_collections_to_be_equivalent_but_subject_collection_is_null_it_should_throw() + { + // Arrange + int[] collection = null; + var collection1 = new[] { 1, 2, 3 }; - [Fact] - public void Default_immutable_lists_should_be_equivalent() - { - // Arrange - ImmutableList collection = default; - ImmutableList collection1 = default; + // Act + Action act = + () => collection.Should().BeEquivalentTo(collection1, "because we want to test the behaviour with a null subject"); - // Act / Assert - collection.Should().BeEquivalentTo(collection1); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to be *"); + } - #endregion + [Fact] + public void Default_immutable_arrays_should_be_equivalent() + { + // Arrange + ImmutableArray collection = default; + ImmutableArray collection1 = default; - #region Not Be Equivalent To + // Act / Assert + collection.Should().BeEquivalentTo(collection1); + } - [Fact] - public void When_collection_is_not_equivalent_to_another_smaller_collection_it_should_succeed() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 3, 1 }; + [Fact] + public void Default_immutable_lists_should_be_equivalent() + { + // Arrange + ImmutableList collection = default; + ImmutableList collection1 = default; - // Act / Assert - collection1.Should().NotBeEquivalentTo(collection2); + // Act / Assert + collection.Should().BeEquivalentTo(collection1); + } } - [Fact] - public void When_large_collection_is_equivalent_to_another_equally_size_collection_it_should_throw() + public class NotBeEquivalentTo { - // Arrange - var collection1 = Enumerable.Repeat(1, 10000); - var collection2 = Enumerable.Repeat(1, 10000); - - // Act - Action act = () => collection1.Should().NotBeEquivalentTo(collection2); - - // Assert - act.Should().Throw(); - } + [Fact] + public void When_collection_is_not_equivalent_to_another_smaller_collection_it_should_succeed() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 3, 1 }; - [Fact] - public void When_collection_is_not_equivalent_to_another_equally_sized_collection_it_should_succeed() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 3, 1, 4 }; + // Act / Assert + collection1.Should().NotBeEquivalentTo(collection2); + } - // Act / Assert - collection1.Should().NotBeEquivalentTo(collection2); - } + [Fact] + public void When_large_collection_is_equivalent_to_another_equally_size_collection_it_should_throw() + { + // Arrange + var collection1 = Enumerable.Repeat(1, 10000); + var collection2 = Enumerable.Repeat(1, 10000); - [Fact] - public void When_collections_are_unexpectedly_equivalent_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 3, 1, 2 }; + // Act + Action act = () => collection1.Should().NotBeEquivalentTo(collection2); - // Act - Action act = () => collection1.Should().NotBeEquivalentTo(collection2); + // Assert + act.Should().Throw(); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 {1, 2, 3} not*equivalent*{3, 1, 2}."); - } + [Fact] + public void When_collection_is_not_equivalent_to_another_equally_sized_collection_it_should_succeed() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 3, 1, 4 }; - [Fact] - public void When_asserting_collections_not_to_be_equivalent_but_subject_collection_is_null_it_should_throw() - { - // Arrange - int[] actual = null; - var expectation = new[] { 1, 2, 3 }; + // Act / Assert + collection1.Should().NotBeEquivalentTo(collection2); + } - // Act - Action act = () => + [Fact] + public void When_collections_are_unexpectedly_equivalent_it_should_throw() { - using var _ = new AssertionScope(); - actual.Should().NotBeEquivalentTo(expectation, "because we want to test the behaviour with a null subject"); - }; + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 3, 1, 2 }; - // Assert - act.Should().Throw().WithMessage( - "*be equivalent because we want to test the behaviour with a null subject, but found *"); - } - - [Fact] - public void When_non_empty_collection_is_not_expected_to_be_equivalent_to_an_empty_collection_it_should_succeed() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new int[0]; + // Act + Action act = () => collection1.Should().NotBeEquivalentTo(collection2); - // Act - Action act = () => collection1.Should().NotBeEquivalentTo(collection2); + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 {1, 2, 3} not*equivalent*{3, 1, 2}."); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_asserting_collections_not_to_be_equivalent_but_subject_collection_is_null_it_should_throw() + { + // Arrange + int[] actual = null; + var expectation = new[] { 1, 2, 3 }; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + actual.Should().NotBeEquivalentTo(expectation, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "*be equivalent because we want to test the behaviour with a null subject, but found *"); + } + + [Fact] + public void When_non_empty_collection_is_not_expected_to_be_equivalent_to_an_empty_collection_it_should_succeed() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new int[0]; - [Fact] - public void When_testing_collections_not_to_be_equivalent_against_null_collection_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - int[] collection2 = null; + // Act + Action act = () => collection1.Should().NotBeEquivalentTo(collection2); - // Act - Action act = () => collection1.Should().NotBeEquivalentTo(collection2); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw() - .WithMessage("Cannot verify inequivalence against a collection.*") - .WithParameterName("unexpected"); - } + [Fact] + public void When_testing_collections_not_to_be_equivalent_against_null_collection_it_should_throw() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + int[] collection2 = null; - [Fact] - public void When_testing_collections_not_to_be_equivalent_against_same_collection_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - var collection1 = collection; + // Act + Action act = () => collection1.Should().NotBeEquivalentTo(collection2); - // Act - Action act = () => collection.Should().NotBeEquivalentTo(collection1, - "because we want to test the behaviour with same objects"); + // Assert + act.Should().Throw() + .WithMessage("Cannot verify inequivalence against a collection.*") + .WithParameterName("unexpected"); + } - // Assert - act.Should().Throw().WithMessage( - "*not to be equivalent*because we want to test the behaviour with same objects*but they both reference the same object."); - } + [Fact] + public void When_testing_collections_not_to_be_equivalent_against_same_collection_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var collection1 = collection; - [Fact] - public void When_a_collections_is_equivalent_to_an_approximate_copy_it_should_throw() - { - // Arrange - var collection = new[] { 1.0, 2.0, 3.0 }; - var collection1 = new[] { 1.5, 2.5, 3.5 }; - - // Act - Action act = () => collection.Should().NotBeEquivalentTo(collection1, opt => opt - .Using(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, 0.5)) - .WhenTypeIs(), - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "*not to be equivalent*because we want to test the failure message*"); - } + // Act + Action act = () => collection.Should().NotBeEquivalentTo(collection1, + "because we want to test the behaviour with same objects"); - [Fact] - public void When_asserting_collections_not_to_be_equivalent_with_options_but_subject_collection_is_null_it_should_throw() - { - // Arrange - int[] actual = null; + // Assert + act.Should().Throw().WithMessage( + "*not to be equivalent*because we want to test the behaviour with same objects*but they both reference the same object."); + } - // Act - Action act = () => + [Fact] + public void When_a_collections_is_equivalent_to_an_approximate_copy_it_should_throw() { - using var _ = new AssertionScope(); - actual.Should().NotBeEquivalentTo(new[] { 1, 2, 3 }, opt => opt, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected actual not to be equivalent *failure message*, but found ."); - } + // Arrange + var collection = new[] { 1.0, 2.0, 3.0 }; + var collection1 = new[] { 1.5, 2.5, 3.5 }; + + // Act + Action act = () => collection.Should().NotBeEquivalentTo(collection1, opt => opt + .Using(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, 0.5)) + .WhenTypeIs(), + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "*not to be equivalent*because we want to test the failure message*"); + } + + [Fact] + public void When_asserting_collections_not_to_be_equivalent_with_options_but_subject_collection_is_null_it_should_throw() + { + // Arrange + int[] actual = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + actual.Should().NotBeEquivalentTo(new[] { 1, 2, 3 }, opt => opt, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected actual not to be equivalent *failure message*, but found ."); + } + + [Fact] + public void Default_immutable_array_should_not_be_equivalent_to_initialized_immutable_array() + { + // Arrange + ImmutableArray collection = default; + ImmutableArray collection1 = ImmutableArray.Create("a", "b", "c"); - [Fact] - public void Default_immutable_array_should_not_be_equivalent_to_initialized_immutable_array() - { - // Arrange - ImmutableArray collection = default; - ImmutableArray collection1 = ImmutableArray.Create("a", "b", "c"); + // Act / Assert + collection.Should().NotBeEquivalentTo(collection1); + } - // Act / Assert - collection.Should().NotBeEquivalentTo(collection1); - } - - [Fact] - public void Immutable_array_should_not_be_equivalent_to_default_immutable_array() - { - // Arrange - ImmutableArray collection = ImmutableArray.Create("a", "b", "c"); - ImmutableArray collection1 = default; + [Fact] + public void Immutable_array_should_not_be_equivalent_to_default_immutable_array() + { + // Arrange + ImmutableArray collection = ImmutableArray.Create("a", "b", "c"); + ImmutableArray collection1 = default; - // Act / Assert - collection.Should().NotBeEquivalentTo(collection1); + // Act / Assert + collection.Should().NotBeEquivalentTo(collection1); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs index bcb424d5f8..696133e152 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs @@ -11,157 +11,155 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be In AscendingOrder - - [Fact] - public void When_asserting_a_null_collection_to_be_in_ascending_order_it_should_throw() + public class BeInAscendingOrder { - // Arrange - List result = null; - - // Act - Action act = () => + [Fact] + public void When_asserting_a_null_collection_to_be_in_ascending_order_it_should_throw() { - using var _ = new AssertionScope(); - result.Should().BeInAscendingOrder(); - }; - - // Assert - act.Should().Throw() - .WithMessage("*but found *"); - } - - [Fact] - public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 2, 2, 3 }; + // Arrange + List result = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + result.Should().BeInAscendingOrder(); + }; + + // Assert + act.Should().Throw() + .WithMessage("*but found *"); + } + + [Fact] + public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 2, 3 }; - // Act / Assert - collection.Should().BeInAscendingOrder(); - } + // Act / Assert + collection.Should().BeInAscendingOrder(); + } - [Fact] - public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_using_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 2, 2, 3 }; + [Fact] + public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_using_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 2, 3 }; - // Act / Assert - collection.Should().BeInAscendingOrder(Comparer.Default); - } + // Act / Assert + collection.Should().BeInAscendingOrder(Comparer.Default); + } - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_it_should_throw() - { - // Arrange - var collection = new[] { 1, 6, 12, 15, 12, 17, 26 }; + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_it_should_throw() + { + // Arrange + var collection = new[] { 1, 6, 12, 15, 12, 17, 26 }; - // Act - Action action = () => collection.Should().BeInAscendingOrder("because numbers are ordered"); + // Act + Action action = () => collection.Should().BeInAscendingOrder("because numbers are ordered"); - // Assert - action.Should().Throw() - .WithMessage("Expected collection to be in ascending order because numbers are ordered," + - " but found {1, 6, 12, 15, 12, 17, 26} where item at index 3 is in wrong order."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected collection to be in ascending order because numbers are ordered," + + " but found {1, 6, 12, 15, 12, 17, 26} where item at index 3 is in wrong order."); + } - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_using_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] { 1, 6, 12, 15, 12, 17, 26 }; + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_using_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] { 1, 6, 12, 15, 12, 17, 26 }; - // Act - Action action = () => collection.Should().BeInAscendingOrder(Comparer.Default, "because numbers are ordered"); + // Act + Action action = () => collection.Should().BeInAscendingOrder(Comparer.Default, "because numbers are ordered"); - // Assert - action.Should().Throw() - .WithMessage("Expected collection to be in ascending order because numbers are ordered," + - " but found {1, 6, 12, 15, 12, 17, 26} where item at index 3 is in wrong order."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected collection to be in ascending order because numbers are ordered," + + " but found {1, 6, 12, 15, 12, 17, 26} where item at index 3 is in wrong order."); + } - [Fact] - public void Items_can_be_ordered_by_the_identity_function() - { - // Arrange - var collection = new[] { 1, 2 }; + [Fact] + public void Items_can_be_ordered_by_the_identity_function() + { + // Arrange + var collection = new[] { 1, 2 }; - // Act - Action action = () => collection.Should().BeInAscendingOrder(x => x); + // Act + Action action = () => collection.Should().BeInAscendingOrder(x => x); - // Assert - action.Should().NotThrow(); + // Assert + action.Should().NotThrow(); + } } - #endregion - - #region Not Be In Ascending Order - - [Fact] - public void When_asserting_a_null_collection_to_not_be_in_ascending_order_it_should_throw() + public class NotBeInAscendingOrder { - // Arrange - List result = null; + [Fact] + public void When_asserting_a_null_collection_to_not_be_in_ascending_order_it_should_throw() + { + // Arrange + List result = null; - // Act - Action act = () => result.Should().NotBeInAscendingOrder(); + // Act + Action act = () => result.Should().NotBeInAscendingOrder(); - // Assert - act.Should().Throw() - .WithMessage("*but found *"); - } + // Assert + act.Should().Throw() + .WithMessage("*but found *"); + } - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_not_in_ascending_order_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 5, 3 }; + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_not_in_ascending_order_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 5, 3 }; - // Act / Assert - collection.Should().NotBeInAscendingOrder(); - } + // Act / Assert + collection.Should().NotBeInAscendingOrder(); + } - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_not_in_ascending_order_using_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 5, 3 }; + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_not_in_ascending_order_using_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 5, 3 }; - // Act / Assert - collection.Should().NotBeInAscendingOrder(Comparer.Default); - } + // Act / Assert + collection.Should().NotBeInAscendingOrder(Comparer.Default); + } - [Fact] - public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_not_in_ascending_order_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 2, 3 }; + [Fact] + public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_not_in_ascending_order_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 2, 3 }; - // Act - Action action = () => collection.Should().NotBeInAscendingOrder("because numbers are not ordered"); + // Act + Action action = () => collection.Should().NotBeInAscendingOrder("because numbers are not ordered"); - // Assert - action.Should().Throw() - .WithMessage("Did not expect collection to be in ascending order because numbers are not ordered," + - " but found {1, 2, 2, 3}."); - } + // Assert + action.Should().Throw() + .WithMessage("Did not expect collection to be in ascending order because numbers are not ordered," + + " but found {1, 2, 2, 3}."); + } - [Fact] - public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_not_in_ascending_order_using_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 2, 3 }; + [Fact] + public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_not_in_ascending_order_using_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 2, 3 }; - // Act - Action action = () => collection.Should().NotBeInAscendingOrder(Comparer.Default, "because numbers are not ordered"); + // Act + Action action = () => collection.Should().NotBeInAscendingOrder(Comparer.Default, "because numbers are not ordered"); - // Assert - action.Should().Throw() - .WithMessage("Did not expect collection to be in ascending order because numbers are not ordered," + - " but found {1, 2, 2, 3}."); + // Assert + action.Should().Throw() + .WithMessage("Did not expect collection to be in ascending order because numbers are not ordered," + + " but found {1, 2, 2, 3}."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs index dadf55c847..be98a70524 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs @@ -10,87 +10,85 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be In Descending Order - - [Fact] - public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_it_should_succeed() + public class BeInDescendingOrder { - // Arrange - var collection = new[] { "z", "y", "x" }; - - // Act / Assert - collection.Should().BeInDescendingOrder(); + [Fact] + public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_it_should_succeed() + { + // Arrange + var collection = new[] { "z", "y", "x" }; + + // Act / Assert + collection.Should().BeInDescendingOrder(); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_it_should_throw() + { + // Arrange + var collection = new[] { "z", "x", "y" }; + + // Act + Action action = () => collection.Should().BeInDescendingOrder("because letters are ordered"); + + // Assert + action.Should().Throw() + .WithMessage("Expected collection to be in descending order because letters are ordered," + + " but found {\"z\", \"x\", \"y\"} where item at index 1 is in wrong order."); + } } - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_it_should_throw() + public class NotBeInDescendingOrder { - // Arrange - var collection = new[] { "z", "x", "y" }; - - // Act - Action action = () => collection.Should().BeInDescendingOrder("because letters are ordered"); - - // Assert - action.Should().Throw() - .WithMessage("Expected collection to be in descending order because letters are ordered," + - " but found {\"z\", \"x\", \"y\"} where item at index 1 is in wrong order."); + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_not_in_descending_order_it_should_succeed() + { + // Arrange + var collection = new[] { "x", "y", "x" }; + + // Act / Assert + collection.Should().NotBeInDescendingOrder(); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_not_in_descending_order_using_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] { "x", "y", "x" }; + + // Act / Assert + collection.Should().NotBeInDescendingOrder(Comparer.Default); + } + + [Fact] + public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_in_descending_order_it_should_throw() + { + // Arrange + var collection = new[] { "c", "b", "a" }; + + // Act + Action action = () => collection.Should().NotBeInDescendingOrder("because numbers are not ordered"); + + // Assert + action.Should().Throw() + .WithMessage("Did not expect collection to be in descending order because numbers are not ordered," + + " but found {\"c\", \"b\", \"a\"}."); + } + + [Fact] + public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_in_descending_order_using_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] { "c", "b", "a" }; + + // Act + Action action = () => collection.Should().NotBeInDescendingOrder(Comparer.Default, "because numbers are not ordered"); + + // Assert + action.Should().Throw() + .WithMessage("Did not expect collection to be in descending order because numbers are not ordered," + + " but found {\"c\", \"b\", \"a\"}."); + } } - - #endregion - - #region Not Be In Descending Order - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_not_in_descending_order_it_should_succeed() - { - // Arrange - var collection = new[] { "x", "y", "x" }; - - // Act / Assert - collection.Should().NotBeInDescendingOrder(); - } - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_not_in_descending_order_using_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] { "x", "y", "x" }; - - // Act / Assert - collection.Should().NotBeInDescendingOrder(Comparer.Default); - } - - [Fact] - public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_in_descending_order_it_should_throw() - { - // Arrange - var collection = new[] { "c", "b", "a" }; - - // Act - Action action = () => collection.Should().NotBeInDescendingOrder("because numbers are not ordered"); - - // Assert - action.Should().Throw() - .WithMessage("Did not expect collection to be in descending order because numbers are not ordered," + - " but found {\"c\", \"b\", \"a\"}."); - } - - [Fact] - public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_in_descending_order_using_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] { "c", "b", "a" }; - - // Act - Action action = () => collection.Should().NotBeInDescendingOrder(Comparer.Default, "because numbers are not ordered"); - - // Assert - action.Should().Throw() - .WithMessage("Did not expect collection to be in descending order because numbers are not ordered," + - " but found {\"c\", \"b\", \"a\"}."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNull.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNull.cs index 04a2aff221..621da8d5de 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNull.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNull.cs @@ -10,60 +10,58 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be Null - - [Fact] - public void When_collection_is_expected_to_be_null_and_it_is_it_should_not_throw() + public class BeNull { - // Arrange - IEnumerable someCollection = null; + [Fact] + public void When_collection_is_expected_to_be_null_and_it_is_it_should_not_throw() + { + // Arrange + IEnumerable someCollection = null; - // Act / Assert - someCollection.Should().BeNull(); - } + // Act / Assert + someCollection.Should().BeNull(); + } - [Fact] - public void When_collection_is_expected_to_be_null_and_it_isnt_it_should_throw() - { - // Arrange - IEnumerable someCollection = new string[0]; + [Fact] + public void When_collection_is_expected_to_be_null_and_it_isnt_it_should_throw() + { + // Arrange + IEnumerable someCollection = new string[0]; - // Act - Action act = () => someCollection.Should().BeNull("because {0} is valid", "null"); + // Act + Action act = () => someCollection.Should().BeNull("because {0} is valid", "null"); - // Assert - act.Should().Throw().WithMessage( - "Expected someCollection to be because null is valid, but found {empty}."); + // Assert + act.Should().Throw().WithMessage( + "Expected someCollection to be because null is valid, but found {empty}."); + } } - #endregion - - #region Not Be Null - - [Fact] - public void When_collection_is_not_expected_to_be_null_and_it_isnt_it_should_not_throw() + public class NotBeNull { - // Arrange - IEnumerable someCollection = new string[0]; + [Fact] + public void When_collection_is_not_expected_to_be_null_and_it_isnt_it_should_not_throw() + { + // Arrange + IEnumerable someCollection = new string[0]; - // Act / Assert - someCollection.Should().NotBeNull(); - } + // Act / Assert + someCollection.Should().NotBeNull(); + } - [Fact] - public void When_collection_is_not_expected_to_be_null_and_it_is_it_should_throw() - { - // Arrange - IEnumerable someCollection = null; + [Fact] + public void When_collection_is_not_expected_to_be_null_and_it_is_it_should_throw() + { + // Arrange + IEnumerable someCollection = null; - // Act - Action act = () => someCollection.Should().NotBeNull("because {0} should not", "someCollection"); + // Act + Action act = () => someCollection.Should().NotBeNull("because {0} should not", "someCollection"); - // Assert - act.Should().Throw().WithMessage( - "Expected someCollection not to be because someCollection should not."); + // Assert + act.Should().Throw().WithMessage( + "Expected someCollection not to be because someCollection should not."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNullOrEmpty.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNullOrEmpty.cs index f4429c7566..f81c1fe8f7 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNullOrEmpty.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeNullOrEmpty.cs @@ -9,115 +9,113 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be Null Or Empty - - [Fact] - public void - When_asserting_a_null_collection_to_be_null_or_empty_it_should_succeed() - { - // Arrange - int[] collection = null; - - // Act / Assert - collection.Should().BeNullOrEmpty(); - } - - [Fact] - public void - When_asserting_an_empty_collection_to_be_null_or_empty_it_should_succeed() - { - // Arrange - var collection = new int[0]; - - // Act / Assert - collection.Should().BeNullOrEmpty(); - } - - [Fact] - public void - When_asserting_non_empty_collection_to_be_null_or_empty_it_should_throw() + public class BeNullOrEmpty { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().BeNullOrEmpty("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected collection to be null or empty because we want to test the failure message, but found {1, 2, 3}."); + [Fact] + public void + When_asserting_a_null_collection_to_be_null_or_empty_it_should_succeed() + { + // Arrange + int[] collection = null; + + // Act / Assert + collection.Should().BeNullOrEmpty(); + } + + [Fact] + public void + When_asserting_an_empty_collection_to_be_null_or_empty_it_should_succeed() + { + // Arrange + var collection = new int[0]; + + // Act / Assert + collection.Should().BeNullOrEmpty(); + } + + [Fact] + public void + When_asserting_non_empty_collection_to_be_null_or_empty_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + + // Act + Action act = () => collection.Should().BeNullOrEmpty("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected collection to be null or empty because we want to test the failure message, but found {1, 2, 3}."); + } + + [Fact] + public void When_asserting_collection_to_be_null_or_empty_it_should_enumerate_only_once() + { + // Arrange + var collection = new CountingGenericEnumerable(new int[0]); + + // Act + collection.Should().BeNullOrEmpty(); + + // Assert + collection.GetEnumeratorCallCount.Should().Be(1); + } } - [Fact] - public void When_asserting_collection_to_be_null_or_empty_it_should_enumerate_only_once() + public class NotBeNullOrEmpty { - // Arrange - var collection = new CountingGenericEnumerable(new int[0]); - - // Act - collection.Should().BeNullOrEmpty(); - - // Assert - collection.GetEnumeratorCallCount.Should().Be(1); + [Fact] + public void + When_asserting_non_empty_collection_to_not_be_null_or_empty_it_should_succeed() + { + // Arrange + var collection = new[] { new object() }; + + // Act / Assert + collection.Should().NotBeNullOrEmpty(); + } + + [Fact] + public void + When_asserting_null_collection_to_not_be_null_or_empty_it_should_throw() + { + // Arrange + int[] collection = null; + + // Act + Action act = () => collection.Should().NotBeNullOrEmpty(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_empty_collection_to_not_be_null_or_empty_it_should_throw() + { + // Arrange + var collection = new int[0]; + + // Act + Action act = () => collection.Should().NotBeNullOrEmpty(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_collection_to_not_be_null_or_empty_it_should_enumerate_only_once() + { + // Arrange + var collection = new CountingGenericEnumerable(new[] { 42 }); + + // Act + collection.Should().NotBeNullOrEmpty(); + + // Assert + collection.GetEnumeratorCallCount.Should().Be(1); + } } - - #endregion - - #region Not Be Null Or Empty - - [Fact] - public void - When_asserting_non_empty_collection_to_not_be_null_or_empty_it_should_succeed() - { - // Arrange - var collection = new[] { new object() }; - - // Act / Assert - collection.Should().NotBeNullOrEmpty(); - } - - [Fact] - public void - When_asserting_null_collection_to_not_be_null_or_empty_it_should_throw() - { - // Arrange - int[] collection = null; - - // Act - Action act = () => collection.Should().NotBeNullOrEmpty(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_empty_collection_to_not_be_null_or_empty_it_should_throw() - { - // Arrange - var collection = new int[0]; - - // Act - Action act = () => collection.Should().NotBeNullOrEmpty(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_collection_to_not_be_null_or_empty_it_should_enumerate_only_once() - { - // Arrange - var collection = new CountingGenericEnumerable(new[] { 42 }); - - // Act - collection.Should().NotBeNullOrEmpty(); - - // Assert - collection.GetEnumeratorCallCount.Should().Be(1); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeSubsetOf.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeSubsetOf.cs index bc86c6f7da..22f1dfb10e 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeSubsetOf.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeSubsetOf.cs @@ -10,162 +10,160 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Be Subset Of - - [Fact] - public void When_collection_is_subset_of_a_specified_collection_it_should_not_throw() - { - // Arrange - var subset = new[] { 1, 2 }; - var superset = new[] { 1, 2, 3 }; - - // Act / Assert - subset.Should().BeSubsetOf(superset); - } - - [Fact] - public void When_collection_is_not_a_subset_of_another_it_should_throw_with_the_reason() + public class BeSubsetOf { - // Arrange - var subset = new[] { 1, 2, 3, 6 }; - var superset = new[] { 1, 2, 4, 5 }; - - // Act - Action act = () => subset.Should().BeSubsetOf(superset, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_is_subset_of_a_specified_collection_it_should_not_throw() + { + // Arrange + var subset = new[] { 1, 2 }; + var superset = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected subset to be a subset of {1, 2, 4, 5} because we want to test the failure message, " + - "but items {3, 6} are not part of the superset."); - } + // Act / Assert + subset.Should().BeSubsetOf(superset); + } - [Fact] - public void When_an_empty_collection_is_tested_against_a_superset_it_should_succeed() - { - // Arrange - var subset = new int[0]; - var superset = new[] { 1, 2, 4, 5 }; - - // Act - Action act = () => subset.Should().BeSubsetOf(superset); + [Fact] + public void When_collection_is_not_a_subset_of_another_it_should_throw_with_the_reason() + { + // Arrange + var subset = new[] { 1, 2, 3, 6 }; + var superset = new[] { 1, 2, 4, 5 }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subset.Should().BeSubsetOf(superset, "because we want to test the failure {0}", "message"); - [Fact] - public void When_a_subset_is_tested_against_a_null_superset_it_should_throw_with_a_clear_explanation() - { - // Arrange - var subset = new[] { 1, 2, 3 }; - int[] superset = null; + // Assert + act.Should().Throw().WithMessage( + "Expected subset to be a subset of {1, 2, 4, 5} because we want to test the failure message, " + + "but items {3, 6} are not part of the superset."); + } - // Act - Action act = () => subset.Should().BeSubsetOf(superset); + [Fact] + public void When_an_empty_collection_is_tested_against_a_superset_it_should_succeed() + { + // Arrange + var subset = new int[0]; + var superset = new[] { 1, 2, 4, 5 }; - // Assert - act.Should().Throw().WithMessage( - "Cannot verify a subset against a collection.*"); - } + // Act + Action act = () => subset.Should().BeSubsetOf(superset); - [Fact] - public void When_a_set_is_expected_to_be_not_a_subset_it_should_succeed() - { - // Arrange - var subject = new[] { 1, 2, 4 }; - var otherSet = new[] { 1, 2, 3 }; + // Assert + act.Should().NotThrow(); + } - // Act / Assert - subject.Should().NotBeSubsetOf(otherSet); - } - - #endregion + [Fact] + public void When_a_subset_is_tested_against_a_null_superset_it_should_throw_with_a_clear_explanation() + { + // Arrange + var subset = new[] { 1, 2, 3 }; + int[] superset = null; - #region Not Be Subset Of + // Act + Action act = () => subset.Should().BeSubsetOf(superset); - [Fact] - public void When_an_empty_set_is_not_supposed_to_be_a_subset_of_another_set_it_should_throw() - { - // Arrange - var subject = new int[] { }; - var otherSet = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw().WithMessage( + "Cannot verify a subset against a collection.*"); + } - // Act - Action act = () => subject.Should().NotBeSubsetOf(otherSet); + [Fact] + public void When_a_set_is_expected_to_be_not_a_subset_it_should_succeed() + { + // Arrange + var subject = new[] { 1, 2, 4 }; + var otherSet = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw() - .WithMessage("Did not expect subject {empty} to be a subset of {1, 2, 3}."); + // Act / Assert + subject.Should().NotBeSubsetOf(otherSet); + } } - [Fact] - public void Should_fail_when_asserting_collection_is_not_subset_of_a_superset_collection() + public class NotBeSubsetOf { - // Arrange - var subject = new[] { 1, 2 }; - var otherSet = new[] { 1, 2, 3 }; - - // Act - Action act = () => subject.Should().NotBeSubsetOf(otherSet, "because I'm {0}", "mistaken"); + [Fact] + public void When_an_empty_set_is_not_supposed_to_be_a_subset_of_another_set_it_should_throw() + { + // Arrange + var subject = new int[] { }; + var otherSet = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Did not expect subject {1, 2} to be a subset of {1, 2, 3} because I'm mistaken."); - } + // Act + Action act = () => subject.Should().NotBeSubsetOf(otherSet); - [Fact] - public void When_asserting_collection_to_be_subset_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; - var collection1 = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw() + .WithMessage("Did not expect subject {empty} to be a subset of {1, 2, 3}."); + } - // Act - Action act = () => + [Fact] + public void Should_fail_when_asserting_collection_is_not_subset_of_a_superset_collection() { - using var _ = new AssertionScope(); - collection.Should().BeSubsetOf(collection1, "because we want to test the behaviour with a null subject"); - }; + // Arrange + var subject = new[] { 1, 2 }; + var otherSet = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to be a subset of {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => subject.Should().NotBeSubsetOf(otherSet, "because I'm {0}", "mistaken"); - [Fact] - public void When_asserting_collection_to_not_be_subset_against_same_collection_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - var collection1 = collection; + // Assert + act.Should().Throw().WithMessage( + "Did not expect subject {1, 2} to be a subset of {1, 2, 3} because I'm mistaken."); + } - // Act - Action act = () => collection.Should().NotBeSubsetOf(collection1, - "because we want to test the behaviour with same objects"); + [Fact] + public void When_asserting_collection_to_be_subset_against_null_collection_it_should_throw() + { + // Arrange + int[] collection = null; + var collection1 = new[] { 1, 2, 3 }; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().BeSubsetOf(collection1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to be a subset of {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_asserting_collection_to_not_be_subset_against_same_collection_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var collection1 = collection; - // Assert - act.Should().Throw().WithMessage( - "Did not expect*to be a subset of*because we want to test the behaviour with same objects*but they both reference the same object."); - } + // Act + Action act = () => collection.Should().NotBeSubsetOf(collection1, + "because we want to test the behaviour with same objects"); - [Fact] - public void When_asserting_collection_to_not_be_subset_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Did not expect*to be a subset of*because we want to test the behaviour with same objects*but they both reference the same object."); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_to_not_be_subset_against_null_collection_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotBeSubsetOf(new[] { 1, 2, 3 }, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Cannot assert a collection against a subset."); + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotBeSubsetOf(new[] { 1, 2, 3 }, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Cannot assert a collection against a subset."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs index 5c842ba873..868e32994b 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs @@ -11,421 +11,419 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Contain - - [Fact] - public void Should_succeed_when_asserting_collection_contains_an_item_from_the_collection() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act / Assert - collection.Should().Contain(1); - } - - [Fact] - public void Should_succeed_when_asserting_collection_contains_multiple_items_from_the_collection_in_any_order() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act / Assert - collection.Should().Contain(new[] { 2, 1 }); - } - - [Fact] - public void When_a_collection_does_not_contain_single_item_it_should_throw_with_clear_explanation() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().Contain(4, "because {0}", "we do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to contain 4 because we do."); - } - - [Fact] - public void When_asserting_collection_does_contain_item_against_null_collection_it_should_throw() + public class Contain { - // Arrange - int[] collection = null; - - // Act - Action act = () => + [Fact] + public void Should_succeed_when_asserting_collection_contains_an_item_from_the_collection() { - using var _ = new AssertionScope(); - collection.Should().Contain(1, "because we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain 1 because we want to test the behaviour with a null subject, but found ."); - } - - [Fact] - public void When_a_collection_does_not_contain_another_collection_it_should_throw_with_clear_explanation() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().Contain(new[] { 3, 4, 5 }, "because {0}", "we do"); + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to contain {3, 4, 5} because we do, but could not find {4, 5}."); - } - - [Fact] - public void When_the_contents_of_a_collection_are_checked_against_an_empty_collection_it_should_throw_clear_explanation() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().Contain(new int[0]); - - // Assert - act.Should().Throw().WithMessage( - "Cannot verify containment against an empty collection*"); - } + // Act / Assert + collection.Should().Contain(1); + } - [Fact] - public void When_asserting_collection_does_contain_a_list_of_items_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; - - // Act - Action act = () => + [Fact] + public void Should_succeed_when_asserting_collection_contains_multiple_items_from_the_collection_in_any_order() { - using var _ = new AssertionScope(); - collection.Should().Contain(new[] { 1, 2 }, "we want to test the failure {0}", "message"); - }; + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw() - .WithMessage("Expected collection to contain {1, 2} *failure message*, but found ."); - } + // Act / Assert + collection.Should().Contain(new[] { 2, 1 }); + } - [Fact] - public void When_injecting_a_null_predicate_into_Contain_it_should_throw() - { - // Arrange - IEnumerable collection = new int[] { }; - - // Act - Action act = () => collection.Should().Contain(predicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("predicate"); - } + [Fact] + public void When_a_collection_does_not_contain_single_item_it_should_throw_with_clear_explanation() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_does_not_contain_an_expected_item_matching_a_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] { 1, 2, 3 }; + // Act + Action act = () => collection.Should().Contain(4, "because {0}", "we do"); - // Act - Action act = () => collection.Should().Contain(item => item > 3, "at least {0} item should be larger than 3", 1); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to contain 4 because we do."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to have an item matching (item > 3) because at least 1 item should be larger than 3."); - } + [Fact] + public void When_asserting_collection_does_contain_item_against_null_collection_it_should_throw() + { + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().Contain(1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain 1 because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_a_collection_does_not_contain_another_collection_it_should_throw_with_clear_explanation() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_does_contain_an_expected_item_matching_a_predicate_it_should_allow_chaining_it() - { - // Arrange - IEnumerable collection = new[] { 1, 2, 3 }; + // Act + Action act = () => collection.Should().Contain(new[] { 3, 4, 5 }, "because {0}", "we do"); - // Act - Action act = () => collection.Should().Contain(item => item == 2).Which.Should().BeGreaterThan(4); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to contain {3, 4, 5} because we do, but could not find {4, 5}."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected*greater*4*2*"); - } + [Fact] + public void When_the_contents_of_a_collection_are_checked_against_an_empty_collection_it_should_throw_clear_explanation() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_does_contain_an_expected_item_matching_a_predicate_it_should_not_throw() - { - // Arrange - IEnumerable collection = new[] { 1, 2, 3 }; + // Act + Action act = () => collection.Should().Contain(new int[0]); - // Act / Assert - collection.Should().Contain(item => item == 2); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot verify containment against an empty collection*"); + } - [Fact] - public void When_a_collection_of_strings_contains_the_expected_string_it_should_not_throw() - { - // Arrange - IEnumerable strings = new[] { "string1", "string2", "string3" }; + [Fact] + public void When_asserting_collection_does_contain_a_list_of_items_against_null_collection_it_should_throw() + { + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().Contain(new[] { 1, 2 }, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected collection to contain {1, 2} *failure message*, but found ."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_Contain_it_should_throw() + { + // Arrange + IEnumerable collection = new int[] { }; - // Act / Assert - strings.Should().Contain("string2"); - } + // Act + Action act = () => collection.Should().Contain(predicate: null); - [Fact] - public void When_a_collection_of_strings_does_not_contain_the_expected_string_it_should_throw() - { - // Arrange - IEnumerable strings = new[] { "string1", "string2", "string3" }; + // Assert + act.Should().ThrowExactly() + .WithParameterName("predicate"); + } - // Act - Action act = () => strings.Should().Contain("string4", "because {0} is required", "4"); + [Fact] + public void When_collection_does_not_contain_an_expected_item_matching_a_predicate_it_should_throw() + { + // Arrange + IEnumerable collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected strings {\"string1\", \"string2\", \"string3\"} to contain \"string4\" because 4 is required."); - } + // Act + Action act = () => collection.Should().Contain(item => item > 3, "at least {0} item should be larger than 3", 1); - [Fact] - public void When_asserting_collection_contains_some_values_but_collection_is_null_it_should_throw() - { - // Arrange - const IEnumerable strings = null; + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to have an item matching (item > 3) because at least 1 item should be larger than 3."); + } - // Act - Action act = () => + [Fact] + public void When_collection_does_contain_an_expected_item_matching_a_predicate_it_should_allow_chaining_it() { - using var _ = new AssertionScope(); - strings.Should().Contain("string4", "because we're checking how it reacts to a null subject"); - }; + // Arrange + IEnumerable collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected strings to contain \"string4\" because we're checking how it reacts to a null subject, but found ."); - } + // Act + Action act = () => collection.Should().Contain(item => item == 2).Which.Should().BeGreaterThan(4); - [Fact] - public void When_the_multiple_matching_objects_exists_it_continuation_using_the_matched_value_should_fail() - { - // Arrange - DateTime now = DateTime.Now; + // Assert + act.Should().Throw().WithMessage( + "Expected*greater*4*2*"); + } - IEnumerable collection = new[] { now, DateTime.SpecifyKind(now, DateTimeKind.Unspecified) }; + [Fact] + public void When_collection_does_contain_an_expected_item_matching_a_predicate_it_should_not_throw() + { + // Arrange + IEnumerable collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().Contain(now).Which.Kind.Should().Be(DateTimeKind.Local); + // Act / Assert + collection.Should().Contain(item => item == 2); + } - // Assert - act.Should().Throw(); - } + [Fact] + public void When_a_collection_of_strings_contains_the_expected_string_it_should_not_throw() + { + // Arrange + IEnumerable strings = new[] { "string1", "string2", "string3" }; - [Fact] - public void When_asserting_collection_contains_values_according_to_predicate_but_collection_is_null_it_should_throw() - { - // Arrange - const IEnumerable strings = null; + // Act / Assert + strings.Should().Contain("string2"); + } - // Act - Action act = () => + [Fact] + public void When_a_collection_of_strings_does_not_contain_the_expected_string_it_should_throw() { - using var _ = new AssertionScope(); - strings.Should().Contain(x => x == "xxx", "because we're checking how it reacts to a null subject"); - }; + // Arrange + IEnumerable strings = new[] { "string1", "string2", "string3" }; - // Assert - act.Should().Throw().WithMessage( - "Expected strings to contain (x == \"xxx\") because we're checking how it reacts to a null subject, but found ."); - } + // Act + Action act = () => strings.Should().Contain("string4", "because {0} is required", "4"); - #endregion + // Assert + act.Should().Throw().WithMessage( + "Expected strings {\"string1\", \"string2\", \"string3\"} to contain \"string4\" because 4 is required."); + } - #region Not Contain + [Fact] + public void When_asserting_collection_contains_some_values_but_collection_is_null_it_should_throw() + { + // Arrange + const IEnumerable strings = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + strings.Should().Contain("string4", "because we're checking how it reacts to a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected strings to contain \"string4\" because we're checking how it reacts to a null subject, but found ."); + } + + [Fact] + public void When_the_multiple_matching_objects_exists_it_continuation_using_the_matched_value_should_fail() + { + // Arrange + DateTime now = DateTime.Now; - [Fact] - public void Should_succeed_when_asserting_collection_does_not_contain_an_item_that_is_not_in_the_collection() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + IEnumerable collection = new[] { now, DateTime.SpecifyKind(now, DateTimeKind.Unspecified) }; - // Act / Assert - collection.Should().NotContain(4); - } + // Act + Action act = () => collection.Should().Contain(now).Which.Kind.Should().Be(DateTimeKind.Local); - [Fact] - public void Should_succeed_when_asserting_collection_does_not_contain_any_items_that_is_not_in_the_collection() - { - // Arrange - IEnumerable collection = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw(); + } - // Act / Assert - collection.Should().NotContain(new[] { 4, 5 }); + [Fact] + public void When_asserting_collection_contains_values_according_to_predicate_but_collection_is_null_it_should_throw() + { + // Arrange + const IEnumerable strings = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + strings.Should().Contain(x => x == "xxx", "because we're checking how it reacts to a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected strings to contain (x == \"xxx\") because we're checking how it reacts to a null subject, but found ."); + } } - - [Fact] - public void When_collection_contains_an_unexpected_item_it_should_throw() + + public class NotContain { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().NotContain(1, "because we {0} like it, but found it anyhow", "don't"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to not contain 1 because we don't like it, but found it anyhow."); - } + [Fact] + public void Should_succeed_when_asserting_collection_does_not_contain_an_item_that_is_not_in_the_collection() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_injecting_a_null_predicate_into_NotContain_it_should_throw() - { - // Arrange - IEnumerable collection = new int[] { }; + // Act / Assert + collection.Should().NotContain(4); + } - // Act - Action act = () => collection.Should().NotContain(predicate: null); + [Fact] + public void Should_succeed_when_asserting_collection_does_not_contain_any_items_that_is_not_in_the_collection() + { + // Arrange + IEnumerable collection = new[] { 1, 2, 3 }; - // Assert - act.Should().ThrowExactly() - .WithParameterName("predicate"); - } + // Act / Assert + collection.Should().NotContain(new[] { 4, 5 }); + } - [Fact] - public void When_collection_does_contain_an_unexpected_item_matching_a_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] { 1, 2, 3 }; + [Fact] + public void When_collection_contains_an_unexpected_item_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().NotContain(item => item == 2, "because {0}s are evil", 2); + // Act + Action act = () => collection.Should().NotContain(1, "because we {0} like it, but found it anyhow", "don't"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to not have any items matching (item == 2) because 2s are evil,*{2}*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to not contain 1 because we don't like it, but found it anyhow."); + } - [Fact] - public void When_collection_does_not_contain_an_unexpected_item_matching_a_predicate_it_should_not_throw() - { - // Arrange - IEnumerable collection = new[] { 1, 2, 3 }; + [Fact] + public void When_injecting_a_null_predicate_into_NotContain_it_should_throw() + { + // Arrange + IEnumerable collection = new int[] { }; - // Act / Assert - collection.Should().NotContain(item => item == 4); - } + // Act + Action act = () => collection.Should().NotContain(predicate: null); - [Fact] - public void When_asserting_collection_does_not_contain_item_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + act.Should().ThrowExactly() + .WithParameterName("predicate"); + } - // Act - Action act = () => + [Fact] + public void When_collection_does_contain_an_unexpected_item_matching_a_predicate_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotContain(1, "because we want to test the behaviour with a null subject"); - }; + // Arrange + IEnumerable collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to not contain 1 because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => collection.Should().NotContain(item => item == 2, "because {0}s are evil", 2); - [Fact] - public void When_collection_contains_unexpected_items_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should() - .NotContain(new[] { 1, 2, 4 }, "because we {0} like them", "don't"); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to not have any items matching (item == 2) because 2s are evil,*{2}*"); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to not contain {1, 2, 4} because we don't like them, but found {1, 2}."); - } + [Fact] + public void When_collection_does_not_contain_an_unexpected_item_matching_a_predicate_it_should_not_throw() + { + // Arrange + IEnumerable collection = new[] { 1, 2, 3 }; - [Fact] - public void When_asserting_collection_does_not_contain_predicate_item_against_null_collection_it_should_fail() - { - // Arrange - int[] collection = null; + // Act / Assert + collection.Should().NotContain(item => item == 4); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_does_not_contain_item_against_null_collection_it_should_throw() + { + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContain(1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to not contain 1 because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_collection_contains_unexpected_items_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotContain(item => item == 4, "we want to test the failure {0}", "message"); - }; + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw() - .WithMessage("Expected collection not to contain (item == 4) *failure message*, but found ."); - } + // Act + Action act = () => collection.Should() + .NotContain(new[] { 1, 2, 4 }, "because we {0} like them", "don't"); - [Fact] - public void When_asserting_collection_does_not_contain_a_list_of_items_against_null_collection_it_should_fail() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to not contain {1, 2, 4} because we don't like them, but found {1, 2}."); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_does_not_contain_predicate_item_against_null_collection_it_should_fail() { - using var _ = new AssertionScope(); - collection.Should().NotContain(new[] { 1, 2, 4 }, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected collection to not contain {1, 2, 4} *failure message*, but found ."); - } - - [Fact] - public void When_asserting_collection_doesnt_contain_values_according_to_predicate_but_collection_is_null_it_should_throw() - { - // Arrange - const IEnumerable strings = null; + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContain(item => item == 4, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected collection not to contain (item == 4) *failure message*, but found ."); + } + + [Fact] + public void When_asserting_collection_does_not_contain_a_list_of_items_against_null_collection_it_should_fail() + { + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContain(new[] { 1, 2, 4 }, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected collection to not contain {1, 2, 4} *failure message*, but found ."); + } + + [Fact] + public void When_asserting_collection_doesnt_contain_values_according_to_predicate_but_collection_is_null_it_should_throw() + { + // Arrange + const IEnumerable strings = null; - // Act - Action act = - () => strings.Should().NotContain(x => x == "xxx", "because we're checking how it reacts to a null subject"); + // Act + Action act = + () => strings.Should().NotContain(x => x == "xxx", "because we're checking how it reacts to a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected strings not to contain (x == \"xxx\") because we're checking how it reacts to a null subject, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected strings not to contain (x == \"xxx\") because we're checking how it reacts to a null subject, but found ."); + } - [Fact] - public void When_a_collection_does_not_contain_the_expected_item_it_should_not_be_enumerated_twice() - { - // Arrange - var collection = new OneTimeEnumerable(1, 2, 3); + [Fact] + public void When_a_collection_does_not_contain_the_expected_item_it_should_not_be_enumerated_twice() + { + // Arrange + var collection = new OneTimeEnumerable(1, 2, 3); - // Act - Action act = () => collection.Should().Contain(4); + // Act + Action act = () => collection.Should().Contain(4); - // Assert - act.Should().Throw().WithMessage( - "Expected collection*to contain 4."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection*to contain 4."); + } - [Fact] - public void When_a_collection_contains_the_unexpected_item_it_should_not_be_enumerated_twice() - { - // Arrange - var collection = new OneTimeEnumerable(1, 2, 3); + [Fact] + public void When_a_collection_contains_the_unexpected_item_it_should_not_be_enumerated_twice() + { + // Arrange + var collection = new OneTimeEnumerable(1, 2, 3); - // Act - Action act = () => collection.Should().NotContain(2); + // Act + Action act = () => collection.Should().NotContain(2); - // Assert - act.Should().Throw().WithMessage( - "Expected collection*to not contain 2."); + // Assert + act.Should().Throw().WithMessage( + "Expected collection*to not contain 2."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainEquivalentOf.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainEquivalentOf.cs index dc1ab8577e..9074cae34d 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainEquivalentOf.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainEquivalentOf.cs @@ -10,399 +10,397 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Contain Equivalent Of - - [Fact] - public void When_collection_contains_object_equal_of_another_it_should_succeed() + public class ContainEquivalentOf { - // Arrange - var item = new Customer { Name = "John" }; - var collection = new[] { new Customer { Name = "Jane" }, item }; - - // Act / Assert - collection.Should().ContainEquivalentOf(item); - } + [Fact] + public void When_collection_contains_object_equal_of_another_it_should_succeed() + { + // Arrange + var item = new Customer { Name = "John" }; + var collection = new[] { new Customer { Name = "Jane" }, item }; - [Fact] - public void When_collection_contains_object_equivalent_of_another_it_should_succeed() - { - // Arrange - var collection = new[] { new Customer { Name = "Jane" }, new Customer { Name = "John" } }; - var item = new Customer { Name = "John" }; + // Act / Assert + collection.Should().ContainEquivalentOf(item); + } - // Act / Assert - collection.Should().ContainEquivalentOf(item); - } + [Fact] + public void When_collection_contains_object_equivalent_of_another_it_should_succeed() + { + // Arrange + var collection = new[] { new Customer { Name = "Jane" }, new Customer { Name = "John" } }; + var item = new Customer { Name = "John" }; - [Fact] - public void When_character_collection_does_contain_equivalent_it_should_succeed() - { - // Arrange - char[] collection = "abc123ab".ToCharArray(); - char item = 'c'; + // Act / Assert + collection.Should().ContainEquivalentOf(item); + } - // Act / Assert - collection.Should().ContainEquivalentOf(item); - } + [Fact] + public void When_character_collection_does_contain_equivalent_it_should_succeed() + { + // Arrange + char[] collection = "abc123ab".ToCharArray(); + char item = 'c'; - [Fact] - public void When_string_collection_does_contain_same_string_with_other_case_it_should_throw() - { - // Arrange - string[] collection = new[] { "a", "b", "c" }; - string item = "C"; + // Act / Assert + collection.Should().ContainEquivalentOf(item); + } - // Act - Action act = () => collection.Should().ContainEquivalentOf(item); + [Fact] + public void When_string_collection_does_contain_same_string_with_other_case_it_should_throw() + { + // Arrange + string[] collection = new[] { "a", "b", "c" }; + string item = "C"; - // Assert - act.Should().Throw().WithMessage("Expected collection {\"a\", \"b\", \"c\"} to contain equivalent of \"C\".*"); - } + // Act + Action act = () => collection.Should().ContainEquivalentOf(item); - [Fact] - public void When_string_collection_does_contain_same_string_it_should_throw_with_a_useful_message() - { - // Arrange - string[] collection = new[] { "a" }; - string item = "b"; + // Assert + act.Should().Throw().WithMessage("Expected collection {\"a\", \"b\", \"c\"} to contain equivalent of \"C\".*"); + } - // Act - Action act = () => collection.Should().ContainEquivalentOf(item, "because we want to test the failure {0}", "message"); + [Fact] + public void When_string_collection_does_contain_same_string_it_should_throw_with_a_useful_message() + { + // Arrange + string[] collection = new[] { "a" }; + string item = "b"; - // Assert - act.Should().Throw() - .WithMessage("*because we want to test the failure message*"); - } + // Act + Action act = () => collection.Should().ContainEquivalentOf(item, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_does_not_contain_object_equivalent_of_another_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int item = 4; + // Assert + act.Should().Throw() + .WithMessage("*because we want to test the failure message*"); + } - // Act - Action act = () => collection.Should().ContainEquivalentOf(item); + [Fact] + public void When_collection_does_not_contain_object_equivalent_of_another_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + int item = 4; - // Act / Assert - act.Should().Throw().WithMessage("Expected collection {1, 2, 3} to contain equivalent of 4.*"); - } + // Act + Action act = () => collection.Should().ContainEquivalentOf(item); - [Fact] - public void When_asserting_collection_to_contain_equivalent_but_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; - int expectation = 1; + // Act / Assert + act.Should().Throw().WithMessage("Expected collection {1, 2, 3} to contain equivalent of 4.*"); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_to_contain_equivalent_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().ContainEquivalentOf(expectation, "because we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain equivalent of 1 because we want to test the behaviour with a null subject, but found ."); - } - - [Fact] - public void When_collection_contains_equivalent_null_object_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 2, 3, (int?)null }; - int? item = null; + // Arrange + int[] collection = null; + int expectation = 1; - // Act - Action act = () => collection.Should().ContainEquivalentOf(item); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().ContainEquivalentOf(expectation, "because we want to test the behaviour with a null subject"); + }; - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain equivalent of 1 because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_collection_does_not_contain_equivalent_null_object_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int? item = null; + [Fact] + public void When_collection_contains_equivalent_null_object_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 3, (int?)null }; + int? item = null; - // Act - Action act = () => collection.Should().ContainEquivalentOf(item); + // Act + Action act = () => collection.Should().ContainEquivalentOf(item); - // Assert - act.Should().Throw().WithMessage("Expected collection {1, 2, 3} to contain equivalent of .*"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_empty_collection_does_not_contain_equivalent_it_should_throw() - { - // Arrange - var collection = new int[0]; - int item = 1; + [Fact] + public void When_collection_does_not_contain_equivalent_null_object_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + int? item = null; - // Act - Action act = () => collection.Should().ContainEquivalentOf(item); + // Act + Action act = () => collection.Should().ContainEquivalentOf(item); - // Assert - act.Should().Throw().WithMessage("Expected collection {empty} to contain equivalent of 1.*"); - } + // Assert + act.Should().Throw().WithMessage("Expected collection {1, 2, 3} to contain equivalent of .*"); + } - [Fact] - public void When_collection_does_not_contain_equivalent_because_of_second_property_it_should_throw() - { - // Arrange - var subject = new[] + [Fact] + public void When_empty_collection_does_not_contain_equivalent_it_should_throw() { - new Customer - { - Name = "John", - Age = 18 - }, - new Customer - { - Name = "Jane", - Age = 18 - } - }; - var item = new Customer { Name = "John", Age = 20 }; + // Arrange + var collection = new int[0]; + int item = 1; - // Act - Action act = () => subject.Should().ContainEquivalentOf(item); + // Act + Action act = () => collection.Should().ContainEquivalentOf(item); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw().WithMessage("Expected collection {empty} to contain equivalent of 1.*"); + } - [Fact] - public void When_collection_does_contain_equivalent_by_including_single_property_it_should_not_throw() - { - // Arrange - var collection = new[] + [Fact] + public void When_collection_does_not_contain_equivalent_because_of_second_property_it_should_throw() { - new Customer + // Arrange + var subject = new[] { - Name = "John", - Age = 18 - }, - new Customer - { - Name = "Jane", - Age = 18 - } - }; - var item = new Customer { Name = "John", Age = 20 }; - - // Act / Assert - collection.Should().ContainEquivalentOf(item, options => options.Including(x => x.Name)); - } - - [Fact] - public void Tracing_should_be_included_in_the_assertion_output() - { - // Arrange - var collection = new[] + new Customer + { + Name = "John", + Age = 18 + }, + new Customer + { + Name = "Jane", + Age = 18 + } + }; + var item = new Customer { Name = "John", Age = 20 }; + + // Act + Action act = () => subject.Should().ContainEquivalentOf(item); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_collection_does_contain_equivalent_by_including_single_property_it_should_not_throw() { - new Customer + // Arrange + var collection = new[] { - Name = "John", - Age = 18 - }, - new Customer + new Customer + { + Name = "John", + Age = 18 + }, + new Customer + { + Name = "Jane", + Age = 18 + } + }; + var item = new Customer { Name = "John", Age = 20 }; + + // Act / Assert + collection.Should().ContainEquivalentOf(item, options => options.Including(x => x.Name)); + } + + [Fact] + public void Tracing_should_be_included_in_the_assertion_output() + { + // Arrange + var collection = new[] { - Name = "Jane", - Age = 18 - } - }; - - var item = new Customer { Name = "John", Age = 21 }; - - // Act - Action act = () => collection.Should().ContainEquivalentOf(item, options => options.WithTracing()); + new Customer + { + Name = "John", + Age = 18 + }, + new Customer + { + Name = "Jane", + Age = 18 + } + }; + + var item = new Customer { Name = "John", Age = 21 }; + + // Act + Action act = () => collection.Should().ContainEquivalentOf(item, options => options.WithTracing()); + + // Assert + act.Should().Throw().WithMessage("*Equivalency was proven*"); + } + + [Fact] + public void When_injecting_a_null_config_to_ContainEquivalentOf_it_should_throw() + { + // Arrange + int[] collection = null; + object item = null; - // Assert - act.Should().Throw().WithMessage("*Equivalency was proven*"); - } + // Act + Action act = () => collection.Should().ContainEquivalentOf(item, config: null); - [Fact] - public void When_injecting_a_null_config_to_ContainEquivalentOf_it_should_throw() - { - // Arrange - int[] collection = null; - object item = null; + // Assert + act.Should().ThrowExactly() + .WithParameterName("config"); + } - // Act - Action act = () => collection.Should().ContainEquivalentOf(item, config: null); + [Fact] + public void When_collection_contains_object_equivalent_of_boxed_object_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + object boxedValue = 2; - // Assert - act.Should().ThrowExactly() - .WithParameterName("config"); + // Act / Assert + collection.Should().ContainEquivalentOf(boxedValue); + } } - [Fact] - public void When_collection_contains_object_equivalent_of_boxed_object_it_should_succeed() + public class NotContainEquivalentOf { - // Arrange - var collection = new[] { 1, 2, 3 }; - object boxedValue = 2; - - // Act / Assert - collection.Should().ContainEquivalentOf(boxedValue); - } - - #endregion + [Fact] + public void When_collection_contains_object_equal_to_another_it_should_throw() + { + // Arrange + var item = 1; + var collection = new[] { 0, 1 }; - #region Not Contain Equivalent Of + // Act + Action act = () => collection.Should().NotContainEquivalentOf(item, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_contains_object_equal_to_another_it_should_throw() - { - // Arrange - var item = 1; - var collection = new[] { 0, 1 }; + // Assert + act.Should().Throw().WithMessage("Expected collection {0, 1} not to contain*because we want to test the failure message, " + + "but found one at index 1.*With configuration*"); + } - // Act - Action act = () => collection.Should().NotContainEquivalentOf(item, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_contains_several_objects_equal_to_another_it_should_throw() + { + // Arrange + var item = 1; + var collection = new[] { 0, 1, 1 }; - // Assert - act.Should().Throw().WithMessage("Expected collection {0, 1} not to contain*because we want to test the failure message, " + - "but found one at index 1.*With configuration*"); - } + // Act + Action act = () => collection.Should().NotContainEquivalentOf(item, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_contains_several_objects_equal_to_another_it_should_throw() - { - // Arrange - var item = 1; - var collection = new[] { 0, 1, 1 }; + // Assert + act.Should().Throw().WithMessage("Expected collection {0, 1, 1} not to contain*because we want to test the failure message, " + + "but found several at indices {1, 2}.*With configuration*"); + } - // Act - Action act = () => collection.Should().NotContainEquivalentOf(item, "because we want to test the failure {0}", "message"); + [Fact] + public void When_asserting_collection_to_not_to_contain_equivalent_but_collection_is_null_it_should_throw() + { + // Arrange + var item = 1; + int[] collection = null; - // Assert - act.Should().Throw().WithMessage("Expected collection {0, 1, 1} not to contain*because we want to test the failure message, " + - "but found several at indices {1, 2}.*With configuration*"); - } + // Act + Action act = () => collection.Should().NotContainEquivalentOf(item); - [Fact] - public void When_asserting_collection_to_not_to_contain_equivalent_but_collection_is_null_it_should_throw() - { - // Arrange - var item = 1; - int[] collection = null; + // Assert + act.Should().Throw().WithMessage("Expected collection*not to contain*but collection is ."); + } - // Act - Action act = () => collection.Should().NotContainEquivalentOf(item); + [Fact] + public void When_injecting_a_null_config_to_NotContainEquivalentOf_it_should_throw() + { + // Arrange + int[] collection = null; + object item = null; - // Assert - act.Should().Throw().WithMessage("Expected collection*not to contain*but collection is ."); - } + // Act + Action act = () => collection.Should().NotContainEquivalentOf(item, config: null); - [Fact] - public void When_injecting_a_null_config_to_NotContainEquivalentOf_it_should_throw() - { - // Arrange - int[] collection = null; - object item = null; + // Assert + act.Should().ThrowExactly() + .WithParameterName("config"); + } - // Act - Action act = () => collection.Should().NotContainEquivalentOf(item, config: null); + [Fact] + public void When_asserting_empty_collection_to_not_contain_equivalent_it_should_succeed() + { + // Arrange + var collection = new int[0]; + int item = 4; - // Assert - act.Should().ThrowExactly() - .WithParameterName("config"); - } + // Act / Assert + collection.Should().NotContainEquivalentOf(item); + } - [Fact] - public void When_asserting_empty_collection_to_not_contain_equivalent_it_should_succeed() - { - // Arrange - var collection = new int[0]; - int item = 4; + [Fact] + public void When_asserting_a_null_collection_to_not_contain_equivalent_of__then_it_should_fail() + { + // Arrange + int[] collection = null; - // Act / Assert - collection.Should().NotContainEquivalentOf(item); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContainEquivalentOf(1, config => config, "we want to test the failure {0}", "message"); + }; - [Fact] - public void When_asserting_a_null_collection_to_not_contain_equivalent_of__then_it_should_fail() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw() + .WithMessage("Expected collection not to contain *failure message*, but collection is ."); + } - // Act - Action act = () => + [Fact] + public void When_collection_does_not_contain_object_equivalent_of_unexpected_it_should_succeed() { - using var _ = new AssertionScope(); - collection.Should().NotContainEquivalentOf(1, config => config, "we want to test the failure {0}", "message"); - }; + // Arrange + var collection = new[] { 1, 2, 3 }; + int item = 4; - // Assert - act.Should().Throw() - .WithMessage("Expected collection not to contain *failure message*, but collection is ."); - } - - [Fact] - public void When_collection_does_not_contain_object_equivalent_of_unexpected_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int item = 4; - - // Act / Assert - collection.Should().NotContainEquivalentOf(item); - } + // Act / Assert + collection.Should().NotContainEquivalentOf(item); + } - [Fact] - public void When_asserting_collection_to_not_contain_equivalent_it_should_respect_config() - { - // Arrange - var collection = new[] + [Fact] + public void When_asserting_collection_to_not_contain_equivalent_it_should_respect_config() { - new Customer - { - Name = "John", - Age = 18 - }, - new Customer + // Arrange + var collection = new[] { - Name = "Jane", - Age = 18 - } - }; - var item = new Customer { Name = "John", Age = 20 }; - - // Act - Action act = () => collection.Should().NotContainEquivalentOf(item, options => options.Excluding(x => x.Age)); - - // Assert - act.Should().Throw().WithMessage("*Exclude*Age*"); - } - - [Fact] - public void When_asserting_collection_to_not_contain_equivalent_it_should_allow_combining_inside_assertion_scope() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int another = 3; - - // Act - Action act = () => + new Customer + { + Name = "John", + Age = 18 + }, + new Customer + { + Name = "Jane", + Age = 18 + } + }; + var item = new Customer { Name = "John", Age = 20 }; + + // Act + Action act = () => collection.Should().NotContainEquivalentOf(item, options => options.Excluding(x => x.Age)); + + // Assert + act.Should().Throw().WithMessage("*Exclude*Age*"); + } + + [Fact] + public void When_asserting_collection_to_not_contain_equivalent_it_should_allow_combining_inside_assertion_scope() { - using (new AssertionScope()) + // Arrange + var collection = new[] { 1, 2, 3 }; + int another = 3; + + // Act + Action act = () => { - collection.Should().NotContainEquivalentOf(another, "because we want to test {0}", "first message") - .And - .HaveCount(4, "because we want to test {0}", "second message"); - } - }; - - // Assert - act.Should().Throw().WithMessage("Expected collection*not to contain*first message*but*.\n" + - "Expected*4 item(s)*because*second message*but*."); + using (new AssertionScope()) + { + collection.Should().NotContainEquivalentOf(another, "because we want to test {0}", "first message") + .And + .HaveCount(4, "because we want to test {0}", "second message"); + } + }; + + // Assert + act.Should().Throw().WithMessage("Expected collection*not to contain*first message*but*.\n" + + "Expected*4 item(s)*because*second message*but*."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainInOrder.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainInOrder.cs index 751bff71e5..ccbf4c9f67 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainInOrder.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainInOrder.cs @@ -10,263 +10,261 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Contain In Order - - [Fact] - public void When_two_collections_contain_the_same_items_in_the_same_order_it_should_not_throw() + public class ContainInOrder { - // Arrange - var collection = new[] { 1, 2, 2, 3 }; - - // Act / Assert - collection.Should().ContainInOrder(1, 2, 3); - } + [Fact] + public void When_two_collections_contain_the_same_items_in_the_same_order_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 2, 3 }; - [Fact] - public void When_collection_contains_null_value_it_should_not_throw() - { - // Arrange - var collection = new object[] { 1, null, 2, "string" }; + // Act / Assert + collection.Should().ContainInOrder(1, 2, 3); + } - // Act / Assert - collection.Should().ContainInOrder(new object[] { 1, null, "string" }); - } + [Fact] + public void When_collection_contains_null_value_it_should_not_throw() + { + // Arrange + var collection = new object[] { 1, null, 2, "string" }; - [Fact] - public void When_the_first_collection_contains_a_duplicate_item_without_affecting_the_order_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 3, 2 }; + // Act / Assert + collection.Should().ContainInOrder(new object[] { 1, null, "string" }); + } - // Act / Assert - collection.Should().ContainInOrder(1, 2, 3); - } + [Fact] + public void When_the_first_collection_contains_a_duplicate_item_without_affecting_the_order_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3, 2 }; - [Fact] - public void When_two_collections_contain_the_same_duplicate_items_in_the_same_order_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 1, 2, 12, 2, 2 }; + // Act / Assert + collection.Should().ContainInOrder(1, 2, 3); + } - // Act / Assert - collection.Should().ContainInOrder(1, 2, 1, 2, 12, 2, 2); - } + [Fact] + public void When_two_collections_contain_the_same_duplicate_items_in_the_same_order_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 1, 2, 12, 2, 2 }; - [Fact] - public void When_a_collection_does_not_contain_a_range_twice_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 1, 3, 12, 2, 2 }; + // Act / Assert + collection.Should().ContainInOrder(1, 2, 1, 2, 12, 2, 2); + } - // Act - Action act = () => collection.Should().ContainInOrder(1, 2, 1, 1, 2); + [Fact] + public void When_a_collection_does_not_contain_a_range_twice_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 1, 3, 12, 2, 2 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 1, 3, 12, 2, 2} to contain items {1, 2, 1, 1, 2} in order, but 1 (index 3) did not appear (in the right order)."); - } + // Act + Action act = () => collection.Should().ContainInOrder(1, 2, 1, 1, 2); - [Fact] - public void When_two_collections_contain_the_same_items_but_in_different_order_it_should_throw_with_a_clear_explanation() - { - // Act - Action act = () => new[] { 1, 2, 3 }.Should().ContainInOrder(new[] { 3, 1 }, "because we said so"); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 1, 3, 12, 2, 2} to contain items {1, 2, 1, 1, 2} in order, but 1 (index 3) did not appear (in the right order)."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to contain items {3, 1} in order because we said so, but 1 (index 1) did not appear (in the right order)."); - } + [Fact] + public void When_two_collections_contain_the_same_items_but_in_different_order_it_should_throw_with_a_clear_explanation() + { + // Act + Action act = () => new[] { 1, 2, 3 }.Should().ContainInOrder(new[] { 3, 1 }, "because we said so"); - [Fact] - public void When_a_collection_does_not_contain_an_ordered_item_it_should_throw_with_a_clear_explanation() - { - // Act - Action act = () => new[] { 1, 2, 3 }.Should().ContainInOrder(new[] { 4, 1 }, "we failed"); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to contain items {3, 1} in order because we said so, but 1 (index 1) did not appear (in the right order)."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3} to contain items {4, 1} in order because we failed, " + - "but 4 (index 0) did not appear (in the right order)."); - } + [Fact] + public void When_a_collection_does_not_contain_an_ordered_item_it_should_throw_with_a_clear_explanation() + { + // Act + Action act = () => new[] { 1, 2, 3 }.Should().ContainInOrder(new[] { 4, 1 }, "we failed"); - [Fact] - public void When_passing_in_null_while_checking_for_ordered_containment_it_should_throw_with_a_clear_explanation() - { - // Act - Action act = () => new[] { 1, 2, 3 }.Should().ContainInOrder(null); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3} to contain items {4, 1} in order because we failed, " + + "but 4 (index 0) did not appear (in the right order)."); + } - // Assert - act.Should().Throw().WithMessage( - "Cannot verify ordered containment against a collection.*"); - } + [Fact] + public void When_passing_in_null_while_checking_for_ordered_containment_it_should_throw_with_a_clear_explanation() + { + // Act + Action act = () => new[] { 1, 2, 3 }.Should().ContainInOrder(null); - [Fact] - public void When_asserting_collection_contains_some_values_in_order_but_collection_is_null_it_should_throw() - { - // Arrange - int[] ints = null; + // Assert + act.Should().Throw().WithMessage( + "Cannot verify ordered containment against a collection.*"); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_contains_some_values_in_order_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - ints.Should().ContainInOrder(new[] { 4 }, "because we're checking how it reacts to a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected ints to contain {4} in order because we're checking how it reacts to a null subject, but found ."); + // Arrange + int[] ints = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + ints.Should().ContainInOrder(new[] { 4 }, "because we're checking how it reacts to a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected ints to contain {4} in order because we're checking how it reacts to a null subject, but found ."); + } } - #endregion - - #region Not Contain In Order - - [Fact] - public void When_two_collections_contain_the_same_items_but_in_different_order_it_should_not_throw() + public class NotContainInOrder { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_two_collections_contain_the_same_items_but_in_different_order_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().NotContainInOrder(2, 1); - } + // Act / Assert + collection.Should().NotContainInOrder(2, 1); + } - [Fact] - public void When_a_collection_does_not_contain_an_ordered_item_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act / Assert - collection.Should().NotContainInOrder(4, 1); - } + [Fact] + public void When_a_collection_does_not_contain_an_ordered_item_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_a_collection_contains_less_items_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2 }; + // Act / Assert + collection.Should().NotContainInOrder(4, 1); + } - // Act / Assert - collection.Should().NotContainInOrder(1, 2, 3); - } + [Fact] + public void When_a_collection_contains_less_items_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2 }; - [Fact] - public void When_a_collection_does_not_contain_a_range_twice_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 1, 3, 12, 2, 2 }; + // Act / Assert + collection.Should().NotContainInOrder(1, 2, 3); + } - // Act / Assert - collection.Should().NotContainInOrder(1, 2, 1, 1, 2); - } + [Fact] + public void When_a_collection_does_not_contain_a_range_twice_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 1, 3, 12, 2, 2 }; - [Fact] - public void When_asserting_collection_does_not_contain_some_values_in_order_but_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Act / Assert + collection.Should().NotContainInOrder(1, 2, 1, 1, 2); + } - // Act - Action act = () => collection.Should().NotContainInOrder(4); + [Fact] + public void When_asserting_collection_does_not_contain_some_values_in_order_but_collection_is_null_it_should_throw() + { + // Arrange + int[] collection = null; - // Assert - act.Should().Throw().WithMessage("Cannot verify absence of ordered containment in a collection."); - } + // Act + Action act = () => collection.Should().NotContainInOrder(4); - [Fact] - public void When_two_collections_contain_the_same_items_in_the_same_order_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 2, 3 }; + // Assert + act.Should().Throw().WithMessage("Cannot verify absence of ordered containment in a collection."); + } - // Act - Action act = () => collection.Should().NotContainInOrder(new[] { 1, 2, 3 }, "that's what we expect"); + [Fact] + public void When_two_collections_contain_the_same_items_in_the_same_order_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 2, 3} to not contain items {1, 2, 3} in order because that's what we expect, " + - "but items appeared in order ending at index 3."); - } + // Act + Action act = () => collection.Should().NotContainInOrder(new[] { 1, 2, 3 }, "that's what we expect"); - [Fact] - public void When_collection_is_null_then_not_contain_in_order_should_fail() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 2, 3} to not contain items {1, 2, 3} in order because that's what we expect, " + + "but items appeared in order ending at index 3."); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_not_contain_in_order_should_fail() { - using var _ = new AssertionScope(); - collection.Should().NotContainInOrder(new[] { 1, 2, 3 }, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Cannot verify absence of ordered containment in a collection."); - } + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContainInOrder(new[] { 1, 2, 3 }, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Cannot verify absence of ordered containment in a collection."); + } + + [Fact] + public void When_collection_contains_contain_the_same_items_in_the_same_order_with_null_value_it_should_throw() + { + // Arrange + var collection = new object[] { 1, null, 2, "string" }; - [Fact] - public void When_collection_contains_contain_the_same_items_in_the_same_order_with_null_value_it_should_throw() - { - // Arrange - var collection = new object[] { 1, null, 2, "string" }; + // Act + Action act = () => collection.Should().NotContainInOrder(1, null, "string"); - // Act - Action act = () => collection.Should().NotContainInOrder(1, null, "string"); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, , 2, \"string\"} to not contain items {1, , \"string\"} in order, " + + "but items appeared in order ending at index 3."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, , 2, \"string\"} to not contain items {1, , \"string\"} in order, " + - "but items appeared in order ending at index 3."); - } + [Fact] + public void When_the_first_collection_contains_a_duplicate_item_without_affecting_the_order_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3, 2 }; - [Fact] - public void When_the_first_collection_contains_a_duplicate_item_without_affecting_the_order_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3, 2 }; + // Act + Action act = () => collection.Should().NotContainInOrder(1, 2, 3); - // Act - Action act = () => collection.Should().NotContainInOrder(1, 2, 3); + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 3, 2} to not contain items {1, 2, 3} in order, " + + "but items appeared in order ending at index 2."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 3, 2} to not contain items {1, 2, 3} in order, " + - "but items appeared in order ending at index 2."); - } - - [Fact] - public void When_two_collections_contain_the_same_duplicate_items_in_the_same_order_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 1, 2, 12, 2, 2 }; + [Fact] + public void When_two_collections_contain_the_same_duplicate_items_in_the_same_order_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 1, 2, 12, 2, 2 }; - // Act - Action act = () => collection.Should().NotContainInOrder(1, 2, 1, 2, 12, 2, 2); + // Act + Action act = () => collection.Should().NotContainInOrder(1, 2, 1, 2, 12, 2, 2); - // Assert - act.Should().Throw().WithMessage( - "Expected collection {1, 2, 1, 2, 12, 2, 2} to not contain items {1, 2, 1, 2, 12, 2, 2} in order, " + - "but items appeared in order ending at index 6."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection {1, 2, 1, 2, 12, 2, 2} to not contain items {1, 2, 1, 2, 12, 2, 2} in order, " + + "but items appeared in order ending at index 6."); + } - [Fact] - public void When_passing_in_null_while_checking_for_absence_of_ordered_containment_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_passing_in_null_while_checking_for_absence_of_ordered_containment_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().NotContainInOrder(null); + // Act + Action act = () => collection.Should().NotContainInOrder(null); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify absence of ordered containment against a collection.*"); + // Assert + act.Should().Throw().WithMessage( + "Cannot verify absence of ordered containment against a collection.*"); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainItemsAssignableTo.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainItemsAssignableTo.cs index 43f3518c2a..bb18b9dadf 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainItemsAssignableTo.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.ContainItemsAssignableTo.cs @@ -11,74 +11,73 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Contain Items Assignable To - - [Fact] - public void Should_succeed_when_asserting_collection_with_all_items_of_same_type_only_contains_item_of_one_type() + public class ContainItemsAssignableTo { - // Arrange - var collection = new[] { "1", "2", "3" }; + [Fact] + public void Should_succeed_when_asserting_collection_with_all_items_of_same_type_only_contains_item_of_one_type() + { + // Arrange + var collection = new[] { "1", "2", "3" }; - // Act / Assert - collection.Should().ContainItemsAssignableTo(); - } + // Act / Assert + collection.Should().ContainItemsAssignableTo(); + } - [Fact] - public void Should_succeed_when_asserting_collection_with_items_of_different_types_contains_item_of_expected_type() - { - // Arrange - var collection = new List + [Fact] + public void Should_succeed_when_asserting_collection_with_items_of_different_types_contains_item_of_expected_type() + { + // Arrange + var collection = new List { 1, "2" }; - // Act / Assert - collection.Should().ContainItemsAssignableTo(); - } - - [Fact] - public void When_asserting_collection_contains_item_assignable_to_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; + // Act / Assert + collection.Should().ContainItemsAssignableTo(); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_contains_item_assignable_to_against_null_collection_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().ContainItemsAssignableTo("because we want to test the behaviour with a null subject"); - }; + // Arrange + int[] collection = null; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain at least one element assignable to type \"System.String\" because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().ContainItemsAssignableTo("because we want to test the behaviour with a null subject"); + }; - [Fact] - public void When_a_collection_is_empty_an_exception_should_be_thrown() - { - // Arrange - int[] collection = Array.Empty(); + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain at least one element assignable to type \"System.String\" because we want to test the behaviour with a null subject, but found ."); + } - // Act - Action act = () => collection.Should().ContainItemsAssignableTo(); + [Fact] + public void When_a_collection_is_empty_an_exception_should_be_thrown() + { + // Arrange + int[] collection = Array.Empty(); - // Assert - act.Should().Throw().WithMessage("Expected collection to contain at least one element assignable to type \"System.Int32\", but found {empty}."); - } + // Act + Action act = () => collection.Should().ContainItemsAssignableTo(); - [Fact] - public void Should_throw_exception_when_asserting_collection_for_missing_item_type() - { - var collection = new object[] { "1", 1.0m }; + // Assert + act.Should().Throw().WithMessage("Expected collection to contain at least one element assignable to type \"System.Int32\", but found {empty}."); + } + + [Fact] + public void Should_throw_exception_when_asserting_collection_for_missing_item_type() + { + var collection = new object[] { "1", 1.0m }; - Action act = () => collection.Should().ContainItemsAssignableTo(); + Action act = () => collection.Should().ContainItemsAssignableTo(); - act.Should().Throw() - .WithMessage("Expected collection to contain at least one element assignable to type \"System.Int32\", but found {System.String, System.Decimal}."); + act.Should().Throw() + .WithMessage("Expected collection to contain at least one element assignable to type \"System.Int32\", but found {System.String, System.Decimal}."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.EndWith.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.EndWith.cs index 10acc79b80..4c3132a4df 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.EndWith.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.EndWith.cs @@ -11,227 +11,226 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region End With - - [Fact] - public void When_collection_does_not_end_with_a_specific_element_it_should_throw() + public class EndWith { - // Arrange - var collection = new[] { "john", "jane", "mike" }; + [Fact] + public void When_collection_does_not_end_with_a_specific_element_it_should_throw() + { + // Arrange + var collection = new[] { "john", "jane", "mike" }; - // Act - Action act = () => collection.Should().EndWith("ryan", "of some reason"); + // Act + Action act = () => collection.Should().EndWith("ryan", "of some reason"); - // Assert - act.Should().Throw().WithMessage( - "Expected*end*ryan*because of some reason*but*mike*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected*end*ryan*because of some reason*but*mike*"); + } - [Fact] - public void When_collection_does_end_with_a_specific_element_and_because_format_is_incorrect_it_should_not_fail() - { - // Arrange - var collection = new[] { "john", "jane", "mike" }; + [Fact] + public void When_collection_does_end_with_a_specific_element_and_because_format_is_incorrect_it_should_not_fail() + { + // Arrange + var collection = new[] { "john", "jane", "mike" }; - // Act - Action act = () => collection.Should().EndWith("mike", "of some reason {0,abc}", 1, 2); + // Act + Action act = () => collection.Should().EndWith("mike", "of some reason {0,abc}", 1, 2); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_collection_does_not_end_with_a_specific_element_in_a_sequence_it_should_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + [Fact] + public void When_collection_does_not_end_with_a_specific_element_in_a_sequence_it_should_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Act - Action act = () => collection.Should().EndWith(new[] { "bill", "ryan", "mike" }, "of some reason"); + // Act + Action act = () => collection.Should().EndWith(new[] { "bill", "ryan", "mike" }, "of some reason"); - // Assert - act.Should().Throw().WithMessage( - "Expected*end*ryan*because of some reason*but*differs at index 2*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected*end*ryan*because of some reason*but*differs at index 2*"); + } - [Fact] - public void When_collection_does_not_end_with_a_null_sequence_it_should_throw() - { - // Arrange - var collection = new[] { "john" }; + [Fact] + public void When_collection_does_not_end_with_a_null_sequence_it_should_throw() + { + // Arrange + var collection = new[] { "john" }; - // Act - Action act = () => collection.Should().EndWith((IEnumerable)null); + // Act + Action act = () => collection.Should().EndWith((IEnumerable)null); - // Assert - act.Should().Throw() - .Which.ParamName.Should().Be("expectation"); - } + // Assert + act.Should().Throw() + .Which.ParamName.Should().Be("expectation"); + } - [Fact] - public void When_collection_does_not_end_with_a_null_sequence_using_a_comparer_it_should_throw() - { - // Arrange - var collection = new[] { "john" }; - - // Act - Action act = () => collection.Should().EndWith((IEnumerable)null, (_, _) => true); + [Fact] + public void When_collection_does_not_end_with_a_null_sequence_using_a_comparer_it_should_throw() + { + // Arrange + var collection = new[] { "john" }; - // Assert - act.Should().Throw() - .Which.ParamName.Should().Be("expectation"); - } + // Act + Action act = () => collection.Should().EndWith((IEnumerable)null, (_, _) => true); - [Fact] - public void When_collection_does_not_end_with_a_specific_element_in_a_sequence_using_custom_equality_comparison_it_should_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + // Assert + act.Should().Throw() + .Which.ParamName.Should().Be("expectation"); + } - // Act - Action act = () => collection.Should().EndWith(new[] { "bill", "ryan", "mike" }, (s1, s2) => string.Equals(s1, s2, StringComparison.Ordinal), "of some reason"); + [Fact] + public void When_collection_does_not_end_with_a_specific_element_in_a_sequence_using_custom_equality_comparison_it_should_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Assert - act.Should().Throw().WithMessage( - "Expected*end*ryan*because of some reason*but*differs at index 2*"); - } + // Act + Action act = () => collection.Should().EndWith(new[] { "bill", "ryan", "mike" }, (s1, s2) => string.Equals(s1, s2, StringComparison.Ordinal), "of some reason"); - [Fact] - public void When_collection_ends_with_the_specific_element_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "jane", "mike" }; + // Assert + act.Should().Throw().WithMessage( + "Expected*end*ryan*because of some reason*but*differs at index 2*"); + } - // Act - Action act = () => collection.Should().EndWith("mike"); + [Fact] + public void When_collection_ends_with_the_specific_element_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().EndWith("mike"); - [Fact] - public void When_collection_ends_with_the_specific_sequence_of_elements_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().EndWith(new[] { "jane", "mike" }); + [Fact] + public void When_collection_ends_with_the_specific_sequence_of_elements_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().EndWith(new[] { "jane", "mike" }); - [Fact] - public void When_collection_ends_with_the_specific_sequence_of_elements_using_custom_equality_comparison_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().EndWith(new[] { "JaNe", "mIkE" }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); + [Fact] + public void When_collection_ends_with_the_specific_sequence_of_elements_using_custom_equality_comparison_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().EndWith(new[] { "JaNe", "mIkE" }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); - [Fact] - public void When_collection_ends_with_the_specific_null_element_it_should_not_throw() - { - // Arrange - var collection = new[] { "jane", "mike", null }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().EndWith((string)null); + [Fact] + public void When_collection_ends_with_the_specific_null_element_it_should_not_throw() + { + // Arrange + var collection = new[] { "jane", "mike", null }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().EndWith((string)null); - [Fact] - public void When_collection_ends_with_the_specific_sequence_with_null_elements_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", null, "mike", null }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().EndWith(new[] { "jane", null, "mike", null }); + [Fact] + public void When_collection_ends_with_the_specific_sequence_with_null_elements_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", null, "mike", null }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().EndWith(new[] { "jane", null, "mike", null }); - [Fact] - public void When_collection_ends_with_the_specific_sequence_with_null_elements_using_custom_equality_comparison_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", null, "mike", null }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().EndWith(new[] { "JaNe", null, "mIkE", null }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); + [Fact] + public void When_collection_ends_with_the_specific_sequence_with_null_elements_using_custom_equality_comparison_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", null, "mike", null }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().EndWith(new[] { "JaNe", null, "mIkE", null }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); - [Fact] - public void When_collection_ends_with_null_but_that_wasnt_expected_it_should_throw() - { - // Arrange - var collection = new[] { "jane", "mike", null }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().EndWith("john"); + [Fact] + public void When_collection_ends_with_null_but_that_wasnt_expected_it_should_throw() + { + // Arrange + var collection = new[] { "jane", "mike", null }; - // Assert - act.Should().Throw().WithMessage( - "Expected*end*john*but*null*"); - } + // Act + Action act = () => collection.Should().EndWith("john"); - [Fact] - public void When_null_collection_is_expected_to_end_with_an_element_it_should_throw() - { - // Arrange - string[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected*end*john*but*null*"); + } - // Act - Action act = () => + [Fact] + public void When_null_collection_is_expected_to_end_with_an_element_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().EndWith("john"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected*end*john*but*collection*null*"); - } - - [Fact] - public void When_non_empty_collection_ends_with_the_empty_sequence_it_should_not_throw() - { - // Arrange - var collection = new[] { "jane", "mike" }; + // Arrange + string[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().EndWith("john"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected*end*john*but*collection*null*"); + } + + [Fact] + public void When_non_empty_collection_ends_with_the_empty_sequence_it_should_not_throw() + { + // Arrange + var collection = new[] { "jane", "mike" }; - // Act - Action act = () => collection.Should().EndWith(new string[] { }); + // Act + Action act = () => collection.Should().EndWith(new string[] { }); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_empty_collection_ends_with_the_empty_sequence_it_should_not_throw() - { - // Arrange - var collection = new string[] { }; + [Fact] + public void When_empty_collection_ends_with_the_empty_sequence_it_should_not_throw() + { + // Arrange + var collection = new string[] { }; - // Act - Action act = () => collection.Should().EndWith(new string[] { }); + // Act + Action act = () => collection.Should().EndWith(new string[] { }); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs index 34d7add515..c187a458e1 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs @@ -11,414 +11,412 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Equal - - [Fact] - public void Should_succeed_when_asserting_collection_is_equal_to_the_same_collection() + public class Equal { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_is_equal_to_the_same_collection() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2, 3 }; - // Act / Assert - collection1.Should().Equal(collection2); - } + // Act / Assert + collection1.Should().Equal(collection2); + } - [Fact] - public void Should_succeed_when_asserting_collection_is_equal_to_the_same_list_of_elements() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_is_equal_to_the_same_list_of_elements() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().Equal(1, 2, 3); - } + // Act / Assert + collection.Should().Equal(1, 2, 3); + } - [Fact] - public void When_both_collections_are_null_it_should_succeed() - { - // Arrange - int[] nullColl = null; + [Fact] + public void When_both_collections_are_null_it_should_succeed() + { + // Arrange + int[] nullColl = null; - // Act - Action act = () => nullColl.Should().Equal(null); + // Act + Action act = () => nullColl.Should().Equal(null); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_two_collections_containing_nulls_are_equal_it_should_not_throw() - { - // Arrange - var subject = new List { "aaa", null }; - var expected = new List { "aaa", null }; + [Fact] + public void When_two_collections_containing_nulls_are_equal_it_should_not_throw() + { + // Arrange + var subject = new List { "aaa", null }; + var expected = new List { "aaa", null }; - // Act - Action action = () => subject.Should().Equal(expected); + // Act + Action action = () => subject.Should().Equal(expected); - // Assert - action.Should().NotThrow(); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_two_collections_are_not_equal_because_one_item_differs_it_should_throw_using_the_reason() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2, 5 }; + [Fact] + public void When_two_collections_are_not_equal_because_one_item_differs_it_should_throw_using_the_reason() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2, 5 }; - // Act - Action act = () => collection1.Should().Equal(collection2, "because we want to test the failure {0}", "message"); + // Act + Action act = () => collection1.Should().Equal(collection2, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 to be equal to {1, 2, 5} because we want to test the failure message, but {1, 2, 3} differs at index 2."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 to be equal to {1, 2, 5} because we want to test the failure message, but {1, 2, 3} differs at index 2."); + } - [Fact] - public void When_two_collections_are_not_equal_because_the_actual_collection_contains_more_items_it_should_throw_using_the_reason() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2 }; + [Fact] + public void When_two_collections_are_not_equal_because_the_actual_collection_contains_more_items_it_should_throw_using_the_reason() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2 }; - // Act - Action act = () => collection1.Should().Equal(collection2, "because we want to test the failure {0}", "message"); + // Act + Action act = () => collection1.Should().Equal(collection2, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 to be equal to {1, 2} because we want to test the failure message, but {1, 2, 3} contains 1 item(s) too many."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 to be equal to {1, 2} because we want to test the failure message, but {1, 2, 3} contains 1 item(s) too many."); + } - [Fact] - public void When_two_collections_are_not_equal_because_the_actual_collection_contains_less_items_it_should_throw_using_the_reason() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2, 3, 4 }; + [Fact] + public void When_two_collections_are_not_equal_because_the_actual_collection_contains_less_items_it_should_throw_using_the_reason() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2, 3, 4 }; - // Act - Action act = () => collection1.Should().Equal(collection2, "because we want to test the failure {0}", "message"); + // Act + Action act = () => collection1.Should().Equal(collection2, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 to be equal to {1, 2, 3, 4} because we want to test the failure message, but {1, 2, 3} contains 1 item(s) less."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 to be equal to {1, 2, 3, 4} because we want to test the failure message, but {1, 2, 3} contains 1 item(s) less."); + } - [Fact] - public void When_two_multidimensional_collections_are_not_equal_and_it_should_format_the_collections_properly() - { - // Arrange - var collection1 = new[] { new[] { 1, 2 }, new[] { 3, 4 } }; - var collection2 = new[] { new[] { 5, 6 }, new[] { 7, 8 } }; + [Fact] + public void When_two_multidimensional_collections_are_not_equal_and_it_should_format_the_collections_properly() + { + // Arrange + var collection1 = new[] { new[] { 1, 2 }, new[] { 3, 4 } }; + var collection2 = new[] { new[] { 5, 6 }, new[] { 7, 8 } }; - // Act - Action act = () => collection1.Should().Equal(collection2); + // Act + Action act = () => collection1.Should().Equal(collection2); - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 to be equal to {{5, 6}, {7, 8}}, but {{1, 2}, {3, 4}} differs at index 0."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 to be equal to {{5, 6}, {7, 8}}, but {{1, 2}, {3, 4}} differs at index 0."); + } - [Fact] - public void When_asserting_collections_to_be_equal_but_subject_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; - var collection1 = new[] { 1, 2, 3 }; + [Fact] + public void When_asserting_collections_to_be_equal_but_subject_collection_is_null_it_should_throw() + { + // Arrange + int[] collection = null; + var collection1 = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().Equal(collection1, "because we want to test the behaviour with a null subject"); + // Act + Action act = () => collection.Should().Equal(collection1, "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection to be equal to {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection to be equal to {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_asserting_collections_to_be_equal_but_expected_collection_is_null_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int[] collection1 = null; + [Fact] + public void When_asserting_collections_to_be_equal_but_expected_collection_is_null_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + int[] collection1 = null; - // Act - Action act = () => collection.Should().Equal(collection1, "because we want to test the behaviour with a null subject"); + // Act + Action act = () => collection.Should().Equal(collection1, "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw() - .WithMessage("Cannot compare collection with .*") - .WithParameterName("expectation"); - } + // Assert + act.Should().Throw() + .WithMessage("Cannot compare collection with .*") + .WithParameterName("expectation"); + } - [Fact] - public void When_an_empty_collection_is_compared_for_equality_to_a_non_empty_collection_it_should_throw() - { - // Arrange - var collection1 = new int[0]; - var collection2 = new[] { 1, 2, 3 }; + [Fact] + public void When_an_empty_collection_is_compared_for_equality_to_a_non_empty_collection_it_should_throw() + { + // Arrange + var collection1 = new int[0]; + var collection2 = new[] { 1, 2, 3 }; - // Act - Action act = () => collection1.Should().Equal(collection2); + // Act + Action act = () => collection1.Should().Equal(collection2); - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 to be equal to {1, 2, 3}, but found empty collection."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 to be equal to {1, 2, 3}, but found empty collection."); + } - [Fact] - public void When_a_non_empty_collection_is_compared_for_equality_to_an_empty_collection_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new int[0]; + [Fact] + public void When_a_non_empty_collection_is_compared_for_equality_to_an_empty_collection_it_should_throw() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new int[0]; - // Act - Action act = () => collection1.Should().Equal(collection2); + // Act + Action act = () => collection1.Should().Equal(collection2); - // Assert - act.Should().Throw().WithMessage( - "Expected collection1 to be equal to {empty}, but found {1, 2, 3}."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection1 to be equal to {empty}, but found {1, 2, 3}."); + } - [Fact] - public void When_all_items_match_according_to_a_predicate_it_should_succeed() - { - // Arrange - var actual = new List { "ONE", "TWO", "THREE", "FOUR" }; - var expected = new[] + [Fact] + public void When_all_items_match_according_to_a_predicate_it_should_succeed() { - new { Value = "One" }, - new { Value = "Two" }, - new { Value = "Three" }, - new { Value = "Four" } - }; - - // Act - Action action = () => actual.Should().Equal(expected, - (a, e) => string.Equals(a, e.Value, StringComparison.OrdinalIgnoreCase)); - - // Assert - action.Should().NotThrow(); - } + // Arrange + var actual = new List { "ONE", "TWO", "THREE", "FOUR" }; + var expected = new[] + { + new { Value = "One" }, + new { Value = "Two" }, + new { Value = "Three" }, + new { Value = "Four" } + }; + + // Act + Action action = () => actual.Should().Equal(expected, + (a, e) => string.Equals(a, e.Value, StringComparison.OrdinalIgnoreCase)); + + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_any_item_does_not_match_according_to_a_predicate_it_should_throw() - { - // Arrange - var actual = new List { "ONE", "TWO", "THREE", "FOUR" }; - var expected = new[] + [Fact] + public void When_any_item_does_not_match_according_to_a_predicate_it_should_throw() { - new { Value = "One" }, - new { Value = "Two" }, - new { Value = "Three" }, - new { Value = "Five" } - }; - - // Act - Action action = () => actual.Should().Equal(expected, - (a, e) => string.Equals(a, e.Value, StringComparison.OrdinalIgnoreCase)); - - // Assert - action - .Should().Throw() - .WithMessage("*Expected*equal to*, but*differs at index 3.*"); - } - - [Fact] - public void When_both_collections_are_empty_it_should_them_as_equal() - { - // Arrange - var actual = new List(); - var expected = new List(); - - // Act - Action act = () => actual.Should().Equal(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_identical_collections_to_be_equal_it_should_enumerate_the_subject_only_once() - { - // Arrange - var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); - var expected = new[] { 1, 2, 3 }; - - // Act - actual.Should().Equal(expected); + // Arrange + var actual = new List { "ONE", "TWO", "THREE", "FOUR" }; + var expected = new[] + { + new { Value = "One" }, + new { Value = "Two" }, + new { Value = "Three" }, + new { Value = "Five" } + }; + + // Act + Action action = () => actual.Should().Equal(expected, + (a, e) => string.Equals(a, e.Value, StringComparison.OrdinalIgnoreCase)); + + // Assert + action + .Should().Throw() + .WithMessage("*Expected*equal to*, but*differs at index 3.*"); + } - // Assert - actual.GetEnumeratorCallCount.Should().Be(1); - } + [Fact] + public void When_both_collections_are_empty_it_should_them_as_equal() + { + // Arrange + var actual = new List(); + var expected = new List(); - [Fact] - public void When_asserting_identical_collections_to_not_be_equal_it_should_enumerate_the_subject_only_once() - { - // Arrange - var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); - var expected = new[] { 1, 2, 3 }; + // Act + Action act = () => actual.Should().Equal(expected); - // Act - try - { - actual.Should().NotEqual(expected); + // Assert + act.Should().NotThrow(); } - catch + + [Fact] + public void When_asserting_identical_collections_to_be_equal_it_should_enumerate_the_subject_only_once() { - /* we don't care about the exception, we just need to check the enumeration count */ - } + // Arrange + var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); + var expected = new[] { 1, 2, 3 }; - // Assert - actual.GetEnumeratorCallCount.Should().Be(1); - } + // Act + actual.Should().Equal(expected); - [Fact] - public void When_asserting_different_collections_to_be_equal_it_should_enumerate_the_subject_once() - { - // Arrange - var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); - var expected = new[] { 1, 2, 4 }; + // Assert + actual.GetEnumeratorCallCount.Should().Be(1); + } - // Act - try + [Fact] + public void When_asserting_identical_collections_to_not_be_equal_it_should_enumerate_the_subject_only_once() { - actual.Should().Equal(expected); + // Arrange + var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); + var expected = new[] { 1, 2, 3 }; + + // Act + try + { + actual.Should().NotEqual(expected); + } + catch + { + /* we don't care about the exception, we just need to check the enumeration count */ + } + + // Assert + actual.GetEnumeratorCallCount.Should().Be(1); } - catch + + [Fact] + public void When_asserting_different_collections_to_be_equal_it_should_enumerate_the_subject_once() { - /* we don't care about the exception, we just need to check the enumeration count */ + // Arrange + var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); + var expected = new[] { 1, 2, 4 }; + + // Act + try + { + actual.Should().Equal(expected); + } + catch + { + /* we don't care about the exception, we just need to check the enumeration count */ + } + + // Assert + actual.GetEnumeratorCallCount.Should().Be(1); } - // Assert - actual.GetEnumeratorCallCount.Should().Be(1); - } - - [Fact] - public void When_asserting_different_collections_to_not_be_equal_it_should_enumerate_the_subject_only_once() - { - // Arrange - var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); - var expected = new[] { 1, 2, 4 }; + [Fact] + public void When_asserting_different_collections_to_not_be_equal_it_should_enumerate_the_subject_only_once() + { + // Arrange + var actual = new CountingGenericEnumerable(new[] { 1, 2, 3 }); + var expected = new[] { 1, 2, 4 }; - // Act - actual.Should().NotEqual(expected); + // Act + actual.Should().NotEqual(expected); - // Assert - actual.GetEnumeratorCallCount.Should().Be(1); - } + // Assert + actual.GetEnumeratorCallCount.Should().Be(1); + } - [Fact] - public void When_asserting_equality_with_a_collection_built_from_params_arguments_that_are_assignable_to_the_subjects_type_parameter_it_should_succeed_by_treating_the_arguments_as_of_that_type() - { - // Arrange - byte[] byteArray = { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }; + [Fact] + public void When_asserting_equality_with_a_collection_built_from_params_arguments_that_are_assignable_to_the_subjects_type_parameter_it_should_succeed_by_treating_the_arguments_as_of_that_type() + { + // Arrange + byte[] byteArray = { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }; - // Act - Action act = () => byteArray.Should().Equal(0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10); + // Act + Action act = () => byteArray.Should().Equal(0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - - #endregion - - #region Not Equal - - [Fact] - public void Should_succeed_when_asserting_collection_is_not_equal_to_a_different_collection() + + public class NotEqual { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 3, 1, 2 }; - - // Act / Assert - collection1.Should() - .NotEqual(collection2); - } + [Fact] + public void Should_succeed_when_asserting_collection_is_not_equal_to_a_different_collection() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 3, 1, 2 }; - [Fact] - public void When_two_equal_collections_are_not_expected_to_be_equal_it_should_throw() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2, 3 }; + // Act / Assert + collection1.Should() + .NotEqual(collection2); + } - // Act - Action act = () => collection1.Should().NotEqual(collection2); + [Fact] + public void When_two_equal_collections_are_not_expected_to_be_equal_it_should_throw() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Did not expect collections {1, 2, 3} and {1, 2, 3} to be equal."); - } + // Act + Action act = () => collection1.Should().NotEqual(collection2); - [Fact] - public void When_two_equal_collections_are_not_expected_to_be_equal_it_should_report_a_clear_explanation() - { - // Arrange - var collection1 = new[] { 1, 2, 3 }; - var collection2 = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw().WithMessage( + "Did not expect collections {1, 2, 3} and {1, 2, 3} to be equal."); + } - // Act - Action act = () => collection1.Should().NotEqual(collection2, "because we want to test the failure {0}", "message"); + [Fact] + public void When_two_equal_collections_are_not_expected_to_be_equal_it_should_report_a_clear_explanation() + { + // Arrange + var collection1 = new[] { 1, 2, 3 }; + var collection2 = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Did not expect collections {1, 2, 3} and {1, 2, 3} to be equal because we want to test the failure message."); - } + // Act + Action act = () => collection1.Should().NotEqual(collection2, "because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_collections_not_to_be_equal_subject_but_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; - var collection1 = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw().WithMessage( + "Did not expect collections {1, 2, 3} and {1, 2, 3} to be equal because we want to test the failure message."); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collections_not_to_be_equal_subject_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotEqual(collection1, "because we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collections not to be equal because we want to test the behaviour with a null subject, but found ."); - } + // Arrange + int[] collection = null; + var collection1 = new[] { 1, 2, 3 }; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotEqual(collection1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collections not to be equal because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_asserting_collections_not_to_be_equal_but_expected_collection_is_null_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int[] collection1 = null; - - // Act - Action act = - () => collection.Should().NotEqual(collection1, "because we want to test the behaviour with a null subject"); - - // Assert - act.Should().Throw() - .WithMessage("Cannot compare collection with .*") - .WithParameterName("unexpected"); - } + [Fact] + public void When_asserting_collections_not_to_be_equal_but_expected_collection_is_null_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + int[] collection1 = null; + + // Act + Action act = + () => collection.Should().NotEqual(collection1, "because we want to test the behaviour with a null subject"); + + // Assert + act.Should().Throw() + .WithMessage("Cannot compare collection with .*") + .WithParameterName("unexpected"); + } - [Fact] - public void When_asserting_collections_not_to_be_equal_but_both_collections_reference_the_same_object_it_should_throw() - { - var collection1 = new[] { "one", "two", "three" }; - var collection2 = collection1; + [Fact] + public void When_asserting_collections_not_to_be_equal_but_both_collections_reference_the_same_object_it_should_throw() + { + var collection1 = new[] { "one", "two", "three" }; + var collection2 = collection1; - // Act - Action act = () => collection1.Should().NotEqual(collection2, "because we want to test the behaviour with same objects"); + // Act + Action act = () => collection1.Should().NotEqual(collection2, "because we want to test the behaviour with same objects"); - // Assert - act.Should().Throw().WithMessage( - "Expected collections not to be equal because we want to test the behaviour with same objects, but they both reference the same object."); + // Assert + act.Should().Throw().WithMessage( + "Expected collections not to be equal because we want to test the behaviour with same objects, but they both reference the same object."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs index fb9710a3c5..a03935bd4a 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs @@ -10,230 +10,228 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Count - - [Fact] - public void Should_succeed_when_asserting_collection_has_a_count_that_equals_the_number_of_items() + public class HaveCount { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act / Assert - collection.Should().HaveCount(3); - } - - [Fact] - public void Should_fail_when_asserting_collection_has_a_count_that_is_different_from_the_number_of_items() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().HaveCount(4); - - // Assert - act.Should().Throw(); - } + [Fact] + public void Should_succeed_when_asserting_collection_has_a_count_that_equals_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_has_a_count_that_is_different_from_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Act / Assert + collection.Should().HaveCount(3); + } - // Act - Action action = () => collection.Should().HaveCount(4, "because we want to test the failure {0}", "message"); + [Fact] + public void Should_fail_when_asserting_collection_has_a_count_that_is_different_from_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - action.Should().Throw() - .WithMessage("Expected collection to contain 4 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); - } + // Act + Action act = () => collection.Should().HaveCount(4); - [Fact] - public void When_collection_has_a_count_larger_than_the_minimum_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw(); + } - // Act / Assert - collection.Should().HaveCount(c => c >= 3); - } + [Fact] + public void When_collection_has_a_count_that_is_different_from_the_number_of_items_it_should_fail_with_descriptive_message_() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_has_a_count_that_not_matches_the_predicate_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Act + Action action = () => collection.Should().HaveCount(4, "because we want to test the failure {0}", "message"); - // Act - Action act = () => collection.Should().HaveCount(c => c >= 4, "a minimum of 4 is required"); + // Assert + action.Should().Throw() + .WithMessage("Expected collection to contain 4 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected collection to have a count (c >= 4) because a minimum of 4 is required, but count is 3: {1, 2, 3}."); - } + [Fact] + public void When_collection_has_a_count_larger_than_the_minimum_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_count_is_matched_against_a_null_predicate_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Act / Assert + collection.Should().HaveCount(c => c >= 3); + } - // Act - Action act = () => collection.Should().HaveCount(null); + [Fact] + public void When_collection_has_a_count_that_not_matches_the_predicate_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Cannot compare collection count against a predicate.*"); - } + // Act + Action act = () => collection.Should().HaveCount(c => c >= 4, "a minimum of 4 is required"); - [Fact] - public void When_collection_count_is_matched_and_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected collection to have a count (c >= 4) because a minimum of 4 is required, but count is 3: {1, 2, 3}."); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_matched_against_a_null_predicate_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveCount(1, "we want to test the behaviour with a null subject"); - }; + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain 1 item(s) because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => collection.Should().HaveCount(null); - [Fact] - public void When_collection_count_is_matched_against_a_predicate_and_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Cannot compare collection count against a predicate.*"); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_matched_and_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveCount(c => c < 3, "we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain (c < 3) items because we want to test the behaviour with a null subject, but found ."); - } - - [Fact] - public void When_collection_count_is_matched_against_a_predicate_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveCount(1, "we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain 1 item(s) because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_collection_count_is_matched_against_a_predicate_and_collection_is_null_it_should_throw() + { + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveCount(c => c < 3, "we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain (c < 3) items because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_collection_count_is_matched_against_a_predicate_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().HaveCount(c => c % 2 == 1); + // Act + Action act = () => collection.Should().HaveCount(c => c % 2 == 1); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_collection_count_is_matched_against_a_predicate_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_collection_count_is_matched_against_a_predicate_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().HaveCount(c => c % 2 == 0); + // Act + Action act = () => collection.Should().HaveCount(c => c % 2 == 0); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_counting_generic_enumerable_it_should_enumerate() - { - // Arrange - var enumerable = new CountingGenericEnumerable(new[] { 1, 2, 3 }); + [Fact] + public void When_counting_generic_enumerable_it_should_enumerate() + { + // Arrange + var enumerable = new CountingGenericEnumerable(new[] { 1, 2, 3 }); - // Act - enumerable.Should().HaveCount(3); + // Act + enumerable.Should().HaveCount(3); - // Assert - enumerable.GetEnumeratorCallCount.Should().Be(1); - } + // Assert + enumerable.GetEnumeratorCallCount.Should().Be(1); + } - [Fact] - public void When_counting_generic_collection_it_should_not_enumerate() - { - // Arrange - var collection = new CountingGenericCollection(new[] { 1, 2, 3 }); + [Fact] + public void When_counting_generic_collection_it_should_not_enumerate() + { + // Arrange + var collection = new CountingGenericCollection(new[] { 1, 2, 3 }); - // Act - collection.Should().HaveCount(3); + // Act + collection.Should().HaveCount(3); - // Assert - collection.GetCountCallCount.Should().Be(1); - collection.GetEnumeratorCallCount.Should().Be(0); + // Assert + collection.GetCountCallCount.Should().Be(1); + collection.GetEnumeratorCallCount.Should().Be(0); + } } - - #endregion - - #region Not Have Count - - [Fact] - public void Should_succeed_when_asserting_collection_has_a_count_different_from_the_number_of_items() + + public class NotHaveCount { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_has_a_count_different_from_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().NotHaveCount(2); - } + // Act / Assert + collection.Should().NotHaveCount(2); + } - [Fact] - public void Should_fail_when_asserting_collection_has_a_count_that_equals_the_number_of_items() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_fail_when_asserting_collection_has_a_count_that_equals_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().NotHaveCount(3); + // Act + Action act = () => collection.Should().NotHaveCount(3); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_collection_has_a_count_that_equals_than_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action action = () => collection.Should().NotHaveCount(3, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_has_a_count_that_equals_than_the_number_of_items_it_should_fail_with_descriptive_message_() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - action.Should().Throw() - .WithMessage("*not contain*3*because we want to test the failure message*3*"); - } + // Act + Action action = () => collection.Should().NotHaveCount(3, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_count_is_same_than_and_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + action.Should().Throw() + .WithMessage("*not contain*3*because we want to test the failure message*3*"); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_same_than_and_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotHaveCount(1, "we want to test the behaviour with a null subject"); - }; + // Arrange + int[] collection = null; - // Assert - act.Should().Throw().WithMessage("*not contain*1*we want to test the behaviour with a null subject*found *"); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotHaveCount(1, "we want to test the behaviour with a null subject"); + }; - #endregion + // Assert + act.Should().Throw().WithMessage("*not contain*1*we want to test the behaviour with a null subject*found *"); + } + } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThan.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThan.cs index 627551d3fa..83f240dc9a 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThan.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThan.cs @@ -11,62 +11,61 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Count Greater Than - - [Fact] - public void Should_succeed_when_asserting_collection_has_a_count_greater_than_less_the_number_of_items() + public class HaveCountGreaterThan { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_has_a_count_greater_than_less_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().HaveCountGreaterThan(2); - } + // Act / Assert + collection.Should().HaveCountGreaterThan(2); + } - [Fact] - public void Should_fail_when_asserting_collection_has_a_count_greater_than_the_number_of_items() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_fail_when_asserting_collection_has_a_count_greater_than_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().HaveCountGreaterThan(3); + // Act + Action act = () => collection.Should().HaveCountGreaterThan(3); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_collection_has_a_count_greater_than_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action action = () => collection.Should().HaveCountGreaterThan(3, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_has_a_count_greater_than_the_number_of_items_it_should_fail_with_descriptive_message_() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - action.Should().Throw() - .WithMessage("Expected collection to contain more than 3 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); - } + // Act + Action action = () => collection.Should().HaveCountGreaterThan(3, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_count_is_greater_than_and_collection_is_null_it_should_throw() - { - // Arrange - IEnumerable collection = null; + // Assert + action.Should().Throw() + .WithMessage("Expected collection to contain more than 3 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_greater_than_and_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveCountGreaterThan(1, "we want to test the behaviour with a null subject"); - }; + // Arrange + IEnumerable collection = null; - // Assert - act.Should().Throw().WithMessage("*more than*1*we want to test the behaviour with a null subject*found *"); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveCountGreaterThan(1, "we want to test the behaviour with a null subject"); + }; - #endregion + // Assert + act.Should().Throw().WithMessage("*more than*1*we want to test the behaviour with a null subject*found *"); + } + } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThanOrEqualTo.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThanOrEqualTo.cs index 3d58081a19..4ba1c88a8f 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThanOrEqualTo.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountGreaterThanOrEqualTo.cs @@ -10,62 +10,61 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Count Greater Than Or Equal To - - [Fact] - public void Should_succeed_when_asserting_collection_has_a_count_greater_than_or_equal_to_less_the_number_of_items() + public class HaveCountGreaterThanOrEqualTo { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_has_a_count_greater_than_or_equal_to_less_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().HaveCountGreaterThanOrEqualTo(3); - } + // Act / Assert + collection.Should().HaveCountGreaterThanOrEqualTo(3); + } - [Fact] - public void Should_fail_when_asserting_collection_has_a_count_greater_than_or_equal_to_the_number_of_items() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_fail_when_asserting_collection_has_a_count_greater_than_or_equal_to_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().HaveCountGreaterThanOrEqualTo(4); + // Act + Action act = () => collection.Should().HaveCountGreaterThanOrEqualTo(4); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_collection_has_a_count_greater_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action action = () => collection.Should().HaveCountGreaterThanOrEqualTo(4, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_has_a_count_greater_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - action.Should().Throw() - .WithMessage("Expected collection to contain at least 4 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); - } + // Act + Action action = () => collection.Should().HaveCountGreaterThanOrEqualTo(4, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_count_is_greater_than_or_equal_to_and_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + action.Should().Throw() + .WithMessage("Expected collection to contain at least 4 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_greater_than_or_equal_to_and_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveCountGreaterThanOrEqualTo(1, "we want to test the behaviour with a null subject"); - }; + // Arrange + int[] collection = null; - // Assert - act.Should().Throw().WithMessage("*at least*1*we want to test the behaviour with a null subject*found *"); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveCountGreaterThanOrEqualTo(1, "we want to test the behaviour with a null subject"); + }; - #endregion + // Assert + act.Should().Throw().WithMessage("*at least*1*we want to test the behaviour with a null subject*found *"); + } + } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThan.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThan.cs index 121f52a30f..ce6e594abf 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThan.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThan.cs @@ -10,62 +10,61 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Count Less Than - - [Fact] - public void Should_succeed_when_asserting_collection_has_a_count_less_than_less_the_number_of_items() + public class HaveCountLessThan { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_has_a_count_less_than_less_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().HaveCountLessThan(4); - } + // Act / Assert + collection.Should().HaveCountLessThan(4); + } - [Fact] - public void Should_fail_when_asserting_collection_has_a_count_less_than_the_number_of_items() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_fail_when_asserting_collection_has_a_count_less_than_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().HaveCountLessThan(3); + // Act + Action act = () => collection.Should().HaveCountLessThan(3); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_collection_has_a_count_less_than_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action action = () => collection.Should().HaveCountLessThan(3, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_has_a_count_less_than_the_number_of_items_it_should_fail_with_descriptive_message_() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - action.Should().Throw() - .WithMessage("Expected collection to contain fewer than 3 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); - } + // Act + Action action = () => collection.Should().HaveCountLessThan(3, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_count_is_less_than_and_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + action.Should().Throw() + .WithMessage("Expected collection to contain fewer than 3 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_less_than_and_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveCountLessThan(1, "we want to test the behaviour with a null subject"); - }; + // Arrange + int[] collection = null; - // Assert - act.Should().Throw().WithMessage("*fewer than*1*we want to test the behaviour with a null subject*found *"); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveCountLessThan(1, "we want to test the behaviour with a null subject"); + }; - #endregion + // Assert + act.Should().Throw().WithMessage("*fewer than*1*we want to test the behaviour with a null subject*found *"); + } + } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThanOrEqualTo.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThanOrEqualTo.cs index e7858c6663..9d790a37ae 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThanOrEqualTo.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCountLessThanOrEqualTo.cs @@ -10,62 +10,61 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Count Less Than Or Equal To - - [Fact] - public void Should_succeed_when_asserting_collection_has_a_count_less_than_or_equal_to_less_the_number_of_items() + public class HaveCountLessThanOrEqualTo { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_succeed_when_asserting_collection_has_a_count_less_than_or_equal_to_less_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().HaveCountLessThanOrEqualTo(3); - } + // Act / Assert + collection.Should().HaveCountLessThanOrEqualTo(3); + } - [Fact] - public void Should_fail_when_asserting_collection_has_a_count_less_than_or_equal_to_the_number_of_items() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void Should_fail_when_asserting_collection_has_a_count_less_than_or_equal_to_the_number_of_items() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().HaveCountLessThanOrEqualTo(2); + // Act + Action act = () => collection.Should().HaveCountLessThanOrEqualTo(2); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_collection_has_a_count_less_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action action = () => collection.Should().HaveCountLessThanOrEqualTo(2, "because we want to test the failure {0}", "message"); + [Fact] + public void When_collection_has_a_count_less_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - action.Should().Throw() - .WithMessage("Expected collection to contain at most 2 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); - } + // Act + Action action = () => collection.Should().HaveCountLessThanOrEqualTo(2, "because we want to test the failure {0}", "message"); - [Fact] - public void When_collection_count_is_less_than_or_equal_to_and_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + action.Should().Throw() + .WithMessage("Expected collection to contain at most 2 item(s) because we want to test the failure message, but found 3: {1, 2, 3}."); + } - // Act - Action act = () => + [Fact] + public void When_collection_count_is_less_than_or_equal_to_and_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveCountLessThanOrEqualTo(1, "we want to test the behaviour with a null subject"); - }; + // Arrange + int[] collection = null; - // Assert - act.Should().Throw().WithMessage("*at most*1*we want to test the behaviour with a null subject*found *"); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveCountLessThanOrEqualTo(1, "we want to test the behaviour with a null subject"); + }; - #endregion + // Assert + act.Should().Throw().WithMessage("*at most*1*we want to test the behaviour with a null subject*found *"); + } + } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementAt.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementAt.cs index a5d09b59c7..b6faa4c6ae 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementAt.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementAt.cs @@ -10,89 +10,88 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Element At - - [Fact] - public void When_collection_has_expected_element_at_specific_index_it_should_not_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act / Assert - collection.Should().HaveElementAt(1, 2); - } - - [Fact] - public void When_collection_does_not_have_the_expected_element_at_specific_index_it_should_throw() + public class HaveElementAt { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().HaveElementAt(1, 3, "we put it {0}", "there"); - - // Assert - act.Should().Throw().WithMessage( - "Expected 3 at index 1 because we put it there, but found 2."); - } + [Fact] + public void When_collection_has_expected_element_at_specific_index_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - [Fact] - public void When_collection_does_not_have_an_element_at_the_specific_index_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + // Act / Assert + collection.Should().HaveElementAt(1, 2); + } - // Act - Action act = () => collection.Should().HaveElementAt(4, 3, "we put it {0}", "there"); + [Fact] + public void When_collection_does_not_have_the_expected_element_at_specific_index_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected 3 at index 4 because we put it there, but found no element."); - } + // Act + Action act = () => collection.Should().HaveElementAt(1, 3, "we put it {0}", "there"); - [Fact] - public void When_asserting_collection_has_element_at_specific_index_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected 3 at index 1 because we put it there, but found 2."); + } - // Act - Action act = () => + [Fact] + public void When_collection_does_not_have_an_element_at_the_specific_index_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().HaveElementAt(1, 1, "because we want to test the behaviour with a null subject"); - }; + // Arrange + var collection = new[] { 1, 2, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to have element at index 1 because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => collection.Should().HaveElementAt(4, 3, "we put it {0}", "there"); - [Fact] - public void When_element_at_specific_index_was_found_it_should_allow_chaining() - { - // Arrange - var expectedElement = new - { - SomeProperty = "hello" - }; + // Assert + act.Should().Throw().WithMessage( + "Expected 3 at index 4 because we put it there, but found no element."); + } - var collection = new[] + [Fact] + public void When_asserting_collection_has_element_at_specific_index_against_null_collection_it_should_throw() { - expectedElement - }; - - // Act - Action act = () => collection.Should() - .HaveElementAt(0, expectedElement) - .Which - .Should().BeAssignableTo(); - - // Assert - act.Should().Throw() - .WithMessage("Expected*assignable*string*"); + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveElementAt(1, 1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to have element at index 1 because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_element_at_specific_index_was_found_it_should_allow_chaining() + { + // Arrange + var expectedElement = new + { + SomeProperty = "hello" + }; + + var collection = new[] + { + expectedElement + }; + + // Act + Action act = () => collection.Should() + .HaveElementAt(0, expectedElement) + .Which + .Should().BeAssignableTo(); + + // Assert + act.Should().Throw() + .WithMessage("Expected*assignable*string*"); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementPreceding.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementPreceding.cs index 792a00d9f8..5e309a03b0 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementPreceding.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementPreceding.cs @@ -12,141 +12,140 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region HaveElementPreceding - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_collection_has_the_correct_element_preceding_another_it_should_not_throw() + public class HaveElementPreceding { - // Arrange - var collection = new[] { "cris", "mick", "john" }; + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_collection_has_the_correct_element_preceding_another_it_should_not_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Act - Action act = () => collection.Should().HaveElementPreceding("mick", "cris"); + // Act + Action act = () => collection.Should().HaveElementPreceding("mick", "cris"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_collection_has_the_wrong_element_preceding_another_it_should_not_throw() - { - // Arrange - var collection = new[] { "cris", "mick", "john" }; - - // Act - Action act = () => collection.Should().HaveElementPreceding("john", "cris", "because of some reason"); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_collection_has_the_wrong_element_preceding_another_it_should_not_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*cris*precede*john*because*reason*found*mick*"); - } + // Act + Action act = () => collection.Should().HaveElementPreceding("john", "cris", "because of some reason"); - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_nothing_is_preceding_an_element_it_should_throw() - { - // Arrange - var collection = new[] { "cris", "mick", "john" }; + // Assert + act.Should().Throw() + .WithMessage("Expected*cris*precede*john*because*reason*found*mick*"); + } - // Act - Action act = () => collection.Should().HaveElementPreceding("cris", "jane"); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_nothing_is_preceding_an_element_it_should_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*jane*precede*cris*found*nothing*"); - } + // Act + Action act = () => collection.Should().HaveElementPreceding("cris", "jane"); - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_expecting_an_element_to_precede_another_but_collection_is_empty_it_should_throw() - { - // Arrange - var collection = new string[0]; + // Assert + act.Should().Throw() + .WithMessage("Expected*jane*precede*cris*found*nothing*"); + } - // Act - Action act = () => collection.Should().HaveElementPreceding("mick", "cris"); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_expecting_an_element_to_precede_another_but_collection_is_empty_it_should_throw() + { + // Arrange + var collection = new string[0]; - // Assert - act.Should().Throw() - .WithMessage("Expected*cris*precede*mick*collection*empty*"); - } + // Act + Action act = () => collection.Should().HaveElementPreceding("mick", "cris"); - [Fact] - public void When_a_null_element_is_preceding_another_element_it_should_not_throw() - { - // Arrange - var collection = new[] { null, "mick", "john" }; + // Assert + act.Should().Throw() + .WithMessage("Expected*cris*precede*mick*collection*empty*"); + } - // Act - Action act = () => collection.Should().HaveElementPreceding("mick", null); + [Fact] + public void When_a_null_element_is_preceding_another_element_it_should_not_throw() + { + // Arrange + var collection = new[] { null, "mick", "john" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().HaveElementPreceding("mick", null); - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_a_null_element_is_not_preceding_another_element_it_should_throw() - { - // Arrange - var collection = new[] { "cris", "mick", "john" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().HaveElementPreceding("mick", null); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_a_null_element_is_not_preceding_another_element_it_should_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*null*precede*mick*but found*cris*"); - } + // Act + Action act = () => collection.Should().HaveElementPreceding("mick", null); - [Fact] - public void When_an_element_is_preceding_a_null_element_it_should_not_throw() - { - // Arrange - var collection = new[] { "mick", null, "john" }; + // Assert + act.Should().Throw() + .WithMessage("Expected*null*precede*mick*but found*cris*"); + } - // Act - Action act = () => collection.Should().HaveElementPreceding(null, "mick"); + [Fact] + public void When_an_element_is_preceding_a_null_element_it_should_not_throw() + { + // Arrange + var collection = new[] { "mick", null, "john" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().HaveElementPreceding(null, "mick"); - [Fact] - public void When_an_element_is_not_preceding_a_null_element_it_should_throw() - { - // Arrange - var collection = new[] { "mick", null, "john" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().HaveElementPreceding(null, "cris"); + [Fact] + public void When_an_element_is_not_preceding_a_null_element_it_should_throw() + { + // Arrange + var collection = new[] { "mick", null, "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*cris*precede*null*but found*mick*"); - } + // Act + Action act = () => collection.Should().HaveElementPreceding(null, "cris"); - [Fact] - public void When_collection_is_null_then_have_element_preceding_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw() + .WithMessage("Expected*cris*precede*null*but found*mick*"); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_have_element_preceding_should_fail() { - using var _ = new AssertionScope(); - collection.Should().HaveElementPreceding("mick", "cris", "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage( - "Expected collection to have \"cris\" precede \"mick\" *failure message*, but the collection is ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveElementPreceding("mick", "cris", "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage( + "Expected collection to have \"cris\" precede \"mick\" *failure message*, but the collection is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementSucceeding.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementSucceeding.cs index 842c4e2543..a638f3d08a 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementSucceeding.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveElementSucceeding.cs @@ -12,139 +12,138 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region HaveElementSucceeding - - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_collection_has_the_correct_element_succeeding_another_it_should_not_throw() + public class HaveElementSucceeding { - // Arrange - var collection = new[] { "cris", "mick", "john" }; + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_collection_has_the_correct_element_succeeding_another_it_should_not_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Act - Action act = () => collection.Should().HaveElementSucceeding("cris", "mick"); + // Act + Action act = () => collection.Should().HaveElementSucceeding("cris", "mick"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_collection_has_the_wrong_element_succeeding_another_it_should_not_throw() - { - // Arrange - var collection = new[] { "cris", "mick", "john" }; - - // Act - Action act = () => collection.Should().HaveElementSucceeding("mick", "cris", "because of some reason"); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_collection_has_the_wrong_element_succeeding_another_it_should_not_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*cris*succeed*mick*because*reason*found*john*"); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding("mick", "cris", "because of some reason"); - [Fact] - [SuppressMessage("ReSharper", "StringLiteralTypo")] - public void When_nothing_is_succeeding_an_element_it_should_throw() - { - // Arrange - var collection = new[] { "cris", "mick", "john" }; + // Assert + act.Should().Throw() + .WithMessage("Expected*cris*succeed*mick*because*reason*found*john*"); + } - // Act - Action act = () => collection.Should().HaveElementSucceeding("john", "jane"); + [Fact] + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public void When_nothing_is_succeeding_an_element_it_should_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*jane*succeed*john*found*nothing*"); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding("john", "jane"); - [Fact] - public void When_expecting_an_element_to_succeed_another_but_the_collection_is_empty_it_should_throw() - { - // Arrange - var collection = new string[0]; + // Assert + act.Should().Throw() + .WithMessage("Expected*jane*succeed*john*found*nothing*"); + } - // Act - Action act = () => collection.Should().HaveElementSucceeding("mick", "cris"); + [Fact] + public void When_expecting_an_element_to_succeed_another_but_the_collection_is_empty_it_should_throw() + { + // Arrange + var collection = new string[0]; - // Assert - act.Should().Throw() - .WithMessage("Expected*cris*succeed*mick*collection*empty*"); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding("mick", "cris"); - [Fact] - public void When_a_null_element_is_succeeding_another_element_it_should_not_throw() - { - // Arrange - var collection = new[] { "mick", null, "john" }; + // Assert + act.Should().Throw() + .WithMessage("Expected*cris*succeed*mick*collection*empty*"); + } - // Act - Action act = () => collection.Should().HaveElementSucceeding("mick", null); + [Fact] + public void When_a_null_element_is_succeeding_another_element_it_should_not_throw() + { + // Arrange + var collection = new[] { "mick", null, "john" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding("mick", null); - [Fact] - public void When_a_null_element_is_not_succeeding_another_element_it_should_throw() - { - // Arrange - var collection = new[] { "cris", "mick", "john" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().HaveElementSucceeding("mick", null); + [Fact] + public void When_a_null_element_is_not_succeeding_another_element_it_should_throw() + { + // Arrange + var collection = new[] { "cris", "mick", "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*null*succeed*mick*but found*john*"); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding("mick", null); - [Fact] - public void When_an_element_is_succeeding_a_null_element_it_should_not_throw() - { - // Arrange - var collection = new[] { "mick", null, "john" }; + // Assert + act.Should().Throw() + .WithMessage("Expected*null*succeed*mick*but found*john*"); + } - // Act - Action act = () => collection.Should().HaveElementSucceeding(null, "john"); + [Fact] + public void When_an_element_is_succeeding_a_null_element_it_should_not_throw() + { + // Arrange + var collection = new[] { "mick", null, "john" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding(null, "john"); - [Fact] - public void When_an_element_is_not_succeeding_a_null_element_it_should_throw() - { - // Arrange - var collection = new[] { "mick", null, "john" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().HaveElementSucceeding(null, "cris"); + [Fact] + public void When_an_element_is_not_succeeding_a_null_element_it_should_throw() + { + // Arrange + var collection = new[] { "mick", null, "john" }; - // Assert - act.Should().Throw() - .WithMessage("Expected*cris*succeed*null*but found*john*"); - } + // Act + Action act = () => collection.Should().HaveElementSucceeding(null, "cris"); - [Fact] - public void When_collection_is_null_then_have_element_succeeding_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw() + .WithMessage("Expected*cris*succeed*null*but found*john*"); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_have_element_succeeding_should_fail() { - using var _ = new AssertionScope(); - collection.Should().HaveElementSucceeding("mick", "cris", "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage( - "Expected collection to have \"cris\" succeed \"mick\" *failure message*, but the collection is ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveElementSucceeding("mick", "cris", "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage( + "Expected collection to have \"cris\" succeed \"mick\" *failure message*, but the collection is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveSameCount.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveSameCount.cs index 9ca9cc5e99..e8d100e283 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveSameCount.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveSameCount.cs @@ -10,178 +10,176 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Have Same Count - - [Fact] - public void When_both_collections_have_the_same_number_elements_it_should_succeed() - { - // Arrange - var firstCollection = new[] { 1, 2, 3 }; - var secondCollection = new[] { 4, 5, 6 }; - - // Act / Assert - firstCollection.Should().HaveSameCount(secondCollection); - } - - [Fact] - public void When_both_collections_do_not_have_the_same_number_of_elements_it_should_fail() - { - // Arrange - var firstCollection = new[] { 1, 2, 3 }; - var secondCollection = new[] { 4, 6 }; - - // Act - Action act = () => firstCollection.Should().HaveSameCount(secondCollection); - - // Assert - act.Should().Throw().WithMessage( - "Expected firstCollection to have 2 item(s), but found 3."); - } - - [Fact] - public void When_comparing_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() + public class HaveSameCount { - // Arrange - var firstCollection = new[] { 1, 2, 3 }; - var secondCollection = new[] { 4, 6 }; - - // Act - Action act = () => firstCollection.Should().HaveSameCount(secondCollection, "we want to test the {0}", "reason"); - - // Assert - act.Should().Throw().WithMessage( - "Expected firstCollection to have 2 item(s) because we want to test the reason, but found 3."); - } + [Fact] + public void When_both_collections_have_the_same_number_elements_it_should_succeed() + { + // Arrange + var firstCollection = new[] { 1, 2, 3 }; + var secondCollection = new[] { 4, 5, 6 }; - [Fact] - public void When_asserting_collections_to_have_same_count_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; - var collection1 = new[] { 1, 2, 3 }; + // Act / Assert + firstCollection.Should().HaveSameCount(secondCollection); + } - // Act - Action act = () => + [Fact] + public void When_both_collections_do_not_have_the_same_number_of_elements_it_should_fail() { - using var _ = new AssertionScope(); - collection.Should().HaveSameCount(collection1, "because we want to test the behaviour with a null subject"); - }; + // Arrange + var firstCollection = new[] { 1, 2, 3 }; + var secondCollection = new[] { 4, 6 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => firstCollection.Should().HaveSameCount(secondCollection); - [Fact] - public void When_asserting_collections_to_have_same_count_against_an_other_null_collection_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int[] otherCollection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected firstCollection to have 2 item(s), but found 3."); + } - // Act - Action act = () => collection.Should().HaveSameCount(otherCollection); + [Fact] + public void When_comparing_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() + { + // Arrange + var firstCollection = new[] { 1, 2, 3 }; + var secondCollection = new[] { 4, 6 }; - // Assert - act.Should().Throw().WithMessage( - "Cannot verify count against a collection.*"); - } + // Act + Action act = () => firstCollection.Should().HaveSameCount(secondCollection, "we want to test the {0}", "reason"); - #endregion + // Assert + act.Should().Throw().WithMessage( + "Expected firstCollection to have 2 item(s) because we want to test the reason, but found 3."); + } - #region Not Have Same Count + [Fact] + public void When_asserting_collections_to_have_same_count_against_null_collection_it_should_throw() + { + // Arrange + int[] collection = null; + var collection1 = new[] { 1, 2, 3 }; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().HaveSameCount(collection1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_asserting_collections_to_have_same_count_against_an_other_null_collection_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + int[] otherCollection = null; - [Fact] - public void When_asserting_not_same_count_and_collections_have_different_number_elements_it_should_succeed() - { - // Arrange - var firstCollection = new[] { 1, 2, 3 }; - var secondCollection = new[] { 4, 6 }; + // Act + Action act = () => collection.Should().HaveSameCount(otherCollection); - // Act / Assert - firstCollection.Should().NotHaveSameCount(secondCollection); + // Assert + act.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } } - [Fact] - public void When_asserting_not_same_count_and_both_collections_have_the_same_number_elements_it_should_fail() + public class NotHaveSameCount { - // Arrange - var firstCollection = new[] { 1, 2, 3 }; - var secondCollection = new[] { 4, 5, 6 }; - - // Act - Action act = () => firstCollection.Should().NotHaveSameCount(secondCollection); - - // Assert - act.Should().Throw().WithMessage( - "Expected firstCollection to not have 3 item(s), but found 3."); - } + [Fact] + public void When_asserting_not_same_count_and_collections_have_different_number_elements_it_should_succeed() + { + // Arrange + var firstCollection = new[] { 1, 2, 3 }; + var secondCollection = new[] { 4, 6 }; - [Fact] - public void When_comparing_not_same_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() - { - // Arrange - var firstCollection = new[] { 1, 2, 3 }; - var secondCollection = new[] { 4, 5, 6 }; + // Act / Assert + firstCollection.Should().NotHaveSameCount(secondCollection); + } - // Act - Action act = () => firstCollection.Should().NotHaveSameCount(secondCollection, "we want to test the {0}", "reason"); + [Fact] + public void When_asserting_not_same_count_and_both_collections_have_the_same_number_elements_it_should_fail() + { + // Arrange + var firstCollection = new[] { 1, 2, 3 }; + var secondCollection = new[] { 4, 5, 6 }; - // Assert - act.Should().Throw().WithMessage( - "Expected firstCollection to not have 3 item(s) because we want to test the reason, but found 3."); - } + // Act + Action act = () => firstCollection.Should().NotHaveSameCount(secondCollection); - [Fact] - public void When_asserting_collections_to_not_have_same_count_against_null_collection_it_should_throw() - { - // Arrange - int[] collection = null; - var collection1 = new[] { 1, 2, 3 }; + // Assert + act.Should().Throw().WithMessage( + "Expected firstCollection to not have 3 item(s), but found 3."); + } - // Act - Action act = () => + [Fact] + public void When_comparing_not_same_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() { - using var _ = new AssertionScope(); - collection.Should().NotHaveSameCount(collection1, "because we want to test the behaviour with a null subject"); - }; + // Arrange + var firstCollection = new[] { 1, 2, 3 }; + var secondCollection = new[] { 4, 5, 6 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to not have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); - } - - [Fact] - public void When_asserting_collections_to_not_have_same_count_against_an_other_null_collection_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - int[] otherCollection = null; + // Act + Action act = () => firstCollection.Should().NotHaveSameCount(secondCollection, "we want to test the {0}", "reason"); - // Act - Action act = () => collection.Should().NotHaveSameCount(otherCollection); + // Assert + act.Should().Throw().WithMessage( + "Expected firstCollection to not have 3 item(s) because we want to test the reason, but found 3."); + } - // Assert - act.Should().Throw().WithMessage( - "Cannot verify count against a collection.*"); - } + [Fact] + public void When_asserting_collections_to_not_have_same_count_against_null_collection_it_should_throw() + { + // Arrange + int[] collection = null; + var collection1 = new[] { 1, 2, 3 }; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotHaveSameCount(collection1, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to not have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_asserting_collections_to_not_have_same_count_against_an_other_null_collection_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + int[] otherCollection = null; - [Fact] - public void When_asserting_collections_to_not_have_same_count_but_both_collections_references_the_same_object_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - var collection1 = collection; + // Act + Action act = () => collection.Should().NotHaveSameCount(otherCollection); - // Act - Action act = () => collection.Should().NotHaveSameCount(collection1, - "because we want to test the behaviour with same objects"); + // Assert + act.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } - // Assert - act.Should().Throw().WithMessage( - "*not have the same count*because we want to test the behaviour with same objects*but they both reference the same object."); + [Fact] + public void When_asserting_collections_to_not_have_same_count_but_both_collections_references_the_same_object_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var collection1 = collection; + + // Act + Action act = () => collection.Should().NotHaveSameCount(collection1, + "because we want to test the behaviour with same objects"); + + // Assert + act.Should().Throw().WithMessage( + "*not have the same count*because we want to test the behaviour with same objects*but they both reference the same object."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.IntersectWith.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.IntersectWith.cs index b3becf6ca9..a691b18fe3 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.IntersectWith.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.IntersectWith.cs @@ -11,118 +11,116 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Intersect With - - [Fact] - public void When_asserting_the_items_in_an_two_intersecting_collections_intersect_it_should_succeed() + public class IntersectWith { - // Arrange - var collection = new[] { 1, 2, 3 }; - var otherCollection = new[] { 3, 4, 5 }; - - // Act / Assert - collection.Should().IntersectWith(otherCollection); - } + [Fact] + public void When_asserting_the_items_in_an_two_intersecting_collections_intersect_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var otherCollection = new[] { 3, 4, 5 }; - [Fact] - public void When_asserting_the_items_in_an_two_non_intersecting_collections_intersect_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - var otherCollection = new[] { 4, 5 }; + // Act / Assert + collection.Should().IntersectWith(otherCollection); + } - // Act - Action action = () => collection.Should().IntersectWith(otherCollection, "they should share items"); + [Fact] + public void When_asserting_the_items_in_an_two_non_intersecting_collections_intersect_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var otherCollection = new[] { 4, 5 }; - // Assert - action.Should().Throw() - .WithMessage("Expected collection to intersect with {4, 5} because they should share items," + - " but {1, 2, 3} does not contain any shared items."); - } + // Act + Action action = () => collection.Should().IntersectWith(otherCollection, "they should share items"); - [Fact] - public void When_collection_is_null_then_intersect_with_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + action.Should().Throw() + .WithMessage("Expected collection to intersect with {4, 5} because they should share items," + + " but {1, 2, 3} does not contain any shared items."); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_intersect_with_should_fail() { - using var _ = new AssertionScope(); - collection.Should().IntersectWith(new[] { 4, 5 }, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected collection to intersect with {4, 5} *failure message*, but found ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().IntersectWith(new[] { 4, 5 }, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected collection to intersect with {4, 5} *failure message*, but found ."); + } } - #endregion - - #region Not Intersect With - - [Fact] - public void When_asserting_the_items_in_an_two_non_intersecting_collections_do_not_intersect_it_should_succeed() + public class NotIntersectWith { - // Arrange - var collection = new[] { 1, 2, 3 }; - var otherCollection = new[] { 4, 5 }; - - // Act / Assert - collection.Should().NotIntersectWith(otherCollection); - } + [Fact] + public void When_asserting_the_items_in_an_two_non_intersecting_collections_do_not_intersect_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var otherCollection = new[] { 4, 5 }; - [Fact] - public void When_asserting_the_items_in_an_two_intersecting_collections_do_not_intersect_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - var otherCollection = new[] { 2, 3, 4 }; + // Act / Assert + collection.Should().NotIntersectWith(otherCollection); + } - // Act - Action action = () => collection.Should().NotIntersectWith(otherCollection, "they should not share items"); + [Fact] + public void When_asserting_the_items_in_an_two_intersecting_collections_do_not_intersect_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var otherCollection = new[] { 2, 3, 4 }; - // Assert - action.Should().Throw() - .WithMessage("Did not expect collection to intersect with {2, 3, 4} because they should not share items," + - " but found the following shared items {2, 3}."); - } + // Act + Action action = () => collection.Should().NotIntersectWith(otherCollection, "they should not share items"); - [Fact] - public void When_asserting_collection_to_not_intersect_with_same_collection_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - var otherCollection = collection; + // Assert + action.Should().Throw() + .WithMessage("Did not expect collection to intersect with {2, 3, 4} because they should not share items," + + " but found the following shared items {2, 3}."); + } - // Act - Action act = () => collection.Should().NotIntersectWith(otherCollection, - "because we want to test the behaviour with same objects"); + [Fact] + public void When_asserting_collection_to_not_intersect_with_same_collection_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + var otherCollection = collection; - // Assert - act.Should().Throw().WithMessage( - "Did not expect*to intersect with*because we want to test the behaviour with same objects*but they both reference the same object."); - } + // Act + Action act = () => collection.Should().NotIntersectWith(otherCollection, + "because we want to test the behaviour with same objects"); - [Fact] - public void When_collection_is_null_then_not_intersect_with_should_fail() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw().WithMessage( + "Did not expect*to intersect with*because we want to test the behaviour with same objects*but they both reference the same object."); + } - // Act - Action act = () => + [Fact] + public void When_collection_is_null_then_not_intersect_with_should_fail() { - using var _ = new AssertionScope(); - collection.Should().NotIntersectWith(new[] { 4, 5 }, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to intersect with {4, 5} *failure message*, but found ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotIntersectWith(new[] { 4, 5 }, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to intersect with {4, 5} *failure message*, but found ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.NotContainNulls.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.NotContainNulls.cs index 325d20e53d..2e0823f6a3 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.NotContainNulls.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.NotContainNulls.cs @@ -11,163 +11,162 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Not Contain Nulls - - [Fact] - public void When_collection_does_not_contain_nulls_it_should_not_throw() + public class NotContainNulls { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_collection_does_not_contain_nulls_it_should_not_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; - // Act / Assert - collection.Should().NotContainNulls(); - } + // Act / Assert + collection.Should().NotContainNulls(); + } - [Fact] - public void When_collection_contains_nulls_that_are_unexpected_it_should_throw() - { - // Arrange - var collection = new[] { new object(), null }; + [Fact] + public void When_collection_contains_nulls_that_are_unexpected_it_should_throw() + { + // Arrange + var collection = new[] { new object(), null }; - // Act - Action act = () => collection.Should().NotContainNulls("because they are {0}", "evil"); + // Act + Action act = () => collection.Should().NotContainNulls("because they are {0}", "evil"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s because they are evil, but found one at index 1."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s because they are evil, but found one at index 1."); + } - [Fact] - public void When_collection_contains_multiple_nulls_that_are_unexpected_it_should_throw() - { - // Arrange - var collection = new[] { new object(), null, new object(), null }; + [Fact] + public void When_collection_contains_multiple_nulls_that_are_unexpected_it_should_throw() + { + // Arrange + var collection = new[] { new object(), null, new object(), null }; - // Act - Action act = () => collection.Should().NotContainNulls("because they are {0}", "evil"); + // Act + Action act = () => collection.Should().NotContainNulls("because they are {0}", "evil"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s*because they are evil*{1, 3}*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s*because they are evil*{1, 3}*"); + } - [Fact] - public void When_asserting_collection_to_not_contain_nulls_but_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + [Fact] + public void When_asserting_collection_to_not_contain_nulls_but_collection_is_null_it_should_throw() + { + // Arrange + int[] collection = null; - // Act - Action act = () => collection.Should().NotContainNulls("because we want to test the behaviour with a null subject"); + // Act + Action act = () => collection.Should().NotContainNulls("because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s because we want to test the behaviour with a null subject, but collection is ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s because we want to test the behaviour with a null subject, but collection is ."); + } - [Fact] - public void When_injecting_a_null_predicate_into_NotContainNulls_it_should_throw() - { - // Arrange - IEnumerable collection = new SomeClass[] { }; + [Fact] + public void When_injecting_a_null_predicate_into_NotContainNulls_it_should_throw() + { + // Arrange + IEnumerable collection = new SomeClass[] { }; - // Act - Action act = () => collection.Should().NotContainNulls(predicate: null); + // Act + Action act = () => collection.Should().NotContainNulls(predicate: null); - // Assert - act.Should().ThrowExactly() - .WithParameterName("predicate"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("predicate"); + } - [Fact] - public void When_collection_does_not_contain_nulls_with_a_predicate_it_should_not_throw() - { - // Arrange - IEnumerable collection = new[] + [Fact] + public void When_collection_does_not_contain_nulls_with_a_predicate_it_should_not_throw() { - new SomeClass { Text = "one" }, - new SomeClass { Text = "two" }, - new SomeClass { Text = "three" } - }; - - // Act / Assert - collection.Should().NotContainNulls(e => e.Text); - } - - [Fact] - public void When_collection_contains_nulls_that_are_unexpected_with_a_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] + // Arrange + IEnumerable collection = new[] + { + new SomeClass { Text = "one" }, + new SomeClass { Text = "two" }, + new SomeClass { Text = "three" } + }; + + // Act / Assert + collection.Should().NotContainNulls(e => e.Text); + } + + [Fact] + public void When_collection_contains_nulls_that_are_unexpected_with_a_predicate_it_should_throw() { - new SomeClass { Text = "" }, - new SomeClass { Text = null } - }; - - // Act - Action act = () => collection.Should().NotContainNulls(e => e.Text, "because they are {0}", "evil"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s*on e.Text*because they are evil*Text = *"); - } - - [Fact] - public void When_collection_contains_multiple_nulls_that_are_unexpected_with_a_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] + // Arrange + IEnumerable collection = new[] + { + new SomeClass { Text = "" }, + new SomeClass { Text = null } + }; + + // Act + Action act = () => collection.Should().NotContainNulls(e => e.Text, "because they are {0}", "evil"); + + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s*on e.Text*because they are evil*Text = *"); + } + + [Fact] + public void When_collection_contains_multiple_nulls_that_are_unexpected_with_a_predicate_it_should_throw() { - new SomeClass { Text = "" }, - new SomeClass { Text = null }, - new SomeClass { Text = "" }, - new SomeClass { Text = null } - }; - - // Act - Action act = () => collection.Should().NotContainNulls(e => e.Text, "because they are {0}", "evil"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s*on e.Text*because they are evil*Text = *Text = *"); - } - - [Fact] - public void When_asserting_collection_to_not_contain_nulls_but_collection_is_null_it_should_fail() - { - // Arrange - SomeClass[] collection = null; - - // Act - Action act = () => + // Arrange + IEnumerable collection = new[] + { + new SomeClass { Text = "" }, + new SomeClass { Text = null }, + new SomeClass { Text = "" }, + new SomeClass { Text = null } + }; + + // Act + Action act = () => collection.Should().NotContainNulls(e => e.Text, "because they are {0}", "evil"); + + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s*on e.Text*because they are evil*Text = *Text = *"); + } + + [Fact] + public void When_asserting_collection_to_not_contain_nulls_but_collection_is_null_it_should_fail() { - using var _ = new AssertionScope(); - collection.Should().NotContainNulls("we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s *failure message*, but collection is ."); - } - - [Fact] - public void When_asserting_collection_to_not_contain_nulls_with_predicate_but_collection_is_null_it_should_throw() - { - // Arrange - IEnumerable collection = null; - - // Act - Action act = () => + // Arrange + SomeClass[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContainNulls("we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s *failure message*, but collection is ."); + } + + [Fact] + public void When_asserting_collection_to_not_contain_nulls_with_predicate_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().NotContainNulls(e => e.Text, "because we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection not to contain s because we want to test the behaviour with a null subject, but collection is ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotContainNulls(e => e.Text, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection not to contain s because we want to test the behaviour with a null subject, but collection is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyContain.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyContain.cs index 889900a17d..736e0f73d4 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyContain.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyContain.cs @@ -12,97 +12,96 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Only Contain - - [Fact] - public void When_a_collection_does_not_contain_the_unexpected_items_it_should_not_be_enumerated_twice() + public class OnlyContain { - // Arrange - var collection = new OneTimeEnumerable(1, 2, 3); + [Fact] + public void When_a_collection_does_not_contain_the_unexpected_items_it_should_not_be_enumerated_twice() + { + // Arrange + var collection = new OneTimeEnumerable(1, 2, 3); - // Act - Action act = () => collection.Should().OnlyContain(i => i > 3); + // Act + Action act = () => collection.Should().OnlyContain(i => i > 3); - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain only items matching*"); - } - - [Fact] - public void When_injecting_a_null_predicate_into_OnlyContain_it_should_throw() - { - // Arrange - IEnumerable collection = new int[] { }; + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain only items matching*"); + } - // Act - Action act = () => collection.Should().OnlyContain(predicate: null); + [Fact] + public void When_injecting_a_null_predicate_into_OnlyContain_it_should_throw() + { + // Arrange + IEnumerable collection = new int[] { }; - // Assert - act.Should().ThrowExactly() - .WithParameterName("predicate"); - } + // Act + Action act = () => collection.Should().OnlyContain(predicate: null); - [Fact] - public void When_a_collection_contains_items_not_matching_a_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] { 2, 12, 3, 11, 2 }; + // Assert + act.Should().ThrowExactly() + .WithParameterName("predicate"); + } - // Act - Action act = () => collection.Should().OnlyContain(i => i <= 10, "10 is the maximum"); + [Fact] + public void When_a_collection_contains_items_not_matching_a_predicate_it_should_throw() + { + // Arrange + IEnumerable collection = new[] { 2, 12, 3, 11, 2 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain only items matching (i <= 10) because 10 is the maximum, but {12, 11} do(es) not match."); - } + // Act + Action act = () => collection.Should().OnlyContain(i => i <= 10, "10 is the maximum"); - [Fact] - public void When_a_collection_is_empty_and_should_contain_only_items_matching_a_predicate_it_should_throw() - { - // Arrange - IEnumerable strings = Enumerable.Empty(); + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain only items matching (i <= 10) because 10 is the maximum, but {12, 11} do(es) not match."); + } - // Act - Action act = () => strings.Should().OnlyContain(e => e.Length > 0); + [Fact] + public void When_a_collection_is_empty_and_should_contain_only_items_matching_a_predicate_it_should_throw() + { + // Arrange + IEnumerable strings = Enumerable.Empty(); - // Assert - act.Should().Throw() - .WithMessage("Expected strings to contain only items matching (e.Length > 0), but the collection is empty."); - } + // Act + Action act = () => strings.Should().OnlyContain(e => e.Length > 0); - [Fact] - public void When_a_collection_contains_only_items_matching_a_predicate_it_should_not_throw() - { - // Arrange - IEnumerable collection = new[] { 2, 9, 3, 8, 2 }; + // Assert + act.Should().Throw() + .WithMessage("Expected strings to contain only items matching (e.Length > 0), but the collection is empty."); + } - // Act - Action act = () => collection.Should().OnlyContain(i => i <= 10); + [Fact] + public void When_a_collection_contains_only_items_matching_a_predicate_it_should_not_throw() + { + // Arrange + IEnumerable collection = new[] { 2, 9, 3, 8, 2 }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().OnlyContain(i => i <= 10); - [Fact] - public void When_a_collection_is_null_then_only_contains_should_fail() - { - // Arrange - int[] collection = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => + [Fact] + public void When_a_collection_is_null_then_only_contains_should_fail() { - using var _ = new AssertionScope(); - collection.Should().OnlyContain(i => i <= 10, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage( - "Expected collection to contain only items matching (i <= 10) *failure message*," + - " but the collection is ."); + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().OnlyContain(i => i <= 10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage( + "Expected collection to contain only items matching (i <= 10) *failure message*," + + " but the collection is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyHaveUniqueItems.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyHaveUniqueItems.cs index b6257b4f08..fec8eb5c30 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyHaveUniqueItems.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.OnlyHaveUniqueItems.cs @@ -11,153 +11,152 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Only Have Unique Items - - [Fact] - public void Should_succeed_when_asserting_collection_with_unique_items_contains_only_unique_items() + public class OnlyHaveUniqueItems { - // Arrange - var collection = new[] { 1, 2, 3, 4 }; - - // Act / Assert - collection.Should().OnlyHaveUniqueItems(); - } + [Fact] + public void Should_succeed_when_asserting_collection_with_unique_items_contains_only_unique_items() + { + // Arrange + var collection = new[] { 1, 2, 3, 4 }; - [Fact] - public void When_a_collection_contains_duplicate_items_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3, 3 }; + // Act / Assert + collection.Should().OnlyHaveUniqueItems(); + } - // Act - Action act = () => collection.Should().OnlyHaveUniqueItems("{0} don't like {1}", "we", "duplicates"); + [Fact] + public void When_a_collection_contains_duplicate_items_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to only have unique items because we don't like duplicates, but item 3 is not unique."); - } + // Act + Action act = () => collection.Should().OnlyHaveUniqueItems("{0} don't like {1}", "we", "duplicates"); - [Fact] - public void When_a_collection_contains_multiple_duplicate_items_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 2, 3, 3 }; + // Assert + act.Should().Throw().WithMessage( + "Expected collection to only have unique items because we don't like duplicates, but item 3 is not unique."); + } - // Act - Action act = () => collection.Should().OnlyHaveUniqueItems("{0} don't like {1}", "we", "duplicates"); + [Fact] + public void When_a_collection_contains_multiple_duplicate_items_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 2, 3, 3 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to only have unique items because we don't like duplicates, but items {2, 3} are not unique."); - } + // Act + Action act = () => collection.Should().OnlyHaveUniqueItems("{0} don't like {1}", "we", "duplicates"); - [Fact] - public void When_asserting_collection_to_only_have_unique_items_but_collection_is_null_it_should_throw() - { - // Arrange - int[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected collection to only have unique items because we don't like duplicates, but items {2, 3} are not unique."); + } - // Act - Action act = () => + [Fact] + public void When_asserting_collection_to_only_have_unique_items_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().OnlyHaveUniqueItems("because we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to only have unique items because we want to test the behaviour with a null subject, but found ."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_OnlyHaveUniqueItems_it_should_throw() - { - // Arrange - IEnumerable collection = new SomeClass[] { }; + // Arrange + int[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().OnlyHaveUniqueItems("because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to only have unique items because we want to test the behaviour with a null subject, but found ."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_OnlyHaveUniqueItems_it_should_throw() + { + // Arrange + IEnumerable collection = new SomeClass[] { }; - // Act - Action act = () => collection.Should().OnlyHaveUniqueItems(predicate: null); + // Act + Action act = () => collection.Should().OnlyHaveUniqueItems(predicate: null); - // Assert - act.Should().ThrowExactly() - .WithParameterName("predicate"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("predicate"); + } - [Fact] - public void Should_succeed_when_asserting_with_a_predicate_a_collection_with_unique_items_contains_only_unique_items() - { - // Arrange - IEnumerable collection = new[] + [Fact] + public void Should_succeed_when_asserting_with_a_predicate_a_collection_with_unique_items_contains_only_unique_items() { - new SomeClass { Text = "one" }, - new SomeClass { Text = "two" }, - new SomeClass { Text = "three" }, - new SomeClass { Text = "four" } - }; - - // Act / Assert - collection.Should().OnlyHaveUniqueItems(e => e.Text); - } - - [Fact] - public void When_a_collection_contains_duplicate_items_with_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] + // Arrange + IEnumerable collection = new[] + { + new SomeClass { Text = "one" }, + new SomeClass { Text = "two" }, + new SomeClass { Text = "three" }, + new SomeClass { Text = "four" } + }; + + // Act / Assert + collection.Should().OnlyHaveUniqueItems(e => e.Text); + } + + [Fact] + public void When_a_collection_contains_duplicate_items_with_predicate_it_should_throw() { - new SomeClass { Text = "one" }, - new SomeClass { Text = "two" }, - new SomeClass { Text = "three" }, - new SomeClass { Text = "three" } - }; - - // Act - Action act = () => collection.Should().OnlyHaveUniqueItems(e => e.Text, "{0} don't like {1}", "we", "duplicates"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to only have unique items*on e.Text*because we don't like duplicates, but item*three*is not unique."); - } - - [Fact] - public void When_a_collection_contains_multiple_duplicate_items_with_a_predicate_it_should_throw() - { - // Arrange - IEnumerable collection = new[] + // Arrange + IEnumerable collection = new[] + { + new SomeClass { Text = "one" }, + new SomeClass { Text = "two" }, + new SomeClass { Text = "three" }, + new SomeClass { Text = "three" } + }; + + // Act + Action act = () => collection.Should().OnlyHaveUniqueItems(e => e.Text, "{0} don't like {1}", "we", "duplicates"); + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to only have unique items*on e.Text*because we don't like duplicates, but item*three*is not unique."); + } + + [Fact] + public void When_a_collection_contains_multiple_duplicate_items_with_a_predicate_it_should_throw() { - new SomeClass { Text = "one" }, - new SomeClass { Text = "two" }, - new SomeClass { Text = "two" }, - new SomeClass { Text = "three" }, - new SomeClass { Text = "three" } - }; - - // Act - Action act = () => collection.Should().OnlyHaveUniqueItems(e => e.Text, "{0} don't like {1}", "we", "duplicates"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to only have unique items*on e.Text*because we don't like duplicates, but items*two*two*three*three*are not unique."); - } - - [Fact] - public void When_asserting_with_a_predicate_a_collection_to_only_have_unique_items_but_collection_is_null_it_should_throw() - { - // Arrange - IEnumerable collection = null; - - // Act - Action act = () => + // Arrange + IEnumerable collection = new[] + { + new SomeClass { Text = "one" }, + new SomeClass { Text = "two" }, + new SomeClass { Text = "two" }, + new SomeClass { Text = "three" }, + new SomeClass { Text = "three" } + }; + + // Act + Action act = () => collection.Should().OnlyHaveUniqueItems(e => e.Text, "{0} don't like {1}", "we", "duplicates"); + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to only have unique items*on e.Text*because we don't like duplicates, but items*two*two*three*three*are not unique."); + } + + [Fact] + public void When_asserting_with_a_predicate_a_collection_to_only_have_unique_items_but_collection_is_null_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().OnlyHaveUniqueItems(e => e.Text, "because we want to test the behaviour with a null subject"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to only have unique items because we want to test the behaviour with a null subject, but found ."); + // Arrange + IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().OnlyHaveUniqueItems(e => e.Text, "because we want to test the behaviour with a null subject"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to only have unique items because we want to test the behaviour with a null subject, but found ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs index 6e8b70e7ba..516902ff65 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs @@ -13,179 +13,203 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - [Fact] - public void When_collection_element_at_each_position_matches_predicate_at_same_position_should_not_throw() + public class Satisfy { - // Arrange - var collection = new int[] { 1, 2, 3 }; + [Fact] + public void When_collection_element_at_each_position_matches_predicate_at_same_position_should_not_throw() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; - // Act - Action act = () => collection.Should().Satisfy( - element => element == 1, - element => element == 2, - element => element == 3); + // Act + Action act = () => collection.Should().Satisfy( + element => element == 1, + element => element == 2, + element => element == 3); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_collection_element_at_each_position_matches_predicate_at_reverse_position_should_not_throw() - { - // Arrange - var collection = new int[] { 1, 2, 3 }; + [Fact] + public void When_collection_element_at_each_position_matches_predicate_at_reverse_position_should_not_throw() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; + + // Act + Action act = () => collection.Should().Satisfy( + element => element == 3, + element => element == 2, + element => element == 1); - // Act - Action act = () => collection.Should().Satisfy( - element => element == 3, - element => element == 2, - element => element == 1); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_one_element_does_not_have_matching_predicate_Satisfy_should_throw() + { + // Arrange + var collection = new int[] { 1, 2 }; - [Fact] - public void When_one_element_does_not_have_matching_predicate_Satisfy_should_throw() - { - // Arrange - var collection = new int[] { 1, 2 }; - - // Act - Action act = () => collection.Should().Satisfy( - element => element == 3, - element => element == 1, - element => element == 2); - - // Assert - act.Should().Throw().WithMessage( -@"Expected collection to satisfy all predicates, but: + // Act + Action act = () => collection.Should().Satisfy( + element => element == 3, + element => element == 1, + element => element == 2); + + // Assert + act.Should().Throw().WithMessage( + @"Expected collection to satisfy all predicates, but: *The following predicates did not have matching elements: *(element == 3)"); - } + } - [Fact] - public void When_some_predicates_have_multiple_matching_elements_and_most_restricitve_predicates_are_last_should_not_throw() - { - // Arrange - var collection = new int[] { 1, 2, 3, 4 }; - - // Act - Action act = () => collection.Should().Satisfy( - element => element == 1 || element == 2 || element == 3 || element == 4, - element => element == 1 || element == 2 || element == 3, - element => element == 1 || element == 2, - element => element == 1); - - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_some_predicates_have_multiple_matching_elements_and_most_restricitve_predicates_are_last_should_not_throw() + { + // Arrange + var collection = new int[] { 1, 2, 3, 4 }; + + // Act + Action act = () => collection.Should().Satisfy( + element => element == 1 || element == 2 || element == 3 || element == 4, + element => element == 1 || element == 2 || element == 3, + element => element == 1 || element == 2, + element => element == 1); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_some_predicates_have_multiple_matching_elements_and_most_restricitve_predicates_are_first_should_not_throw() + { + // Arrange + var collection = new int[] { 1, 2, 3, 4 }; - [Fact] - public void When_some_predicates_have_multiple_matching_elements_and_most_restricitve_predicates_are_first_should_not_throw() - { - // Arrange - var collection = new int[] { 1, 2, 3, 4 }; - - // Act - Action act = () => collection.Should().Satisfy( - element => element == 1, - element => element == 1 || element == 2, - element => element == 1 || element == 2 || element == 3, - element => element == 1 || element == 2 || element == 3 || element == 4); - - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().Satisfy( + element => element == 1, + element => element == 1 || element == 2, + element => element == 1 || element == 2 || element == 3, + element => element == 1 || element == 2 || element == 3 || element == 4); - [Fact] - public void When_second_predicate_matches_first_and_last_element_and_solution_exists_should_not_throw() - { - // Arrange - var collection = new int[] { 1, 2, 3 }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().Satisfy( - element => element == 1, - element => element == 1 || element == 3, - element => element == 2); + [Fact] + public void When_second_predicate_matches_first_and_last_element_and_solution_exists_should_not_throw() + { + // Arrange + var collection = new int[] { 1, 2, 3 }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().Satisfy( + element => element == 1, + element => element == 1 || element == 3, + element => element == 2); - [Fact] - public void When_assertion_fails_then_failure_message_must_contain_predicates_without_matching_elements_and_elements_without_matching_predicates() - { - // Arrange - IEnumerable collection = new[] + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_assertion_fails_then_failure_message_must_contain_predicates_without_matching_elements_and_elements_without_matching_predicates() { - new SomeClass { Text = "one", Number = 1 }, - new SomeClass { Text = "two", Number = 3 }, - new SomeClass { Text = "three", Number = 3 }, - new SomeClass { Text = "four", Number = 4 }, - }; - - // Act - Action act = () => collection.Should().Satisfy( - new Expression>[] + // Arrange + IEnumerable collection = new[] { + new SomeClass { Text = "one", Number = 1 }, + new SomeClass { Text = "two", Number = 3 }, + new SomeClass { Text = "three", Number = 3 }, + new SomeClass { Text = "four", Number = 4 }, + }; + + // Act + Action act = () => collection.Should().Satisfy( + new Expression>[] + { element => element.Text == "four" && element.Number == 4, element => element.Text == "two" && element.Number == 2, - }, - because: "we want to test formatting ({0})", - becauseArgs: "args"); + }, + because: "we want to test formatting ({0})", + becauseArgs: "args"); - // Assert - act.Should().Throw().WithMessage( -@"Expected collection to satisfy all predicates because we want to test formatting (args), but: + // Assert + act.Should().Throw().WithMessage( + @"Expected collection to satisfy all predicates because we want to test formatting (args), but: *The following predicates did not have matching elements: *(element.Text == ""two"") AndAlso (element.Number == 2) *The following elements did not match any predicate: *Index: 0, Element:*FluentAssertions.Specs.Collections.CollectionAssertionSpecs+SomeClass*{*Number = 1*Text = ""one""*} *Index: 1, Element:*FluentAssertions.Specs.Collections.CollectionAssertionSpecs+SomeClass*{*Number = 3*Text = ""two""*} *Index: 2, Element:*FluentAssertions.Specs.Collections.CollectionAssertionSpecs+SomeClass*{*Number = 3*Text = ""three""*}"); - } + } - [Fact] - public void When_Satisfy_asserting_against_null_inspectors_it_should_throw_with_clear_explanation() - { - // Arrange - IEnumerable collection = new[] { 1, 2 }; + [Fact] + public void When_Satisfy_asserting_against_null_inspectors_it_should_throw_with_clear_explanation() + { + // Arrange + IEnumerable collection = new[] { 1, 2 }; - // Act - Action act = () => collection.Should().Satisfy(null); + // Act + Action act = () => collection.Should().Satisfy(null); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify against a collection of predicates*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot verify against a collection of predicates*"); + } - [Fact] - public void When_asserting_against_empty_inspectors_should_throw_with_clear_explanation() - { - // Arrange - IEnumerable collection = new[] { 1, 2 }; + [Fact] + public void When_asserting_against_empty_inspectors_should_throw_with_clear_explanation() + { + // Arrange + IEnumerable collection = new[] { 1, 2 }; - // Act - Action act = () => collection.Should().Satisfy(); + // Act + Action act = () => collection.Should().Satisfy(); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify against an empty collection of predicates*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot verify against an empty collection of predicates*"); + } - [Fact] - public void When_asserting_collection_which_is_null_should_throw() - { - // Arrange - IEnumerable collection = null; + [Fact] + public void When_asserting_collection_which_is_null_should_throw() + { + // Arrange + IEnumerable collection = null; - // Act - Action act = () => + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().Satisfy( + new Expression>[] + { + element => element == 1, + element => element == 2, + }, + because: "we want to test the failure message ({0})", + becauseArgs: "args"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to satisfy all predicates because we want to test the failure message (args), but collection is ."); + } + + [Fact] + public void When_asserting_collection_which_is_empty_should_throw() { - using var _ = new AssertionScope(); - collection.Should().Satisfy( + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().Satisfy( new Expression>[] { element => element == 1, @@ -193,52 +217,31 @@ public void When_asserting_collection_which_is_null_should_throw() }, because: "we want to test the failure message ({0})", becauseArgs: "args"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to satisfy all predicates because we want to test the failure message (args), but collection is ."); - } - [Fact] - public void When_asserting_collection_which_is_empty_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); + // Assert + act.Should().Throw().WithMessage( + "Expected collection to satisfy all predicates because we want to test the failure message (args), but collection is empty."); + } - // Act - Action act = () => collection.Should().Satisfy( - new Expression>[] - { - element => element == 1, - element => element == 2, - }, - because: "we want to test the failure message ({0})", - becauseArgs: "args"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to satisfy all predicates because we want to test the failure message (args), but collection is empty."); - } - - [Fact] - public void When_elements_are_integers_assertion_fails_then_failure_message_must_be_readable() - { - // Arrange - var collection = new List { 1, 2, 3 }; + [Fact] + public void When_elements_are_integers_assertion_fails_then_failure_message_must_be_readable() + { + // Arrange + var collection = new List { 1, 2, 3 }; - // Act - Action act = () => collection.Should().Satisfy( - element => element == 2); + // Act + Action act = () => collection.Should().Satisfy( + element => element == 2); - // Assert - act.Should().Throw().WithMessage( -@"Expected collection to satisfy all predicates, but: + // Assert + act.Should().Throw().WithMessage( + @"Expected collection to satisfy all predicates, but: *The following elements did not match any predicate: *Index: 0, Element: 1 *Index: 2, Element: 3"); + } } - + private class SomeClass { public string Text { get; set; } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.SatisfyRespectively.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.SatisfyRespectively.cs index a741187fe8..3338e4781c 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.SatisfyRespectively.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.SatisfyRespectively.cs @@ -12,138 +12,104 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Satisfy Respectively - - [Fact] - public void When_collection_asserting_against_null_inspectors_it_should_throw_with_clear_explanation() + public class SatisfyRespectively { - // Arrange - IEnumerable collection = new[] { 1, 2 }; - - // Act - Action act = () => collection.Should().SatisfyRespectively(null); - - // Assert - act.Should().Throw().WithMessage( - "Cannot verify against a collection of inspectors*"); - } - - [Fact] - public void When_collection_asserting_against_empty_inspectors_it_should_throw_with_clear_explanation() - { - // Arrange - IEnumerable collection = new[] { 1, 2 }; - - // Act - Action act = () => collection.Should().SatisfyRespectively(); + [Fact] + public void When_collection_asserting_against_null_inspectors_it_should_throw_with_clear_explanation() + { + // Arrange + IEnumerable collection = new[] { 1, 2 }; - // Assert - act.Should().Throw().WithMessage( - "Cannot verify against an empty collection of inspectors*"); - } + // Act + Action act = () => collection.Should().SatisfyRespectively(null); - [Fact] - public void When_collection_which_is_asserting_against_inspectors_is_null_it_should_throw() - { - // Arrange - IEnumerable collection = null; + // Assert + act.Should().Throw().WithMessage( + "Cannot verify against a collection of inspectors*"); + } - // Act - Action act = () => + [Fact] + public void When_collection_asserting_against_empty_inspectors_it_should_throw_with_clear_explanation() { - using var _ = new AssertionScope(); - collection.Should().SatisfyRespectively( - new Action[] { x => x.Should().Be(1) }, "because we want to test the failure {0}", "message"); - }; + // Arrange + IEnumerable collection = new[] { 1, 2 }; - // Assert - act.Should().Throw().WithMessage( - "Expected collection to satisfy all inspectors because we want to test the failure message, but collection is ."); - } + // Act + Action act = () => collection.Should().SatisfyRespectively(); - [Fact] - public void When_collection_which_is_asserting_against_inspectors_is_empty_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().SatisfyRespectively(new Action[] { x => x.Should().Be(1) }, - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected collection to satisfy all inspectors because we want to test the failure message, but collection is empty."); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot verify against an empty collection of inspectors*"); + } - [Fact] - public void When_asserting_collection_satisfies_all_inspectors_it_should_succeed() - { - // Arrange - var collection = new[] { new Customer { Age = 21, Name = "John" }, new Customer { Age = 22, Name = "Jane" } }; + [Fact] + public void When_collection_which_is_asserting_against_inspectors_is_null_it_should_throw() + { + // Arrange + IEnumerable collection = null; - // Act / Assert - collection.Should().SatisfyRespectively( - value => - { - value.Age.Should().Be(21); - value.Name.Should().Be("John"); - }, - value => + // Act + Action act = () => { - value.Age.Should().Be(22); - value.Name.Should().Be("Jane"); - }); - } - - private class Customer - { - private string PrivateProperty { get; set; } - - protected string ProtectedProperty { get; set; } - - public string Name { get; set; } - - public int Age { get; set; } + using var _ = new AssertionScope(); + collection.Should().SatisfyRespectively( + new Action[] { x => x.Should().Be(1) }, "because we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to satisfy all inspectors because we want to test the failure message, but collection is ."); + } - public DateTime Birthdate { get; set; } + [Fact] + public void When_collection_which_is_asserting_against_inspectors_is_empty_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); - public long Id { get; set; } + // Act + Action act = () => collection.Should().SatisfyRespectively(new Action[] { x => x.Should().Be(1) }, + "because we want to test the failure {0}", "message"); - public void SetProtected(string value) - { - ProtectedProperty = value; + // Assert + act.Should().Throw().WithMessage( + "Expected collection to satisfy all inspectors because we want to test the failure message, but collection is empty."); } - public Customer() + [Fact] + public void When_asserting_collection_satisfies_all_inspectors_it_should_succeed() { - } + // Arrange + var collection = new[] { new Customer { Age = 21, Name = "John" }, new Customer { Age = 22, Name = "Jane" } }; - public Customer(string privateProperty) - { - PrivateProperty = privateProperty; + // Act / Assert + collection.Should().SatisfyRespectively( + value => + { + value.Age.Should().Be(21); + value.Name.Should().Be("John"); + }, + value => + { + value.Age.Should().Be(22); + value.Name.Should().Be("Jane"); + }); } - } - - private class CustomerWithItems : Customer - { - public int[] Items { get; set; } - } - [Fact] - public void When_asserting_collection_does_not_satisfy_any_inspector_it_should_throw() - { - // Arrange - var customers = new[] + [Fact] + public void When_asserting_collection_does_not_satisfy_any_inspector_it_should_throw() { - new CustomerWithItems { Age = 21, Items = new[] { 1, 2 } }, - new CustomerWithItems { Age = 22, Items = new[] { 3 } } - }; - - // Act - Action act = () => customers.Should().SatisfyRespectively( - new Action[] + // Arrange + var customers = new[] { + new CustomerWithItems { Age = 21, Items = new[] { 1, 2 } }, + new CustomerWithItems { Age = 22, Items = new[] { 3 } } + }; + + // Act + Action act = () => customers.Should().SatisfyRespectively( + new Action[] + { customer => { customer.Age.Should().BeLessThan(21); @@ -156,11 +122,11 @@ public void When_asserting_collection_does_not_satisfy_any_inspector_it_should_t customer.Age.Should().BeLessThan(22); customer.Items.Should().SatisfyRespectively(item => item.Should().Be(2)); } - }, "because we want to test {0}", "nested assertions"); + }, "because we want to test {0}", "nested assertions"); - // Assert - act.Should().Throw().WithMessage( - @"Expected customers to satisfy all inspectors because we want to test nested assertions, but some inspectors are not satisfied: + // Assert + act.Should().Throw().WithMessage( + @"Expected customers to satisfy all inspectors because we want to test nested assertions, but some inspectors are not satisfied: *At index 0: *Expected customer.Age to be less than 21, but found 21 *Expected customer.Items to satisfy all inspectors, but some inspectors are not satisfied: @@ -173,52 +139,85 @@ public void When_asserting_collection_does_not_satisfy_any_inspector_it_should_t *Expected customer.Items to satisfy all inspectors, but some inspectors are not satisfied: *At index 0: *Expected item to be 2, but found 3" - ); - } + ); + } - [Fact] - public void When_inspector_message_is_not_reformatable_it_should_not_throw() - { - // Arrange - byte[][] subject = { new byte[] { 1 } }; + [Fact] + public void When_inspector_message_is_not_reformatable_it_should_not_throw() + { + // Arrange + byte[][] subject = { new byte[] { 1 } }; - // Act - Action act = () => subject.Should().SatisfyRespectively(e => e.Should().BeEquivalentTo(new byte[] { 2, 3, 4 })); + // Act + Action act = () => subject.Should().SatisfyRespectively(e => e.Should().BeEquivalentTo(new byte[] { 2, 3, 4 })); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_inspectors_count_does_not_equal_asserting_collection_length_it_should_throw_with_a_useful_message() - { - // Arrange - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_inspectors_count_does_not_equal_asserting_collection_length_it_should_throw_with_a_useful_message() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + + // Act + Action act = () => collection.Should().SatisfyRespectively( + new Action[] { value => value.Should().Be(1), value => value.Should().Be(2) }, + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected collection to contain exactly 2 items*we want to test the failure message*, but it contains 3 items"); + } - // Act - Action act = () => collection.Should().SatisfyRespectively( - new Action[] { value => value.Should().Be(1), value => value.Should().Be(2) }, - "because we want to test the failure {0}", "message"); + [Fact] + public void When_inspectors_count_does_not_equal_asserting_collection_length_it_should_fail_with_a_useful_message() + { + // Arrange + var collection = new int[0]; + + // Act + Action act = () => collection.Should().SatisfyRespectively( + new Action[] { value => value.Should().Be(1), }, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected collection to contain exactly 2 items*we want to test the failure message*, but it contains 3 items"); + // Assert + act.Should().Throw().WithMessage("*because we want to test the failure*"); + } } - [Fact] - public void When_inspectors_count_does_not_equal_asserting_collection_length_it_should_fail_with_a_useful_message() + private class Customer { - // Arrange - var collection = new int[0]; + private string PrivateProperty { get; set; } + + protected string ProtectedProperty { get; set; } + + public string Name { get; set; } + + public int Age { get; set; } + + public DateTime Birthdate { get; set; } - // Act - Action act = () => collection.Should().SatisfyRespectively( - new Action[] { value => value.Should().Be(1), }, "because we want to test the failure {0}", "message"); + public long Id { get; set; } + + public void SetProtected(string value) + { + ProtectedProperty = value; + } - // Assert - act.Should().Throw().WithMessage("*because we want to test the failure*"); + public Customer() + { + } + + public Customer(string privateProperty) + { + PrivateProperty = privateProperty; + } } - #endregion + private class CustomerWithItems : Customer + { + public int[] Items { get; set; } + } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.StartWith.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.StartWith.cs index 00e1ca5b99..31091acd88 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.StartWith.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.StartWith.cs @@ -11,214 +11,213 @@ namespace FluentAssertions.Specs.Collections /// public partial class CollectionAssertionSpecs { - #region Start With - - [Fact] - public void When_collection_does_not_start_with_a_specific_element_it_should_throw() + public class StartWith { - // Arrange - var collection = new[] { "john", "jane", "mike" }; + [Fact] + public void When_collection_does_not_start_with_a_specific_element_it_should_throw() + { + // Arrange + var collection = new[] { "john", "jane", "mike" }; - // Act - Action act = () => collection.Should().StartWith("ryan", "of some reason"); + // Act + Action act = () => collection.Should().StartWith("ryan", "of some reason"); - // Assert - act.Should().Throw().WithMessage( - "Expected*start*ryan*because of some reason*but*john*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected*start*ryan*because of some reason*but*john*"); + } - [Fact] - public void When_collection_does_not_start_with_a_null_sequence_it_should_throw() - { - // Arrange - var collection = new[] { "john" }; + [Fact] + public void When_collection_does_not_start_with_a_null_sequence_it_should_throw() + { + // Arrange + var collection = new[] { "john" }; - // Act - Action act = () => collection.Should().StartWith((IEnumerable)null); + // Act + Action act = () => collection.Should().StartWith((IEnumerable)null); - // Assert - act.Should().Throw() - .Which.ParamName.Should().Be("expectation"); - } + // Assert + act.Should().Throw() + .Which.ParamName.Should().Be("expectation"); + } - [Fact] - public void When_collection_does_not_start_with_a_null_sequence_using_a_comparer_it_should_throw() - { - // Arrange - var collection = new[] { "john" }; + [Fact] + public void When_collection_does_not_start_with_a_null_sequence_using_a_comparer_it_should_throw() + { + // Arrange + var collection = new[] { "john" }; - // Act - Action act = () => collection.Should().StartWith((IEnumerable)null, (_, _) => true); + // Act + Action act = () => collection.Should().StartWith((IEnumerable)null, (_, _) => true); - // Assert - act.Should().Throw() - .Which.ParamName.Should().Be("expectation"); - } + // Assert + act.Should().Throw() + .Which.ParamName.Should().Be("expectation"); + } - [Fact] - public void When_collection_does_not_start_with_a_specific_element_in_a_sequence_it_should_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + [Fact] + public void When_collection_does_not_start_with_a_specific_element_in_a_sequence_it_should_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Act - Action act = () => collection.Should().StartWith(new[] { "john", "ryan", "jane" }, "of some reason"); + // Act + Action act = () => collection.Should().StartWith(new[] { "john", "ryan", "jane" }, "of some reason"); - // Assert - act.Should().Throw().WithMessage( - "Expected*start*ryan*because of some reason*but*differs at index 1*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected*start*ryan*because of some reason*but*differs at index 1*"); + } - [Fact] - public void When_collection_does_not_start_with_a_specific_element_in_a_sequence_using_custom_equality_comparison_it_should_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + [Fact] + public void When_collection_does_not_start_with_a_specific_element_in_a_sequence_using_custom_equality_comparison_it_should_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Act - Action act = () => collection.Should().StartWith(new[] { "john", "ryan", "jane" }, (s1, s2) => string.Equals(s1, s2, StringComparison.Ordinal), "of some reason"); + // Act + Action act = () => collection.Should().StartWith(new[] { "john", "ryan", "jane" }, (s1, s2) => string.Equals(s1, s2, StringComparison.Ordinal), "of some reason"); - // Assert - act.Should().Throw().WithMessage( - "Expected*start*ryan*because of some reason*but*differs at index 1*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected*start*ryan*because of some reason*but*differs at index 1*"); + } - [Fact] - public void When_collection_starts_with_the_specific_element_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "jane", "mike" }; + [Fact] + public void When_collection_starts_with_the_specific_element_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "jane", "mike" }; - // Act - Action act = () => collection.Should().StartWith("john"); + // Act + Action act = () => collection.Should().StartWith("john"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_collection_starts_with_the_specific_sequence_of_elements_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + [Fact] + public void When_collection_starts_with_the_specific_sequence_of_elements_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Act - Action act = () => collection.Should().StartWith(new[] { "john", "bill" }); + // Act + Action act = () => collection.Should().StartWith(new[] { "john", "bill" }); - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_collection_starts_with_the_specific_sequence_of_elements_using_custom_equality_comparison_it_should_not_throw() - { - // Arrange - var collection = new[] { "john", "bill", "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith(new[] { "JoHn", "bIlL" }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); + [Fact] + public void When_collection_starts_with_the_specific_sequence_of_elements_using_custom_equality_comparison_it_should_not_throw() + { + // Arrange + var collection = new[] { "john", "bill", "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().StartWith(new[] { "JoHn", "bIlL" }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); - [Fact] - public void When_collection_starts_with_the_specific_null_element_it_should_not_throw() - { - // Arrange - var collection = new[] { null, "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith((string)null); + [Fact] + public void When_collection_starts_with_the_specific_null_element_it_should_not_throw() + { + // Arrange + var collection = new[] { null, "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().StartWith((string)null); - [Fact] - public void When_non_empty_collection_starts_with_the_empty_sequence_it_should_not_throw() - { - // Arrange - var collection = new[] { "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith(new string[] { }); + [Fact] + public void When_non_empty_collection_starts_with_the_empty_sequence_it_should_not_throw() + { + // Arrange + var collection = new[] { "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().StartWith(new string[] { }); - [Fact] - public void When_empty_collection_starts_with_the_empty_sequence_it_should_not_throw() - { - // Arrange - var collection = new string[] { }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith(new string[] { }); + [Fact] + public void When_empty_collection_starts_with_the_empty_sequence_it_should_not_throw() + { + // Arrange + var collection = new string[] { }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().StartWith(new string[] { }); - [Fact] - public void When_collection_starts_with_the_specific_sequence_with_null_elements_it_should_not_throw() - { - // Arrange - var collection = new[] { null, "john", null, "bill", "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith(new[] { null, "john", null, "bill" }); + [Fact] + public void When_collection_starts_with_the_specific_sequence_with_null_elements_it_should_not_throw() + { + // Arrange + var collection = new[] { null, "john", null, "bill", "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().StartWith(new[] { null, "john", null, "bill" }); - [Fact] - public void When_collection_starts_with_the_specific_sequence_with_null_elements_using_custom_equality_comparison_it_should_not_throw() - { - // Arrange - var collection = new[] { null, "john", null, "bill", "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith(new[] { null, "JoHn", null, "bIlL" }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); + [Fact] + public void When_collection_starts_with_the_specific_sequence_with_null_elements_using_custom_equality_comparison_it_should_not_throw() + { + // Arrange + var collection = new[] { null, "john", null, "bill", "jane", "mike" }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => collection.Should().StartWith(new[] { null, "JoHn", null, "bIlL" }, (s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)); - [Fact] - public void When_collection_starts_with_null_but_that_wasnt_expected_it_should_throw() - { - // Arrange - var collection = new[] { null, "jane", "mike" }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => collection.Should().StartWith("john"); + [Fact] + public void When_collection_starts_with_null_but_that_wasnt_expected_it_should_throw() + { + // Arrange + var collection = new[] { null, "jane", "mike" }; - // Assert - act.Should().Throw().WithMessage( - "Expected*start*john*but*null*"); - } + // Act + Action act = () => collection.Should().StartWith("john"); - [Fact] - public void When_null_collection_is_expected_to_start_with_an_element_it_should_throw() - { - // Arrange - string[] collection = null; + // Assert + act.Should().Throw().WithMessage( + "Expected*start*john*but*null*"); + } - // Act - Action act = () => + [Fact] + public void When_null_collection_is_expected_to_start_with_an_element_it_should_throw() { - using var _ = new AssertionScope(); - collection.Should().StartWith("john"); - }; - - // Assert - act.Should().Throw().WithMessage( - "Expected*start*john*but*collection*null*"); + // Arrange + string[] collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().StartWith("john"); + }; + + // Assert + act.Should().Throw().WithMessage( + "Expected*start*john*but*collection*null*"); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Collections/GenericDictionaryAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Collections/GenericDictionaryAssertionSpecs.cs index 5d51b4d959..f98d828d0f 100644 --- a/Tests/FluentAssertions.Specs/Collections/GenericDictionaryAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Collections/GenericDictionaryAssertionSpecs.cs @@ -12,1338 +12,1541 @@ namespace FluentAssertions.Specs.Collections public class GenericDictionaryAssertionSpecs { // If you try to implement support for IReadOnlyDictionary, these tests should still succeed. - #region Sanity Checks - - [Fact] - public void When_the_same_dictionaries_are_expected_to_be_the_same_it_should_not_fail() + public class SanityChecks { - // Arrange - IDictionary dictionary = new Dictionary(); - IDictionary referenceToDictionary = dictionary; + [Fact] + public void When_the_same_dictionaries_are_expected_to_be_the_same_it_should_not_fail() + { + // Arrange + IDictionary dictionary = new Dictionary(); + IDictionary referenceToDictionary = dictionary; - // Act / Assert - dictionary.Should().BeSameAs(referenceToDictionary); - } + // Act / Assert + dictionary.Should().BeSameAs(referenceToDictionary); + } - [Fact] - public void When_the_same_custom_dictionaries_are_expected_to_be_the_same_it_should_not_fail() - { - // Arrange - IDictionary dictionary = new DictionaryNotImplementingIReadOnlyDictionary(); - IDictionary referenceToDictionary = dictionary; + [Fact] + public void When_the_same_custom_dictionaries_are_expected_to_be_the_same_it_should_not_fail() + { + // Arrange + IDictionary dictionary = new DictionaryNotImplementingIReadOnlyDictionary(); + IDictionary referenceToDictionary = dictionary; - // Act / Assert - dictionary.Should().BeSameAs(referenceToDictionary); - } + // Act / Assert + dictionary.Should().BeSameAs(referenceToDictionary); + } - [Fact] - public void When_object_type_is_exactly_equal_to_the_specified_type_it_should_not_fail() - { - // Arrange - IDictionary dictionary = new DictionaryNotImplementingIReadOnlyDictionary(); + [Fact] + public void When_object_type_is_exactly_equal_to_the_specified_type_it_should_not_fail() + { + // Arrange + IDictionary dictionary = new DictionaryNotImplementingIReadOnlyDictionary(); - // Act / Assert - dictionary.Should().BeOfType>(); - } + // Act / Assert + dictionary.Should().BeOfType>(); + } - [Fact] - public void When_a_dictionary_does_not_implement_the_read_only_interface_it_should_have_dictionary_assertions() - { - // Arrange - IDictionary dictionary = new DictionaryNotImplementingIReadOnlyDictionary(); + [Fact] + public void When_a_dictionary_does_not_implement_the_read_only_interface_it_should_have_dictionary_assertions() + { + // Arrange + IDictionary dictionary = new DictionaryNotImplementingIReadOnlyDictionary(); - // Act / Assert - dictionary.Should().NotContainKey(0, "Dictionaries not implementing IReadOnlyDictionary " - + "should be supported at least until Fluent Assertions 6.0."); + // Act / Assert + dictionary.Should().NotContainKey(0, "Dictionaries not implementing IReadOnlyDictionary " + + "should be supported at least until Fluent Assertions 6.0."); + } } - #endregion - - #region Be Null - - [Fact] - public void When_dictionary_is_expected_to_be_null_and_it_is_it_should_not_throw() + public class BeNull { - // Arrange - IDictionary someDictionary = null; + [Fact] + public void When_dictionary_is_expected_to_be_null_and_it_is_it_should_not_throw() + { + // Arrange + IDictionary someDictionary = null; - // Act / Assert - someDictionary.Should().BeNull(); - } + // Act / Assert + someDictionary.Should().BeNull(); + } - [Fact] - public void When_a_custom_dictionary_implementation_is_expected_not_to_be_null_and_it_is_it_should_not_throw() - { - // Arrange - var dictionary = new TrackingTestDictionary(); + [Fact] + public void When_a_custom_dictionary_implementation_is_expected_not_to_be_null_and_it_is_it_should_not_throw() + { + // Arrange + var dictionary = new TrackingTestDictionary(); - // Act / Assert - dictionary.Should().NotBeNull(); - } + // Act / Assert + dictionary.Should().NotBeNull(); + } - [Fact] - public void When_dictionary_is_expected_to_be_null_and_it_isnt_it_should_throw() - { - // Arrange - var someDictionary = new Dictionary(); + [Fact] + public void When_dictionary_is_expected_to_be_null_and_it_isnt_it_should_throw() + { + // Arrange + var someDictionary = new Dictionary(); - // Act - Action act = () => someDictionary.Should().BeNull("because {0} is valid", "null"); + // Act + Action act = () => someDictionary.Should().BeNull("because {0} is valid", "null"); - // Assert - act.Should().Throw().WithMessage( - "Expected someDictionary to be because null is valid, but found {empty}."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected someDictionary to be because null is valid, but found {empty}."); + } - [Fact] - public void When_dictionary_is_not_expected_to_be_null_and_it_isnt_it_should_not_throw() - { - // Arrange - IDictionary someDictionary = new Dictionary(); + [Fact] + public void When_dictionary_is_not_expected_to_be_null_and_it_isnt_it_should_not_throw() + { + // Arrange + IDictionary someDictionary = new Dictionary(); - // Act / Assert - someDictionary.Should().NotBeNull(); - } + // Act / Assert + someDictionary.Should().NotBeNull(); + } - [Fact] - public void When_dictionary_is_not_expected_to_be_null_and_it_is_it_should_throw() - { - // Arrange - IDictionary someDictionary = null; + [Fact] + public void When_dictionary_is_not_expected_to_be_null_and_it_is_it_should_throw() + { + // Arrange + IDictionary someDictionary = null; - // Act - Action act = () => someDictionary.Should().NotBeNull("because {0} should not", "someDictionary"); + // Act + Action act = () => someDictionary.Should().NotBeNull("because {0} should not", "someDictionary"); - // Assert - act.Should().Throw().WithMessage( - "Expected someDictionary not to be because someDictionary should not."); + // Assert + act.Should().Throw().WithMessage( + "Expected someDictionary not to be because someDictionary should not."); + } } - #endregion - - #region Have Count - - [Fact] - public void Should_succeed_when_asserting_dictionary_has_a_count_that_equals_the_number_of_items() + public class HaveCount { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_has_a_count_that_equals_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().HaveCount(3); - } + // Act / Assert + dictionary.Should().HaveCount(3); + } - [Fact] - public void Should_fail_when_asserting_dictionary_has_a_count_that_is_different_from_the_number_of_items() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_has_a_count_that_is_different_from_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCount(4); + // Act + Action act = () => dictionary.Should().HaveCount(4); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void - When_dictionary_has_a_count_that_is_different_from_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void + When_dictionary_has_a_count_that_is_different_from_the_number_of_items_it_should_fail_with_descriptive_message_() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action action = () => dictionary.Should().HaveCount(4, "because we want to test the failure {0}", "message"); + // Act + Action action = () => dictionary.Should().HaveCount(4, "because we want to test the failure {0}", "message"); - // Assert - action.Should().Throw() - .WithMessage("Expected dictionary to contain 4 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected dictionary to contain 4 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); + } - [Fact] - public void When_dictionary_has_a_count_larger_than_the_minimum_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_larger_than_the_minimum_it_should_not_throw() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().HaveCount(c => c >= 3); - } + // Act / Assert + dictionary.Should().HaveCount(c => c >= 3); + } - [Fact] - public void When_dictionary_has_a_count_that_not_matches_the_predicate_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_that_not_matches_the_predicate_it_should_throw() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCount(c => c >= 4, "a minimum of 4 is required"); + // Act + Action act = () => dictionary.Should().HaveCount(c => c >= 4, "a minimum of 4 is required"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to have a count (c >= 4) because a minimum of 4 is required, but count is 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to have a count (c >= 4) because a minimum of 4 is required, but count is 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); + } - [Fact] - public void When_dictionary_count_is_matched_against_a_null_predicate_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_count_is_matched_against_a_null_predicate_it_should_throw() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCount(null); + // Act + Action act = () => dictionary.Should().HaveCount(null); - // Assert - act.Should().Throw().WithMessage( - "Cannot compare collection count against a predicate.*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot compare collection count against a predicate.*"); + } - [Fact] - public void When_dictionary_count_is_matched_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_matched_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().HaveCount(1, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().HaveCount(1, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain 1 item(s) because we want to test the behaviour with a null subject, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain 1 item(s) because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_dictionary_count_is_matched_against_a_predicate_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_matched_against_a_predicate_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().HaveCount(c => c < 3, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().HaveCount(c => c < 3, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain (c < 3) items because we want to test the behaviour with a null subject, but found ."); + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain (c < 3) items because we want to test the behaviour with a null subject, but found ."); + } } - #endregion - - #region Not Have Count - - [Fact] - public void Should_succeed_when_asserting_dictionary_has_a_count_different_from_the_number_of_items() + public class NotHaveCount { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_has_a_count_different_from_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().NotHaveCount(2); - } + // Act / Assert + dictionary.Should().NotHaveCount(2); + } - [Fact] - public void Should_fail_when_asserting_dictionary_has_a_count_that_equals_the_number_of_items() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_has_a_count_that_equals_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().NotHaveCount(3); + // Act + Action act = () => dictionary.Should().NotHaveCount(3); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_dictionary_has_a_count_that_equals_than_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_that_equals_than_the_number_of_items_it_should_fail_with_descriptive_message_() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action action = () => dictionary.Should().NotHaveCount(3, "because we want to test the failure {0}", "message"); + // Act + Action action = () => dictionary.Should().NotHaveCount(3, "because we want to test the failure {0}", "message"); - // Assert - action.Should().Throw() - .WithMessage("*not contain*3*because we want to test the failure message*3*"); - } + // Assert + action.Should().Throw() + .WithMessage("*not contain*3*because we want to test the failure message*3*"); + } - [Fact] - public void When_dictionary_count_is_same_than_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_same_than_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().NotHaveCount(1, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().NotHaveCount(1, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage("*not contain*1*we want to test the behaviour with a null subject*found *"); + // Assert + act.Should().Throw().WithMessage("*not contain*1*we want to test the behaviour with a null subject*found *"); + } } - #endregion - - #region Have Count Greater Than - - [Fact] - public void Should_succeed_when_asserting_dictionary_has_a_count_greater_than_less_the_number_of_items() + public class HaveCountGreaterThan { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_has_a_count_greater_than_less_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().HaveCountGreaterThan(2); - } + // Act / Assert + dictionary.Should().HaveCountGreaterThan(2); + } - [Fact] - public void Should_fail_when_asserting_dictionary_has_a_count_greater_than_the_number_of_items() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_has_a_count_greater_than_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCountGreaterThan(3); + // Act + Action act = () => dictionary.Should().HaveCountGreaterThan(3); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_dictionary_has_a_count_greater_than_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_greater_than_the_number_of_items_it_should_fail_with_descriptive_message_() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action action = () => dictionary.Should().HaveCountGreaterThan(3, "because we want to test the failure {0}", "message"); + // Act + Action action = () => dictionary.Should().HaveCountGreaterThan(3, "because we want to test the failure {0}", "message"); - // Assert - action.Should().Throw() - .WithMessage("Expected dictionary to contain more than 3 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected dictionary to contain more than 3 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); + } - [Fact] - public void When_dictionary_count_is_greater_than_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_greater_than_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().HaveCountGreaterThan(1, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().HaveCountGreaterThan(1, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage("*more than*1*we want to test the behaviour with a null subject*found *"); + // Assert + act.Should().Throw().WithMessage("*more than*1*we want to test the behaviour with a null subject*found *"); + } } - #endregion - - #region Have Count Greater Than Or Equal To - - [Fact] - public void Should_succeed_when_asserting_dictionary_has_a_count_greater_than_or_equal_to_less_the_number_of_items() + public class HaveCountGreaterThanOrEqualTo { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_has_a_count_greater_than_or_equal_to_less_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().HaveCountGreaterThanOrEqualTo(3); - } + // Act / Assert + dictionary.Should().HaveCountGreaterThanOrEqualTo(3); + } - [Fact] - public void Should_fail_when_asserting_dictionary_has_a_count_greater_than_or_equal_to_the_number_of_items() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_has_a_count_greater_than_or_equal_to_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCountGreaterThanOrEqualTo(4); + // Act + Action act = () => dictionary.Should().HaveCountGreaterThanOrEqualTo(4); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_dictionary_has_a_count_greater_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_greater_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action action = () => dictionary.Should().HaveCountGreaterThanOrEqualTo(4, "because we want to test the failure {0}", "message"); + // Act + Action action = () => dictionary.Should().HaveCountGreaterThanOrEqualTo(4, "because we want to test the failure {0}", "message"); - // Assert - action.Should().Throw() - .WithMessage("Expected dictionary to contain at least 4 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected dictionary to contain at least 4 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); + } - [Fact] - public void When_dictionary_count_is_greater_than_or_equal_to_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_greater_than_or_equal_to_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().HaveCountGreaterThanOrEqualTo(1, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().HaveCountGreaterThanOrEqualTo(1, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage("*at least*1*we want to test the behaviour with a null subject*found *"); + // Assert + act.Should().Throw().WithMessage("*at least*1*we want to test the behaviour with a null subject*found *"); + } } - #endregion - - #region Have Count Less Than - - [Fact] - public void Should_succeed_when_asserting_dictionary_has_a_count_less_than_less_the_number_of_items() + public class HaveCountLessThan { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_has_a_count_less_than_less_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().HaveCountLessThan(4); - } + // Act / Assert + dictionary.Should().HaveCountLessThan(4); + } - [Fact] - public void Should_fail_when_asserting_dictionary_has_a_count_less_than_the_number_of_items() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_has_a_count_less_than_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCountLessThan(3); + // Act + Action act = () => dictionary.Should().HaveCountLessThan(3); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_dictionary_has_a_count_less_than_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_less_than_the_number_of_items_it_should_fail_with_descriptive_message_() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action action = () => dictionary.Should().HaveCountLessThan(3, "because we want to test the failure {0}", "message"); + // Act + Action action = () => dictionary.Should().HaveCountLessThan(3, "because we want to test the failure {0}", "message"); - // Assert - action.Should().Throw() - .WithMessage("Expected dictionary to contain fewer than 3 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected dictionary to contain fewer than 3 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); + } - [Fact] - public void When_dictionary_count_is_less_than_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_less_than_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().HaveCountLessThan(1, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().HaveCountLessThan(1, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage("*fewer than*1*we want to test the behaviour with a null subject*found *"); + // Assert + act.Should().Throw().WithMessage("*fewer than*1*we want to test the behaviour with a null subject*found *"); + } } - #endregion - - #region Have Count Less Than Or Equal To - - [Fact] - public void Should_succeed_when_asserting_dictionary_has_a_count_less_than_or_equal_to_less_the_number_of_items() + public class HaveCountLessThanOrEqualTo { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_has_a_count_less_than_or_equal_to_less_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act / Assert - dictionary.Should().HaveCountLessThanOrEqualTo(3); - } + // Act / Assert + dictionary.Should().HaveCountLessThanOrEqualTo(3); + } - [Fact] - public void Should_fail_when_asserting_dictionary_has_a_count_less_than_or_equal_to_the_number_of_items() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_has_a_count_less_than_or_equal_to_the_number_of_items() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action act = () => dictionary.Should().HaveCountLessThanOrEqualTo(2); + // Act + Action act = () => dictionary.Should().HaveCountLessThanOrEqualTo(2); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_dictionary_has_a_count_less_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_has_a_count_less_than_or_equal_to_the_number_of_items_it_should_fail_with_descriptive_message_() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; - // Act - Action action = () => dictionary.Should().HaveCountLessThanOrEqualTo(2, "because we want to test the failure {0}", "message"); + // Act + Action action = () => dictionary.Should().HaveCountLessThanOrEqualTo(2, "because we want to test the failure {0}", "message"); - // Assert - action.Should().Throw() - .WithMessage("Expected dictionary to contain at most 2 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); - } + // Assert + action.Should().Throw() + .WithMessage("Expected dictionary to contain at most 2 item(s) because we want to test the failure message, but found 3: {[1] = \"One\", [2] = \"Two\", [3] = \"Three\"}."); + } - [Fact] - public void When_dictionary_count_is_less_than_or_equal_to_and_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_count_is_less_than_or_equal_to_and_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().HaveCountLessThanOrEqualTo(1, "we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().HaveCountLessThanOrEqualTo(1, "we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage("*at most*1*we want to test the behaviour with a null subject*found *"); + // Assert + act.Should().Throw().WithMessage("*at most*1*we want to test the behaviour with a null subject*found *"); + } } - #endregion - - #region Have Same Count - - [Fact] - public void When_dictionary_and_collection_have_the_same_number_elements_it_should_succeed() + public class HaveSameCount { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_and_collection_have_the_same_number_elements_it_should_succeed() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = new[] { 4, 5, 6 }; - - // Act / Assert - dictionary.Should().HaveSameCount(collection); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = new[] { 4, 5, 6 }; + + // Act / Assert + dictionary.Should().HaveSameCount(collection); + } - [Fact] - public void When_dictionary_and_collection_do_not_have_the_same_number_of_elements_it_should_fail() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_and_collection_do_not_have_the_same_number_of_elements_it_should_fail() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = new[] { 4, 6 }; - - // Act - Action act = () => dictionary.Should().HaveSameCount(collection); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = new[] { 4, 6 }; + + // Act + Action act = () => dictionary.Should().HaveSameCount(collection); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to have 2 item(s), but found 3."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to have 2 item(s), but found 3."); - } + [Fact] + public void When_comparing_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = new[] { 4, 6 }; + + // Act + Action act = () => dictionary.Should().HaveSameCount(collection, "we want to test the {0}", "reason"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to have 2 item(s) because we want to test the reason, but found 3."); + } - [Fact] - public void When_comparing_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_and_collection_have_same_count_against_null_dictionary_it_should_throw() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = new[] { 4, 6 }; + // Arrange + Dictionary dictionary = null; + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => dictionary.Should().HaveSameCount(collection, "we want to test the {0}", "reason"); + // Act + Action act = () => dictionary.Should().HaveSameCount(collection, + "because we want to test the behaviour with a null subject"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to have 2 item(s) because we want to test the reason, but found 3."); + [Fact] + public void When_asserting_dictionary_and_collection_have_same_count_against_a_null_collection_it_should_throw() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + int[] collection = null; + + // Act + Action act = () => dictionary.Should().HaveSameCount(collection); + + // Assert + act.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } } - [Fact] - public void When_asserting_dictionary_and_collection_have_same_count_against_null_dictionary_it_should_throw() + public class NotHaveSameCount { - // Arrange - Dictionary dictionary = null; - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_asserting_not_same_count_and_collections_have_different_number_elements_it_should_succeed() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = new[] { 4, 6 }; + + // Act / Assert + dictionary.Should().NotHaveSameCount(collection); + } - // Act - Action act = () => dictionary.Should().HaveSameCount(collection, - "because we want to test the behaviour with a null subject"); + [Fact] + public void When_asserting_not_same_count_and_both_collections_have_the_same_number_elements_it_should_fail() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = new[] { 4, 5, 6 }; + + // Act + Action act = () => dictionary.Should().NotHaveSameCount(collection); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not have 3 item(s), but found 3."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); - } + [Fact] + public void When_comparing_not_same_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = new[] { 4, 5, 6 }; + + // Act + Action act = () => dictionary.Should().NotHaveSameCount(collection, "we want to test the {0}", "reason"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not have 3 item(s) because we want to test the reason, but found 3."); + } - [Fact] - public void When_asserting_dictionary_and_collection_have_same_count_against_a_null_collection_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_and_collection_to_not_have_same_count_against_null_dictionary_it_should_throw() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - int[] collection = null; + // Arrange + Dictionary dictionary = null; + var collection = new[] { 1, 2, 3 }; - // Act - Action act = () => dictionary.Should().HaveSameCount(collection); + // Act + Action act = () => dictionary.Should().NotHaveSameCount(collection, + "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify count against a collection.*"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); + } - #endregion + [Fact] + public void When_asserting_dictionary_and_collection_to_not_have_same_count_against_a_null_collection_it_should_throw() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + int[] collection = null; + + // Act + Action act = () => dictionary.Should().NotHaveSameCount(collection); + + // Assert + act.Should().Throw().WithMessage( + "Cannot verify count against a collection.*"); + } - #region Not Have Same Count + [Fact] + public void When_asserting_dictionary_and_collection_to_not_have_same_count_but_both_reference_the_same_object_it_should_throw() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var collection = dictionary; + + // Act + Action act = () => dictionary.Should().NotHaveSameCount(collection, + "because we want to test the behaviour with same objects"); + + // Assert + act.Should().Throw().WithMessage( + "*not have the same count*because we want to test the behaviour with same objects*but they both reference the same object."); + } + } - [Fact] - public void When_asserting_not_same_count_and_collections_have_different_number_elements_it_should_succeed() + public class BeEmpty { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_without_items_is_empty() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = new[] { 4, 6 }; + // Arrange + var dictionary = new Dictionary(); - // Act / Assert - dictionary.Should().NotHaveSameCount(collection); - } + // Act / Assert + dictionary.Should().BeEmpty(); + } - [Fact] - public void When_asserting_not_same_count_and_both_collections_have_the_same_number_elements_it_should_fail() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_when_asserting_dictionary_with_items_is_empty() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = new[] { 4, 5, 6 }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One" + }; - // Act - Action act = () => dictionary.Should().NotHaveSameCount(collection); + // Act + Action act = () => dictionary.Should().BeEmpty(); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not have 3 item(s), but found 3."); - } + // Assert + act.Should().Throw(); + } - [Fact] - public void When_comparing_not_same_item_counts_and_a_reason_is_specified_it_should_it_in_the_exception() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_fail_with_descriptive_message_when_asserting_dictionary_with_items_is_empty() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = new[] { 4, 5, 6 }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One" + }; - // Act - Action act = () => dictionary.Should().NotHaveSameCount(collection, "we want to test the {0}", "reason"); + // Act + Action act = () => dictionary.Should().BeEmpty("because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not have 3 item(s) because we want to test the reason, but found 3."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected dictionary to be empty because we want to test the failure message, but found {[1] = \"One\"}."); + } - [Fact] - public void When_asserting_dictionary_and_collection_to_not_have_same_count_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; - var collection = new[] { 1, 2, 3 }; + [Fact] + public void When_asserting_dictionary_with_items_is_not_empty_it_should_succeed() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One" + }; - // Act - Action act = () => dictionary.Should().NotHaveSameCount(collection, - "because we want to test the behaviour with a null subject"); + // Act / Assert + dictionary.Should().NotBeEmpty(); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not have the same count as {1, 2, 3} because we want to test the behaviour with a null subject, but found ."); - } +#if !NET5_0_OR_GREATER - [Fact] - public void When_asserting_dictionary_and_collection_to_not_have_same_count_against_a_null_collection_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_with_items_is_not_empty_it_should_enumerate_the_dictionary_only_once() { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - int[] collection = null; + // Arrange + var trackingDictionary = new TrackingTestDictionary(new KeyValuePair(1, "One")); - // Act - Action act = () => dictionary.Should().NotHaveSameCount(collection); + // Act + trackingDictionary.Should().NotBeEmpty(); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify count against a collection.*"); - } + // Assert + trackingDictionary.Enumerator.LoopCount.Should().Be(1); + } - [Fact] - public void When_asserting_dictionary_and_collection_to_not_have_same_count_but_both_reference_the_same_object_it_should_throw() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var collection = dictionary; +#endif - // Act - Action act = () => dictionary.Should().NotHaveSameCount(collection, - "because we want to test the behaviour with same objects"); + [Fact] + public void When_asserting_dictionary_without_items_is_not_empty_it_should_fail() + { + // Arrange + var dictionary = new Dictionary(); - // Assert - act.Should().Throw().WithMessage( - "*not have the same count*because we want to test the behaviour with same objects*but they both reference the same object."); - } + // Act + Action act = () => dictionary.Should().NotBeEmpty(); - #endregion + // Assert + act.Should().Throw(); + } - #region Be Empty + [Fact] + public void When_asserting_dictionary_without_items_is_not_empty_it_should_fail_with_descriptive_message_() + { + // Arrange + var dictionary = new Dictionary(); - [Fact] - public void Should_succeed_when_asserting_dictionary_without_items_is_empty() - { - // Arrange - var dictionary = new Dictionary(); + // Act + Action act = () => dictionary.Should().NotBeEmpty("because we want to test the failure {0}", "message"); - // Act / Assert - dictionary.Should().BeEmpty(); - } + // Assert + act.Should().Throw() + .WithMessage("Expected dictionary not to be empty because we want to test the failure message."); + } - [Fact] - public void Should_fail_when_asserting_dictionary_with_items_is_empty() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_to_be_empty_but_dictionary_is_null_it_should_throw() { - [1] = "One" - }; + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().BeEmpty(); + // Act + Action act = () => dictionary.Should().BeEmpty("because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to be empty because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void Should_fail_with_descriptive_message_when_asserting_dictionary_with_items_is_empty() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_to_be_not_empty_but_dictionary_is_null_it_should_throw() { - [1] = "One" - }; + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().BeEmpty("because we want to test the failure {0}", "message"); + // Act + Action act = () => dictionary.Should().NotBeEmpty("because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw() - .WithMessage("Expected dictionary to be empty because we want to test the failure message, but found {[1] = \"One\"}."); + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary not to be empty because we want to test the behaviour with a null subject, but found ."); + } } - [Fact] - public void When_asserting_dictionary_with_items_is_not_empty_it_should_succeed() + public class Equal { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_is_equal_to_the_same_dictionary() { - [1] = "One" - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary.Should().NotBeEmpty(); - } - -#if !NET5_0_OR_GREATER + // Act / Assert + dictionary1.Should().Equal(dictionary2); + } - [Fact] - public void When_asserting_dictionary_with_items_is_not_empty_it_should_enumerate_the_dictionary_only_once() - { - // Arrange - var trackingDictionary = new TrackingTestDictionary(new KeyValuePair(1, "One")); + [Fact] + public void Should_succeed_when_asserting_dictionary_with_null_value_is_equal_to_the_same_dictionary() + { + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = null + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = null + }; - // Act - trackingDictionary.Should().NotBeEmpty(); + // Act / Assert + dictionary1.Should().Equal(dictionary2); + } - // Assert - trackingDictionary.Enumerator.LoopCount.Should().Be(1); - } + [Fact] + public void When_asserting_dictionaries_to_be_equal_but_subject_dictionary_misses_a_value_it_should_throw() + { + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [22] = "Two" + }; -#endif + // Act + Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_dictionary_without_items_is_not_empty_it_should_fail() - { - // Arrange - var dictionary = new Dictionary(); + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary1 to be equal to {[1] = \"One\", [22] = \"Two\"} because we want to test the failure message, but could not find keys {22}."); + } - // Act - Action act = () => dictionary.Should().NotBeEmpty(); + [Fact] + public void When_asserting_dictionaries_to_be_equal_but_subject_dictionary_has_extra_key_it_should_throw() + { + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw(); - } + // Act + Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_dictionary_without_items_is_not_empty_it_should_fail_with_descriptive_message_() - { - // Arrange - var dictionary = new Dictionary(); + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Two\"} because we want to test the failure message, but found additional keys {3}."); + } - // Act - Action act = () => dictionary.Should().NotBeEmpty("because we want to test the failure {0}", "message"); + [Fact] + public void When_two_dictionaries_are_not_equal_by_values_it_should_throw_using_the_reason() + { + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Three" + }; - // Assert - act.Should().Throw() - .WithMessage("Expected dictionary not to be empty because we want to test the failure message."); - } + // Act + Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_dictionary_to_be_empty_but_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Three\"} because we want to test the failure message, but {[1] = \"One\", [2] = \"Two\"} differs at key 2."); + } - // Act - Action act = () => dictionary.Should().BeEmpty("because we want to test the behaviour with a null subject"); + [Fact] + public void When_asserting_dictionaries_to_be_equal_but_subject_dictionary_is_null_it_should_throw() + { + // Arrange + Dictionary dictionary1 = null; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to be empty because we want to test the behaviour with a null subject, but found ."); - } + // Act + Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the behaviour with a null subject"); - [Fact] - public void When_asserting_dictionary_to_be_not_empty_but_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Two\"} because we want to test the behaviour with a null subject, but found ."); + } - // Act - Action act = () => dictionary.Should().NotBeEmpty("because we want to test the behaviour with a null subject"); + [Fact] + public void When_asserting_dictionaries_to_be_equal_but_expected_dictionary_is_null_it_should_throw() + { + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + Dictionary dictionary2 = null; + + // Act + Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the behaviour with a null subject"); + + // Assert + act.Should().Throw() + .WithMessage("Cannot compare dictionary with .*") + .WithParameterName("expected"); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary not to be empty because we want to test the behaviour with a null subject, but found ."); - } + [Fact] + public void When_an_empty_dictionary_is_compared_for_equality_to_a_non_empty_dictionary_it_should_throw() + { + // Arrange + var dictionary1 = new Dictionary(); + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - #endregion + // Act + Action act = () => dictionary1.Should().Equal(dictionary2); - #region Equal + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Two\"}, but could not find keys {1, 2}."); + } + } - [Fact] - public void Should_succeed_when_asserting_dictionary_is_equal_to_the_same_dictionary() + public class NotEqual { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_is_not_equal_to_a_dictionary_with_different_key() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [22] = "Two" + }; - // Act / Assert - dictionary1.Should().Equal(dictionary2); - } + // Act / Assert + dictionary1.Should().NotEqual(dictionary2); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_with_null_value_is_equal_to_the_same_dictionary() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = null - }; - var dictionary2 = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_is_not_equal_to_a_dictionary_with_different_value() { - [1] = "One", - [2] = null - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = null + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary1.Should().Equal(dictionary2); - } + // Act / Assert + dictionary1.Should().NotEqual(dictionary2); + } - [Fact] - public void When_asserting_dictionaries_to_be_equal_but_subject_dictionary_misses_a_value_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = new Dictionary + [Fact] + public void When_two_equal_dictionaries_are_not_expected_to_be_equal_it_should_throw() { - [1] = "One", - [22] = "Two" - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the failure {0}", "message"); + // Act + Action act = () => dictionary1.Should().NotEqual(dictionary2); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary1 to be equal to {[1] = \"One\", [22] = \"Two\"} because we want to test the failure message, but could not find keys {22}."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect dictionaries {[1] = \"One\", [2] = \"Two\"} and {[1] = \"One\", [2] = \"Two\"} to be equal."); + } - [Fact] - public void When_asserting_dictionaries_to_be_equal_but_subject_dictionary_has_extra_key_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = "Two", - [3] = "Three" - }; - var dictionary2 = new Dictionary + [Fact] + public void When_two_equal_dictionaries_are_not_expected_to_be_equal_it_should_report_a_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the failure {0}", "message"); + // Act + Action act = () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Two\"} because we want to test the failure message, but found additional keys {3}."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect dictionaries {[1] = \"One\", [2] = \"Two\"} and {[1] = \"One\", [2] = \"Two\"} to be equal because we want to test the failure message."); + } - [Fact] - public void When_two_dictionaries_are_not_equal_by_values_it_should_throw_using_the_reason() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = new Dictionary + [Fact] + public void When_asserting_dictionaries_not_to_be_equal_subject_but_dictionary_is_null_it_should_throw() { - [1] = "One", - [2] = "Three" - }; + // Arrange + Dictionary dictionary1 = null; + var dictionary2 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the failure {0}", "message"); + // Act + Action act = + () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Three\"} because we want to test the failure message, but {[1] = \"One\", [2] = \"Two\"} differs at key 2."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionaries not to be equal because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_asserting_dictionaries_to_be_equal_but_subject_dictionary_is_null_it_should_throw() - { - // Arrange - Dictionary dictionary1 = null; - var dictionary2 = new Dictionary + [Fact] + public void When_asserting_dictionaries_not_to_be_equal_but_expected_dictionary_is_null_it_should_throw() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the behaviour with a null subject"); + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + Dictionary dictionary2 = null; + + // Act + Action act = + () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the behaviour with a null subject"); + + // Assert + act.Should().Throw() + .WithMessage("Cannot compare dictionary with .*") + .WithParameterName("unexpected"); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Two\"} because we want to test the behaviour with a null subject, but found ."); + [Fact] + public void When_asserting_dictionaries_not_to_be_equal_subject_but_both_dictionaries_reference_the_same_object_it_should_throw() + { + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + var dictionary2 = dictionary1; + + // Act + Action act = + () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the behaviour with same objects"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionaries not to be equal because we want to test the behaviour with same objects, but they both reference the same object."); + } } - [Fact] - public void When_asserting_dictionaries_to_be_equal_but_expected_dictionary_is_null_it_should_throw() + public class ContainKey { - // Arrange - var dictionary1 = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_contains_a_key_from_the_dictionary() { - [1] = "One", - [2] = "Two" - }; - Dictionary dictionary2 = null; - - // Act - Action act = () => dictionary1.Should().Equal(dictionary2, "because we want to test the behaviour with a null subject"); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw() - .WithMessage("Cannot compare dictionary with .*") - .WithParameterName("expected"); - } + // Act / Assert + dictionary.Should().ContainKey(1); + } - [Fact] - public void When_an_empty_dictionary_is_compared_for_equality_to_a_non_empty_dictionary_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary(); - var dictionary2 = new Dictionary + [Fact] + public void When_a_dictionary_has_custom_equality_comparer_the_contains_key_assertion_should_work_accordingly() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["One"] = "One", + ["Two"] = "Two" + }; - // Act - Action act = () => dictionary1.Should().Equal(dictionary2); + // Act - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary1 to be equal to {[1] = \"One\", [2] = \"Two\"}, but could not find keys {1, 2}."); - } + // Assert + dictionary.Should().ContainKey("One"); + dictionary.Should().ContainKey("ONE"); + dictionary.Should().ContainKey("one"); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_is_not_equal_to_a_dictionary_with_different_key() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_contains_multiple_keys_from_the_dictionary() { - [1] = "One", - [22] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary1.Should().NotEqual(dictionary2); - } + // Act / Assert + dictionary.Should().ContainKeys(2, 1); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_is_not_equal_to_a_dictionary_with_different_value() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = null - }; - var dictionary2 = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_single_key_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary1.Should().NotEqual(dictionary2); - } + // Act + Action act = () => dictionary.Should().ContainKey(3, "because {0}", "we do"); - [Fact] - public void When_two_equal_dictionaries_are_not_expected_to_be_equal_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary - { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = new Dictionary + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key 3 because we do."); + } + + [Fact] + public void When_the_requested_key_exists_it_should_allow_continuation_with_the_value() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + ["Key"] = new MyClass { SomeProperty = 3 } + }; - // Act - Action act = () => dictionary1.Should().NotEqual(dictionary2); + // Act + Action act = () => dictionary.Should().ContainKey("Key").WhoseValue.Should().Be(4); - // Assert - act.Should().Throw().WithMessage( - "Did not expect dictionaries {[1] = \"One\", [2] = \"Two\"} and {[1] = \"One\", [2] = \"Two\"} to be equal."); - } + // Assert + act.Should().Throw().WithMessage("Expected*4*3*."); + } - [Fact] - public void When_two_equal_dictionaries_are_not_expected_to_be_equal_it_should_report_a_clear_explanation() - { - // Arrange - var dictionary1 = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_a_list_of_keys_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = new Dictionary + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + + // Act + Action act = () => dictionary.Should().ContainKeys(new[] { 2, 3 }, "because {0}", "we do"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key {2, 3} because we do, but could not find {3}."); + } + + [Fact] + public void When_the_contents_of_a_dictionary_are_checked_against_an_empty_list_of_keys_it_should_throw_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the failure {0}", "message"); + // Act + Action act = () => dictionary.Should().ContainKeys(new int[0]); - // Assert - act.Should().Throw().WithMessage( - "Did not expect dictionaries {[1] = \"One\", [2] = \"Two\"} and {[1] = \"One\", [2] = \"Two\"} to be equal because we want to test the failure message."); + // Assert + act.Should().Throw().WithMessage( + "Cannot verify key containment against an empty sequence*"); + } } - [Fact] - public void When_asserting_dictionaries_not_to_be_equal_subject_but_dictionary_is_null_it_should_throw() + public class NotContainKey { - // Arrange - Dictionary dictionary1 = null; - var dictionary2 = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_a_key_that_is_not_in_the_dictionary_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = - () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().NotContainKey(4); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionaries not to be equal because we want to test the behaviour with a null subject, but found ."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_dictionaries_not_to_be_equal_but_expected_dictionary_is_null_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_multiple_keys_from_the_dictionary_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; - Dictionary dictionary2 = null; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = - () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().NotContainKeys(3, 4); - // Assert - act.Should().Throw() - .WithMessage("Cannot compare dictionary with .*") - .WithParameterName("unexpected"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_dictionaries_not_to_be_equal_subject_but_both_dictionaries_reference_the_same_object_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary + [Fact] + public void When_dictionary_contains_an_unexpected_key_it_should_throw() { - [1] = "One", - [2] = "Two" - }; - var dictionary2 = dictionary1; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = - () => dictionary1.Should().NotEqual(dictionary2, "because we want to test the behaviour with same objects"); + // Act + Action act = () => dictionary.Should().NotContainKey(1, "because we {0} like it", "don't"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionaries not to be equal because we want to test the behaviour with same objects, but they both reference the same object."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} not to contain key 1 because we don't like it, but found it anyhow."); + } + + [Fact] + public void When_asserting_dictionary_does_not_contain_key_against_null_dictionary_it_should_throw() + { + // Arrange + Dictionary dictionary = null; - #endregion + // Act + Action act = () => dictionary.Should() + .NotContainKey(1, "because we want to test the behaviour with a null subject"); - #region ContainKey + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary not to contain key 1 because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_contains_a_key_from_the_dictionary() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_contains_a_list_of_keys_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary.Should().ContainKey(1); - } + // Act + Action act = () => dictionary.Should().NotContainKeys(new[] { 2, 3 }, "because {0}", "we do"); - [Fact] - public void When_a_dictionary_has_custom_equality_comparer_the_contains_key_assertion_should_work_accordingly() - { - // Arrange - var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase) + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain key {2, 3} because we do, but found {2}."); + } + + [Fact] + public void When_a_dictionary_contains_exactly_one_of_the_keys_it_should_throw_with_clear_explanation() { - ["One"] = "One", - ["Two"] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act + // Act + Action act = () => dictionary.Should().NotContainKeys(new[] { 2 }, "because {0}", "we do"); - // Assert - dictionary.Should().ContainKey("One"); - dictionary.Should().ContainKey("ONE"); - dictionary.Should().ContainKey("one"); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain key 2 because we do."); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_contains_multiple_keys_from_the_dictionary() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_the_noncontents_of_a_dictionary_are_checked_against_an_empty_list_of_keys_it_should_throw_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary.Should().ContainKeys(2, 1); - } + // Act + Action act = () => dictionary.Should().NotContainKeys(new int[0]); - [Fact] - public void When_a_dictionary_does_not_contain_single_key_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + // Assert + act.Should().Throw().WithMessage( + "Cannot verify key containment against an empty sequence*"); + } + + [Fact] + public void When_a_dictionary_checks_a_list_of_keys_not_to_be_present_it_will_honor_the_case_sensitive_equality_comparer_of_the_dictionary() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary(StringComparer.Ordinal) + { + ["ONE"] = "One", + ["TWO"] = "Two" + }; - // Act - Action act = () => dictionary.Should().ContainKey(3, "because {0}", "we do"); + // Act + Action act = () => dictionary.Should().NotContainKeys(new[] { "One", "Two" }); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key 3 because we do."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_requested_key_exists_it_should_allow_continuation_with_the_value() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_checks_a_list_of_keys_not_to_be_present_it_will_honor_the_case_insensitive_equality_comparer_of_the_dictionary() { - ["Key"] = new MyClass { SomeProperty = 3 } - }; + // Arrange + var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["ONE"] = "One", + ["TWO"] = "Two" + }; + + // Act + Action act = () => dictionary.Should().NotContainKeys(new[] { "One", "Two" }); - // Act - Action act = () => dictionary.Should().ContainKey("Key").WhoseValue.Should().Be(4); + // Assert + act.Should().Throw(); + } - // Assert - act.Should().Throw().WithMessage("Expected*4*3*."); + [Fact] + public void When_an_assertion_fails_on_ContainKey_succeeding_message_should_be_included() + { + // Act + Action act = () => + { + using var _ = new AssertionScope(); + var values = new Dictionary(); + values.Should().ContainKey(0); + values.Should().ContainKey(1); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected*to contain key 0*Expected*to contain key 1*"); + } } public class MyClass @@ -1381,1339 +1584,1135 @@ public override int GetHashCode() } } - [Fact] - public void When_a_dictionary_does_not_contain_a_list_of_keys_it_should_throw_with_clear_explanation() + public class ContainValue { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_expected_value_it_should_succeed() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().ContainKeys(new[] { 2, 3 }, "because {0}", "we do"); + // Act + Action act = () => dictionary.Should().ContainValue("One"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key {2, 3} because we do, but could not find {3}."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_contents_of_a_dictionary_are_checked_against_an_empty_list_of_keys_it_should_throw_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_expected_null_value_it_should_succeed() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = null + }; - // Act - Action act = () => dictionary.Should().ContainKeys(new int[0]); + // Act + Action act = () => dictionary.Should().ContainValue(null); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify key containment against an empty sequence*"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_dictionary_does_not_contain_a_key_that_is_not_in_the_dictionary_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_the_specified_value_exists_it_should_allow_continuation_using_that_value() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var myClass = new MyClass() + { + SomeProperty = 0 + }; - // Act - Action act = () => dictionary.Should().NotContainKey(4); + var dictionary = new Dictionary + { + [1] = myClass + }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => dictionary.Should().ContainValue(myClass).Which.SomeProperty.Should().BeGreaterThan(0); - [Fact] - public void When_dictionary_does_not_contain_multiple_keys_from_the_dictionary_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Assert + act.Should().Throw().WithMessage("Expected*greater*0*0*"); + } - // Act - Action act = () => dictionary.Should().NotContainKeys(3, 4); + [Fact] + public void When_multiple_matches_for_the_specified_value_exist_continuation_using_the_matched_value_should_fail() + { + // Arrange + var myClass = new MyClass { SomeProperty = 0 }; - // Assert - act.Should().NotThrow(); - } + var dictionary = new Dictionary + { + [1] = myClass, + [2] = new MyClass { SomeProperty = 0 } + }; + + // Act + Action act = + () => + dictionary.Should() + .ContainValue(new MyClass { SomeProperty = 0 }) + .Which.Should() + .BeSameAs(myClass); + + // Assert + act.Should().Throw(); + } - [Fact] - public void When_dictionary_contains_an_unexpected_key_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_multiple_values_from_the_dictionary_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().NotContainKey(1, "because we {0} like it", "don't"); + // Act + Action act = () => dictionary.Should().ContainValues("Two", "One"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} not to contain key 1 because we don't like it, but found it anyhow."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_dictionary_does_not_contain_key_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_a_dictionary_does_not_contain_single_value_it_should_throw_with_clear_explanation() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should() - .NotContainKey(1, "because we want to test the behaviour with a null subject"); + // Act + Action act = () => dictionary.Should().ContainValue("Three", "because {0}", "we do"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary not to contain key 1 because we want to test the behaviour with a null subject, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain value \"Three\" because we do."); + } - [Fact] - public void When_a_dictionary_contains_a_list_of_keys_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_a_number_of_values_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().NotContainKeys(new[] { 2, 3 }, "because {0}", "we do"); + // Act + Action act = () => dictionary.Should().ContainValues(new[] { "Two", "Three" }, "because {0}", "we do"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain key {2, 3} because we do, but found {2}."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain value {\"Two\", \"Three\"} because we do, but could not find {\"Three\"}."); + } - [Fact] - public void When_a_dictionary_contains_exactly_one_of_the_keys_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_the_contents_of_a_dictionary_are_checked_against_an_empty_list_of_values_it_should_throw_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().NotContainKeys(new[] { 2 }, "because {0}", "we do"); + // Act + Action act = () => dictionary.Should().ContainValues(new string[0]); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain key 2 because we do."); + // Assert + act.Should().Throw().WithMessage( + "Cannot verify value containment with an empty sequence*"); + } } - [Fact] - public void When_the_noncontents_of_a_dictionary_are_checked_against_an_empty_list_of_keys_it_should_throw_clear_explanation() + public class NotContainValue { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_a_value_that_is_not_in_the_dictionary_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().NotContainKeys(new int[0]); + // Act + Action act = () => dictionary.Should().NotContainValue("Three"); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify key containment against an empty sequence*"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_dictionary_checks_a_list_of_keys_not_to_be_present_it_will_honor_the_case_sensitive_equality_comparer_of_the_dictionary() - { - // Arrange - var dictionary = new Dictionary(StringComparer.Ordinal) + [Fact] + public void When_dictionary_contains_an_unexpected_value_it_should_throw() { - ["ONE"] = "One", - ["TWO"] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().NotContainKeys(new[] { "One", "Two" }); + // Act + Action act = () => dictionary.Should().NotContainValue("One", "because we {0} like it", "don't"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} not to contain value \"One\" because we don't like it, but found it anyhow."); + } - [Fact] - public void When_a_dictionary_checks_a_list_of_keys_not_to_be_present_it_will_honor_the_case_insensitive_equality_comparer_of_the_dictionary() - { - // Arrange - var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase) + [Fact] + public void When_asserting_dictionary_does_not_contain_value_against_null_dictionary_it_should_throw() { - ["ONE"] = "One", - ["TWO"] = "Two" - }; + // Arrange + Dictionary dictionary = null; - // Act - Action act = () => dictionary.Should().NotContainKeys(new[] { "One", "Two" }); + // Act + Action act = () => dictionary.Should() + .NotContainValue("One", "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary not to contain value \"One\" because we want to test the behaviour with a null subject, but found ."); + } - [Fact] - public void When_an_assertion_fails_on_ContainKey_succeeding_message_should_be_included() - { - // Act - Action act = () => + [Fact] + public void When_dictionary_does_not_contain_multiple_values_that_is_not_in_the_dictionary_it_should_not_throw() { - using var _ = new AssertionScope(); - var values = new Dictionary(); - values.Should().ContainKey(0); - values.Should().ContainKey(1); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected*to contain key 0*Expected*to contain key 1*"); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - #endregion + // Act + Action act = () => dictionary.Should().NotContainValues("Three", "Four"); - #region ContainValue + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_dictionary_contains_expected_value_it_should_succeed() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_contains_a_exactly_one_of_the_values_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().ContainValue("One"); + // Act + Action act = () => dictionary.Should().NotContainValues(new[] { "Two" }, "because {0}", "we do"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain value \"Two\" because we do."); + } - [Fact] - public void When_dictionary_contains_expected_null_value_it_should_succeed() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_contains_a_number_of_values_it_should_throw_with_clear_explanation() { - [1] = null - }; - - // Act - Action act = () => dictionary.Should().ContainValue(null); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => dictionary.Should().NotContainValues(new[] { "Two", "Three" }, "because {0}", "we do"); - [Fact] - public void When_the_specified_value_exists_it_should_allow_continuation_using_that_value() - { - // Arrange - var myClass = new MyClass() - { - SomeProperty = 0 - }; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain value {\"Two\", \"Three\"} because we do, but found {\"Two\"}."); + } - var dictionary = new Dictionary + [Fact] + public void When_the_noncontents_of_a_dictionary_are_checked_against_an_empty_list_of_values_it_should_throw_clear_explanation() { - [1] = myClass - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary.Should().ContainValue(myClass).Which.SomeProperty.Should().BeGreaterThan(0); + // Act + Action act = () => dictionary.Should().NotContainValues(new string[0]); - // Assert - act.Should().Throw().WithMessage("Expected*greater*0*0*"); + // Assert + act.Should().Throw().WithMessage( + "Cannot verify value containment with an empty sequence*"); + } } - [Fact] - public void When_multiple_matches_for_the_specified_value_exist_continuation_using_the_matched_value_should_fail() + public class Contain { - // Arrange - var myClass = new MyClass { SomeProperty = 0 }; + [Fact] + public void Should_succeed_when_asserting_dictionary_contains_single_key_value_pair() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = myClass, - [2] = new MyClass { SomeProperty = 0 } + new KeyValuePair(1, "One") }; - // Act - Action act = - () => - dictionary.Should() - .ContainValue(new MyClass { SomeProperty = 0 }) - .Which.Should() - .BeSameAs(myClass); - - // Assert - act.Should().Throw(); - } + // Act / Assert + dictionary.Should().Contain(keyValuePairs); + } - [Fact] - public void When_dictionary_contains_multiple_values_from_the_dictionary_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_contains_multiple_key_value_pair() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two", + [3] = "Three", + [4] = "Four" + }; - // Act - Action act = () => dictionary.Should().ContainValues("Two", "One"); + var expectedKeyValuePair1 = new KeyValuePair(2, "Two"); + var expectedKeyValuePair2 = new KeyValuePair(3, "Three"); - // Assert - act.Should().NotThrow(); - } + // Act / Assert + dictionary.Should().Contain(expectedKeyValuePair1, expectedKeyValuePair2); + } - [Fact] - public void When_a_dictionary_does_not_contain_single_value_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_contains_multiple_key_value_pairs() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().ContainValue("Three", "because {0}", "we do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain value \"Three\" because we do."); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_a_dictionary_does_not_contain_a_number_of_values_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(1, "One"), + new KeyValuePair(2, "Two") }; - // Act - Action act = () => dictionary.Should().ContainValues(new[] { "Two", "Three" }, "because {0}", "we do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain value {\"Two\", \"Three\"} because we do, but could not find {\"Three\"}."); - } + // Act / Assert + dictionary.Should().Contain(keyValuePairs); + } - [Fact] - public void When_the_contents_of_a_dictionary_are_checked_against_an_empty_list_of_values_it_should_throw_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_single_value_for_key_value_pairs_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().ContainValues(new string[0]); - - // Assert - act.Should().Throw().WithMessage( - "Cannot verify value containment with an empty sequence*"); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_dictionary_does_not_contain_a_value_that_is_not_in_the_dictionary_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(1, "One"), + new KeyValuePair(2, "Three") }; - // Act - Action act = () => dictionary.Should().NotContainValue("Three"); + // Act + Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain value \"Three\" at key 2 because we do, but found \"Two\"."); + } - [Fact] - public void When_dictionary_contains_an_unexpected_value_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_multiple_values_for_key_value_pairs_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().NotContainValue("One", "because we {0} like it", "don't"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} not to contain value \"One\" because we don't like it, but found it anyhow."); - } - - [Fact] - public void When_asserting_dictionary_does_not_contain_value_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; - - // Act - Action act = () => dictionary.Should() - .NotContainValue("One", "because we want to test the behaviour with a null subject"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary not to contain value \"One\" because we want to test the behaviour with a null subject, but found ."); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_dictionary_does_not_contain_multiple_values_that_is_not_in_the_dictionary_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(1, "Two"), + new KeyValuePair(2, "Three") }; - // Act - Action act = () => dictionary.Should().NotContainValues("Three", "Four"); + // Act + Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain {[1, Two], [2, Three]} because we do, but dictionary differs at keys {1, 2}."); + } - [Fact] - public void When_a_dictionary_contains_a_exactly_one_of_the_values_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_single_key_for_key_value_pairs_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().NotContainValues(new[] { "Two" }, "because {0}", "we do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain value \"Two\" because we do."); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_a_dictionary_contains_a_number_of_values_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(3, "Three") }; - // Act - Action act = () => dictionary.Should().NotContainValues(new[] { "Two", "Three" }, "because {0}", "we do"); + // Act + Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to not contain value {\"Two\", \"Three\"} because we do, but found {\"Two\"}."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key 3 because we do."); + } - [Fact] - public void When_the_noncontents_of_a_dictionary_are_checked_against_an_empty_list_of_values_it_should_throw_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_does_not_contain_multiple_keys_for_key_value_pairs_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().NotContainValues(new string[0]); - - // Assert - act.Should().Throw().WithMessage( - "Cannot verify value containment with an empty sequence*"); - } - - #endregion - - #region Contain + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void Should_succeed_when_asserting_dictionary_contains_single_key_value_pair() - { - // Arrange - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(1, "One"), + new KeyValuePair(3, "Three"), + new KeyValuePair(4, "Four") }; - var keyValuePairs = new List>() - { - new KeyValuePair(1, "One") - }; + // Act + Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); - // Act / Assert - dictionary.Should().Contain(keyValuePairs); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key(s) {1, 3, 4} because we do, but could not find keys {3, 4}."); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_contains_multiple_key_value_pair() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_contains_key_value_pairs_against_null_dictionary_it_should_throw() + { + // Arrange + Dictionary dictionary = null; + List> keyValuePairs = new List>() { - [1] = "One", - [2] = "Two", - [3] = "Three", - [4] = "Four" + new KeyValuePair(1, "One"), + new KeyValuePair(1, "Two") }; - var expectedKeyValuePair1 = new KeyValuePair(2, "Two"); - var expectedKeyValuePair2 = new KeyValuePair(3, "Three"); + // Act + Action act = () => dictionary.Should().Contain(keyValuePairs, + "because we want to test the behaviour with a null subject"); - // Act / Assert - dictionary.Should().Contain(expectedKeyValuePair1, expectedKeyValuePair2); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain key/value pairs {[1, One], [1, Two]} because we want to test the behaviour with a null subject, but dictionary is ."); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_does_not_contain_single_key_value_pair() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_contains_key_value_pairs_but_expected_key_value_pairs_are_empty_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + List> keyValuePairs = new List>(); - var keyValuePairs = new List>() - { - new KeyValuePair(3, "Three") - }; + // Act + Action act = () => dictionary1.Should().Contain(keyValuePairs, "because we want to test the behaviour with an empty set of key/value pairs"); - // Act / Assert - dictionary.Should().NotContain(keyValuePairs); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot verify key containment against an empty collection of key/value pairs*"); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_does_not_contain_multiple_key_value_pair() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_contains_key_value_pairs_but_expected_key_value_pairs_are_null_it_should_throw() { - [1] = "One", - [2] = "Two" - }; - - var unexpectedKeyValuePair1 = new KeyValuePair(3, "Three"); - var unexpectedKeyValuePair2 = new KeyValuePair(4, "Four"); - - // Act / Assert - dictionary.Should().NotContain(unexpectedKeyValuePair1, unexpectedKeyValuePair2); - } + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + List> keyValuePairs = null; + + // Act + Action act = () => dictionary1.Should().Contain(keyValuePairs, "because we want to test the behaviour with a null subject"); + + // Assert + act.Should().Throw() + .WithMessage("Cannot compare dictionary with .*") + .WithParameterName("expected"); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_does_not_contain_single_key_value_pair_with_existing_key_but_different_value() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_expected_value_at_specific_key_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + + // Act / Assert + dictionary.Should().Contain(1, "One"); + } - var keyValuePairs = new List>() + [Fact] + public void When_dictionary_contains_expected_null_at_specific_key_it_should_not_throw() { - new KeyValuePair(1, "Two") - }; + // Arrange + var dictionary = new Dictionary + { + [1] = null + }; - // Act / Assert - dictionary.Should().NotContain(keyValuePairs); - } + // Act / Assert + dictionary.Should().Contain(1, null); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_contains_multiple_key_value_pairs() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_expected_key_value_pairs_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - var keyValuePairs = new List>() + // Act / Assert + var items = new List>() { new KeyValuePair(1, "One"), new KeyValuePair(2, "Two") }; + dictionary.Should().Contain(items); + } - // Act / Assert - dictionary.Should().Contain(keyValuePairs); - } - - [Fact] - public void Should_succeed_when_asserting_dictionary_does_not_contain_multiple_key_value_pairs() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; - - var keyValuePairs = new List>() + [Fact] + public void When_dictionary_contains_expected_key_value_pair_it_should_not_throw() { - new KeyValuePair(3, "Three"), - new KeyValuePair(4, "Four") - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary.Should().NotContain(keyValuePairs); - } + // Act / Assert + var item = new KeyValuePair(1, "One"); + dictionary.Should().Contain(item); + } - [Fact] - public void Should_succeed_when_asserting_dictionary_does_not_contain_multiple_key_value_pairs_with_existing_keys_but_different_values() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_the_expected_value_at_specific_key_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - var keyValuePairs = new List>() - { - new KeyValuePair(1, "Three"), - new KeyValuePair(2, "Four") - }; + // Act + var item = new KeyValuePair(1, "Two"); + Action act = () => dictionary.Should().Contain(item, "we put it {0}", "there"); - // Act / Assert - dictionary.Should().NotContain(keyValuePairs); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain value \"Two\" at key 1 because we put it there, but found \"One\"."); + } - [Fact] - public void When_a_dictionary_does_not_contain_single_value_for_key_value_pairs_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_the_key_value_pairs_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - var keyValuePairs = new List>() + var items = new List>() { - new KeyValuePair(1, "One"), + new KeyValuePair(1, "Two"), new KeyValuePair(2, "Three") }; - // Act - Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain value \"Three\" at key 2 because we do, but found \"Two\"."); - } + // Act + Action act = () => dictionary.Should().Contain(items, "we put them {0}", "there"); - [Fact] - public void When_a_dictionary_does_not_contain_multiple_values_for_key_value_pairs_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain {[1, Two], [2, Three]} because we put them there, but dictionary differs at keys {1, 2}."); + } - var keyValuePairs = new List>() + [Fact] + public void When_dictionary_does_not_contain_the_key_value_pair_it_should_throw() { - new KeyValuePair(1, "Two"), - new KeyValuePair(2, "Three") - }; - - // Act - Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain {[1, Two], [2, Three]} because we do, but dictionary differs at keys {1, 2}."); - } + // Act + Action act = () => dictionary.Should().Contain(1, "Two", "we put it {0}", "there"); - [Fact] - public void When_a_dictionary_does_not_contain_single_key_for_key_value_pairs_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain value \"Two\" at key 1 because we put it there, but found \"One\"."); + } - var keyValuePairs = new List>() + [Fact] + public void When_dictionary_does_not_contain_an_value_at_the_specific_key_it_should_throw() { - new KeyValuePair(3, "Three") - }; - - // Act - Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key 3 because we do."); - } + // Act + Action act = () => dictionary.Should().Contain(3, "Two", "we put it {0}", "there"); - [Fact] - public void When_a_dictionary_does_not_contain_multiple_keys_for_key_value_pairs_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain value \"Two\" at key 3 because we put it there, but the key was not found."); + } - var keyValuePairs = new List>() + [Fact] + public void When_asserting_dictionary_contains_value_at_specific_key_against_null_dictionary_it_should_throw() { - new KeyValuePair(1, "One"), - new KeyValuePair(3, "Three"), - new KeyValuePair(4, "Four") - }; - - // Act - Action act = () => dictionary.Should().Contain(keyValuePairs, "because {0}", "we do"); + // Arrange + Dictionary dictionary = null; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary {[1] = \"One\", [2] = \"Two\"} to contain key(s) {1, 3, 4} because we do, but could not find keys {3, 4}."); - } + // Act + Action act = () => dictionary.Should().Contain(1, "One", + "because we want to test the behaviour with a null subject"); - [Fact] - public void When_a_dictionary_does_contain_single_key_value_pair_it_should_throw_with_clear_explanation() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to contain value \"One\" at key 1 because we want to test the behaviour with a null subject, but dictionary is ."); + } - var keyValuePairs = new List>() + [Fact] + public void When_a_dictionary_like_collection_contains_the_default_key_it_should_succeed() { - new KeyValuePair(1, "One") - }; + // Arrange + var subject = new List>() { new(0, 0) }; - // Act - Action act = () => dictionary.Should().NotContain(keyValuePairs, "because {0}", "we do"); + // Act + Action act = () => subject.Should().Contain(0, 0); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not contain value \"One\" at key 1 because we do, but found it anyhow."); + // Assert + act.Should().NotThrow(); + } } - [Fact] - public void When_a_dictionary_does_contain_multiple_key_value_pairs_it_should_throw_with_clear_explanation() + public class NotContain { - // Arrange - var dictionary = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_does_not_contain_single_key_value_pair() { - [1] = "One", - [2] = "Two" - }; - - var keyValuePairs = new List>() - { - new KeyValuePair(1, "One"), - new KeyValuePair(2, "Two") - }; - - // Act - Action act = () => dictionary.Should().NotContain(keyValuePairs, "because {0}", "we do"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not contain key/value pairs {[1, One], [2, Two]} because we do, but found them anyhow."); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_asserting_dictionary_contains_key_value_pairs_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; - List> keyValuePairs = new List>() + var keyValuePairs = new List>() { - new KeyValuePair(1, "One"), - new KeyValuePair(1, "Two") + new KeyValuePair(3, "Three") }; - // Act - Action act = () => dictionary.Should().Contain(keyValuePairs, - "because we want to test the behaviour with a null subject"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain key/value pairs {[1, One], [1, Two]} because we want to test the behaviour with a null subject, but dictionary is ."); - } + // Act / Assert + dictionary.Should().NotContain(keyValuePairs); + } - [Fact] - public void When_asserting_dictionary_contains_key_value_pairs_but_expected_key_value_pairs_are_empty_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_does_not_contain_multiple_key_value_pair() { - [1] = "One", - [2] = "Two" - }; - List> keyValuePairs = new List>(); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action act = () => dictionary1.Should().Contain(keyValuePairs, "because we want to test the behaviour with an empty set of key/value pairs"); + var unexpectedKeyValuePair1 = new KeyValuePair(3, "Three"); + var unexpectedKeyValuePair2 = new KeyValuePair(4, "Four"); - // Assert - act.Should().Throw().WithMessage( - "Cannot verify key containment against an empty collection of key/value pairs*"); - } + // Act / Assert + dictionary.Should().NotContain(unexpectedKeyValuePair1, unexpectedKeyValuePair2); + } - [Fact] - public void When_asserting_dictionary_contains_key_value_pairs_but_expected_key_value_pairs_are_null_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary + [Fact] + public void Should_succeed_when_asserting_dictionary_does_not_contain_single_key_value_pair_with_existing_key_but_different_value() { - [1] = "One", - [2] = "Two" - }; - List> keyValuePairs = null; - - // Act - Action act = () => dictionary1.Should().Contain(keyValuePairs, "because we want to test the behaviour with a null subject"); - - // Assert - act.Should().Throw() - .WithMessage("Cannot compare dictionary with .*") - .WithParameterName("expected"); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_asserting_dictionary_does_not_contain_key_value_pairs_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; - List> keyValuePairs = new List>() + var keyValuePairs = new List>() { - new KeyValuePair(1, "One"), new KeyValuePair(1, "Two") }; - // Act - Action act = () => dictionary.Should().NotContain(keyValuePairs, - "because we want to test the behaviour with a null subject"); + // Act / Assert + dictionary.Should().NotContain(keyValuePairs); + } - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not contain key/value pairs {[1, One], [1, Two]} because we want to test the behaviour with a null subject, but dictionary is ."); - } + [Fact] + public void Should_succeed_when_asserting_dictionary_does_not_contain_multiple_key_value_pairs() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_asserting_dictionary_does_not_contain_key_value_pairs_but_expected_key_value_pairs_are_empty_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(3, "Three"), + new KeyValuePair(4, "Four") }; - List> keyValuePair = new List>(); - // Act - Action act = () => dictionary1.Should().NotContain(keyValuePair, "because we want to test the behaviour with an empty set of key/value pairs"); + // Act / Assert + dictionary.Should().NotContain(keyValuePairs); + } - // Assert - act.Should().Throw().WithMessage( - "Cannot verify key containment against an empty collection of key/value pairs*"); - } + [Fact] + public void Should_succeed_when_asserting_dictionary_does_not_contain_multiple_key_value_pairs_with_existing_keys_but_different_values() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_asserting_dictionary_does_not_contain_key_value_pairs_but_expected_key_value_pairs_are_null_it_should_throw() - { - // Arrange - var dictionary1 = new Dictionary + var keyValuePairs = new List>() { - [1] = "One", - [2] = "Two" + new KeyValuePair(1, "Three"), + new KeyValuePair(2, "Four") }; - List> keyValuePairs = null; - - // Act - Action act = () => dictionary1.Should().NotContain(keyValuePairs, "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw() - .WithMessage("Cannot compare dictionary with .*") - .WithParameterName("items"); - } + // Act / Assert + dictionary.Should().NotContain(keyValuePairs); + } - [Fact] - public void When_dictionary_contains_expected_value_at_specific_key_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_a_dictionary_does_contain_single_key_value_pair_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; - - // Act / Assert - dictionary.Should().Contain(1, "One"); - } + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - [Fact] - public void When_dictionary_contains_expected_null_at_specific_key_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + var keyValuePairs = new List>() { - [1] = null + new KeyValuePair(1, "One") }; - // Act / Assert - dictionary.Should().Contain(1, null); - } + // Act + Action act = () => dictionary.Should().NotContain(keyValuePairs, "because {0}", "we do"); - [Fact] - public void When_dictionary_contains_expected_key_value_pairs_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not contain value \"One\" at key 1 because we do, but found it anyhow."); + } + + [Fact] + public void When_a_dictionary_does_contain_multiple_key_value_pairs_it_should_throw_with_clear_explanation() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - var items = new List>() + var keyValuePairs = new List>() { new KeyValuePair(1, "One"), new KeyValuePair(2, "Two") }; - dictionary.Should().Contain(items); - } - [Fact] - public void When_dictionary_contains_expected_key_value_pair_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Act + Action act = () => dictionary.Should().NotContain(keyValuePairs, "because {0}", "we do"); - // Act / Assert - var item = new KeyValuePair(1, "One"); - dictionary.Should().Contain(item); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not contain key/value pairs {[1, One], [2, Two]} because we do, but found them anyhow."); + } - [Fact] - public void When_dictionary_does_not_contain_the_expected_value_at_specific_key_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_does_not_contain_key_value_pairs_against_null_dictionary_it_should_throw() { - [1] = "One", - [2] = "Two" - }; - - // Act - var item = new KeyValuePair(1, "Two"); - Action act = () => dictionary.Should().Contain(item, "we put it {0}", "there"); + // Arrange + Dictionary dictionary = null; + List> keyValuePairs = new List>() + { + new KeyValuePair(1, "One"), + new KeyValuePair(1, "Two") + }; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain value \"Two\" at key 1 because we put it there, but found \"One\"."); - } + // Act + Action act = () => dictionary.Should().NotContain(keyValuePairs, + "because we want to test the behaviour with a null subject"); - [Fact] - public void When_dictionary_does_not_contain_the_key_value_pairs_it_should_throw() - { - // Arrange - var dictionary = new Dictionary - { - [1] = "One", - [2] = "Two" - }; + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not contain key/value pairs {[1, One], [1, Two]} because we want to test the behaviour with a null subject, but dictionary is ."); + } - var items = new List>() + [Fact] + public void When_asserting_dictionary_does_not_contain_key_value_pairs_but_expected_key_value_pairs_are_empty_it_should_throw() { - new KeyValuePair(1, "Two"), - new KeyValuePair(2, "Three") - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + List> keyValuePair = new List>(); - // Act - Action act = () => dictionary.Should().Contain(items, "we put them {0}", "there"); + // Act + Action act = () => dictionary1.Should().NotContain(keyValuePair, "because we want to test the behaviour with an empty set of key/value pairs"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain {[1, Two], [2, Three]} because we put them there, but dictionary differs at keys {1, 2}."); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot verify key containment against an empty collection of key/value pairs*"); + } - [Fact] - public void When_dictionary_does_not_contain_the_key_value_pair_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_asserting_dictionary_does_not_contain_key_value_pairs_but_expected_key_value_pairs_are_null_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary1 = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + List> keyValuePairs = null; + + // Act + Action act = () => dictionary1.Should().NotContain(keyValuePairs, "because we want to test the behaviour with a null subject"); + + // Assert + act.Should().Throw() + .WithMessage("Cannot compare dictionary with .*") + .WithParameterName("items"); + } - // Act - Action act = () => dictionary.Should().Contain(1, "Two", "we put it {0}", "there"); + [Fact] + public void When_dictionary_does_not_contain_unexpected_value_or_key_it_should_not_throw() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain value \"Two\" at key 1 because we put it there, but found \"One\"."); - } + // Act / Assert + dictionary.Should().NotContain(3, "Three"); + } - [Fact] - public void When_dictionary_does_not_contain_an_value_at_the_specific_key_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_unexpected_value_at_existing_key_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().Contain(3, "Two", "we put it {0}", "there"); + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain value \"Two\" at key 3 because we put it there, but the key was not found."); - } + // Act / Assert + dictionary.Should().NotContain(2, "Three"); + } - [Fact] - public void When_asserting_dictionary_contains_value_at_specific_key_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; + [Fact] + public void When_dictionary_does_not_have_the_unexpected_value_but_null_at_existing_key_it_should_succeed() + { + // Arrange + var dictionary = new Dictionary + { + [1] = null + }; - // Act - Action act = () => dictionary.Should().Contain(1, "One", - "because we want to test the behaviour with a null subject"); + // Act + Action action = () => dictionary.Should().NotContain(1, "other"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to contain value \"One\" at key 1 because we want to test the behaviour with a null subject, but dictionary is ."); - } + // Assert + action.Should().NotThrow(); + } - [Fact] - public void When_dictionary_does_not_contain_unexpected_value_or_key_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_unexpected_key_value_pairs_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary.Should().NotContain(3, "Three"); - } + // Act / Assert + var items = new List>() + { + new KeyValuePair(3, "Three"), + new KeyValuePair(4, "Four") + }; + dictionary.Should().NotContain(items); + } - [Fact] - public void When_dictionary_does_not_contain_unexpected_value_at_existing_key_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_does_not_contain_unexpected_key_value_pair_it_should_not_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - dictionary.Should().NotContain(2, "Three"); - } + // Act / Assert + var item = new KeyValuePair(3, "Three"); + dictionary.Should().NotContain(item); + } - [Fact] - public void When_dictionary_does_not_have_the_unexpected_value_but_null_at_existing_key_it_should_succeed() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_the_unexpected_value_at_specific_key_it_should_throw() { - [1] = null - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act - Action action = () => dictionary.Should().NotContain(1, "other"); + // Act + var item = new KeyValuePair(1, "One"); + Action act = () => dictionary.Should().NotContain(item, "we put it {0}", "there"); - // Assert - action.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary not to contain value \"One\" at key 1 because we put it there, but found it anyhow."); + } - [Fact] - public void When_dictionary_does_not_contain_unexpected_key_value_pairs_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_the_key_value_pairs_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - var items = new List>() - { - new KeyValuePair(3, "Three"), - new KeyValuePair(4, "Four") - }; - dictionary.Should().NotContain(items); - } + // Act + var items = new List>() + { + new KeyValuePair(1, "One"), + new KeyValuePair(2, "Two") + }; + Action act = () => dictionary.Should().NotContain(items, "we did not put them {0}", "there"); + + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary to not contain key/value pairs {[1, One], [2, Two]} because we did not put them there, but found them anyhow."); + } - [Fact] - public void When_dictionary_does_not_contain_unexpected_key_value_pair_it_should_not_throw() - { - // Arrange - var dictionary = new Dictionary + [Fact] + public void When_dictionary_contains_the_key_value_pair_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; - // Act / Assert - var item = new KeyValuePair(3, "Three"); - dictionary.Should().NotContain(item); - } + // Act + Action act = () => dictionary.Should().NotContain(1, "One", "we did not put it {0}", "there"); - [Fact] - public void When_dictionary_contains_the_unexpected_value_at_specific_key_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary not to contain value \"One\" at key 1 because we did not put it there, but found it anyhow."); + } + + [Fact] + public void When_asserting_dictionary_does_not_contain_value_at_specific_key_against_null_dictionary_it_should_throw() { - [1] = "One", - [2] = "Two" - }; + // Arrange + Dictionary dictionary = null; - // Act - var item = new KeyValuePair(1, "One"); - Action act = () => dictionary.Should().NotContain(item, "we put it {0}", "there"); + // Act + Action act = () => dictionary.Should().NotContain(1, "One", + "because we want to test the behaviour with a null subject"); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary not to contain value \"One\" at key 1 because we put it there, but found it anyhow."); + // Assert + act.Should().Throw().WithMessage( + "Expected dictionary not to contain value \"One\" at key 1 because we want to test the behaviour with a null subject, but dictionary is ."); + } } - [Fact] - public void When_dictionary_contains_the_key_value_pairs_it_should_throw() + public class OtherDictionaryAssertions { - // Arrange - var dictionary = new Dictionary + [Theory] + [MemberData(nameof(SingleDictionaryData))] + public void When_a_dictionary_like_collection_contains_the_expected_key_and_value_it_should_succeed(T subject) + where T : IEnumerable> { - [1] = "One", - [2] = "Two" - }; + // Assert + subject.Should().Contain(1, 42); + } - // Act - var items = new List>() + [Theory] + [MemberData(nameof(SingleDictionaryData))] + public void When_using_a_dictionary_like_collection_it_should_preserve_reference_equality(T subject) + where T : IEnumerable> { - new KeyValuePair(1, "One"), - new KeyValuePair(2, "Two") - }; - Action act = () => dictionary.Should().NotContain(items, "we did not put them {0}", "there"); + // Act + Action act = () => subject.Should().BeSameAs(subject); - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary to not contain key/value pairs {[1, One], [2, Two]} because we did not put them there, but found them anyhow."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_dictionary_contains_the_key_value_pair_it_should_throw() - { - // Arrange - var dictionary = new Dictionary + [Theory] + [MemberData(nameof(SingleDictionaryData))] + public void When_a_dictionary_like_collection_contains_the_expected_key_it_should_succeed(T subject) + where T : IEnumerable> { - [1] = "One", - [2] = "Two" - }; - - // Act - Action act = () => dictionary.Should().NotContain(1, "One", "we did not put it {0}", "there"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary not to contain value \"One\" at key 1 because we did not put it there, but found it anyhow."); - } - - [Fact] - public void When_asserting_dictionary_does_not_contain_value_at_specific_key_against_null_dictionary_it_should_throw() - { - // Arrange - Dictionary dictionary = null; - - // Act - Action act = () => dictionary.Should().NotContain(1, "One", - "because we want to test the behaviour with a null subject"); - - // Assert - act.Should().Throw().WithMessage( - "Expected dictionary not to contain value \"One\" at key 1 because we want to test the behaviour with a null subject, but dictionary is ."); - } - - #endregion + // Act + Action act = () => subject.Should().ContainKey(1); - #region Miscellaneous + // Assert + act.Should().NotThrow(); + } - [Fact] - public void Should_support_chaining_constraints_with_and() - { - // Arrange - var dictionary = new Dictionary + [Theory] + [MemberData(nameof(SingleDictionaryData))] + public void When_a_dictionary_like_collection_contains_the_expected_value_it_should_succeed(T subject) + where T : IEnumerable> { - [1] = "One", - [2] = "Two" - }; - - // Act / Assert - dictionary.Should() - .HaveCount(2) - .And.ContainKey(1) - .And.ContainValue("Two"); - } - - #endregion - - [Theory] - [MemberData(nameof(DictionariesData))] - public void When_comparing_dictionary_like_collections_for_equality_it_should_succeed(T1 subject, T2 expected) - where T1 : IEnumerable> - where T2 : IEnumerable> - { - // Act - Action act = () => subject.Should().Equal(expected); - - // Assert - act.Should().NotThrow(); - } - - [Theory] - [MemberData(nameof(DictionariesData))] - public void When_comparing_dictionary_like_collections_for_inequality_it_should_throw(T1 subject, T2 expected) - where T1 : IEnumerable> - where T2 : IEnumerable> - { - // Act - Action act = () => subject.Should().NotEqual(expected); - - // Assert - act.Should().Throw(); - } - - public static IEnumerable DictionariesData() - { - return from x in Dictionaries() - from y in Dictionaries() - select new[] { x, y }; - } - - [Theory] - [MemberData(nameof(SingleDictionaryData))] - public void When_a_dictionary_like_collection_contains_the_expected_key_it_should_succeed(T subject) - where T : IEnumerable> - { - // Act - Action act = () => subject.Should().ContainKey(1); - - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => subject.Should().ContainValue(42); - [Theory] - [MemberData(nameof(SingleDictionaryData))] - public void When_a_dictionary_like_collection_contains_the_expected_key_and_value_it_should_succeed(T subject) - where T : IEnumerable> - { - // Assert - subject.Should().Contain(1, 42); - } + // Assert + act.Should().NotThrow(); + } - [Theory] - [MemberData(nameof(SingleDictionaryData))] - public void When_a_dictionary_like_collection_contains_the_expected_value_it_should_succeed(T subject) - where T : IEnumerable> - { - // Act - Action act = () => subject.Should().ContainValue(42); + [Theory] + [MemberData(nameof(DictionariesData))] + public void When_comparing_dictionary_like_collections_for_equality_it_should_succeed(T1 subject, T2 expected) + where T1 : IEnumerable> + where T2 : IEnumerable> + { + // Act + Action act = () => subject.Should().Equal(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Theory] - [MemberData(nameof(SingleDictionaryData))] - public void When_using_a_dictionary_like_collection_it_should_preserve_reference_equality(T subject) - where T : IEnumerable> - { - // Act - Action act = () => subject.Should().BeSameAs(subject); + [Theory] + [MemberData(nameof(DictionariesData))] + public void When_comparing_dictionary_like_collections_for_inequality_it_should_throw(T1 subject, T2 expected) + where T1 : IEnumerable> + where T2 : IEnumerable> + { + // Act + Action act = () => subject.Should().NotEqual(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw(); + } - public static IEnumerable SingleDictionaryData() => - Dictionaries().Select(x => new[] { x }); + public static IEnumerable SingleDictionaryData() => + Dictionaries().Select(x => new[] { x }); - private static object[] Dictionaries() - { - return new object[] + public static object[] Dictionaries() { + return new object[] + { new Dictionary() { [1] = 42 }, new TrueReadOnlyDictionary(new Dictionary() { [1] = 42 }), new List> { new KeyValuePair(1, 42) } - }; + }; + } + + public static IEnumerable DictionariesData() + { + return from x in Dictionaries() + from y in Dictionaries() + select new[] { x, y }; + } } - [Fact] - public void When_a_dictionary_like_collection_contains_the_default_key_it_should_succeed() + public class Miscellaneous { - // Arrange - var subject = new List>() { new(0, 0) }; - - // Act - Action act = () => subject.Should().Contain(0, 0); - - // Assert - act.Should().NotThrow(); + [Fact] + public void Should_support_chaining_constraints_with_and() + { + // Arrange + var dictionary = new Dictionary + { + [1] = "One", + [2] = "Two" + }; + + // Act / Assert + dictionary.Should() + .HaveCount(2) + .And.ContainKey(1) + .And.ContainValue("Two"); + } } /// From 083921a0f1cbba0e5b20443a67e96335998c5c75 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Fri, 22 Apr 2022 15:35:47 +0200 Subject: [PATCH 36/48] Seperate all `Event` assertions into nested classes --- .../Events/EventAssertionSpecs.cs | 1321 ++++++++--------- 1 file changed, 660 insertions(+), 661 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs index f07bc28c78..871bb98455 100644 --- a/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs @@ -17,798 +17,797 @@ namespace FluentAssertions.Specs.Events [Collection("EventMonitoring")] public class EventAssertionSpecs { - #region ShouldRaise - - [Fact] - public void When_asserting_an_event_that_doesnt_exist_it_should_throw() + public class ShouldRaise { - // Arrange - var subject = new EventRaisingClass(); - using var monitoredSubject = subject.Monitor(); + [Fact] + public void When_asserting_an_event_that_doesnt_exist_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitoredSubject = subject.Monitor(); - // Act - // ReSharper disable once AccessToDisposedClosure - Action act = () => monitoredSubject.Should().Raise("NonExistingEvent"); + // Act + // ReSharper disable once AccessToDisposedClosure + Action act = () => monitoredSubject.Should().Raise("NonExistingEvent"); - // Assert - act.Should().Throw().WithMessage( - "Not monitoring any events named \"NonExistingEvent\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Not monitoring any events named \"NonExistingEvent\"."); + } - [Fact] - public void When_asserting_that_an_event_was_not_raised_and_it_doesnt_exist_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); + [Fact] + public void When_asserting_that_an_event_was_not_raised_and_it_doesnt_exist_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); - // Act - Action act = () => monitor.Should().NotRaise("NonExistingEvent"); + // Act + Action act = () => monitor.Should().NotRaise("NonExistingEvent"); - // Assert - act.Should().Throw().WithMessage( - "Not monitoring any events named \"NonExistingEvent\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Not monitoring any events named \"NonExistingEvent\"."); + } - [Fact] - public void When_an_event_was_not_raised_it_should_throw_and_use_the_reason() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); + [Fact] + public void When_an_event_was_not_raised_it_should_throw_and_use_the_reason() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); - // Act - Action act = () => monitor.Should().Raise("PropertyChanged", "{0} should cause the event to get raised", "Foo()"); + // Act + Action act = () => monitor.Should().Raise("PropertyChanged", "{0} should cause the event to get raised", "Foo()"); - // Assert - act.Should().Throw().WithMessage( - "Expected object " + Formatter.ToString(subject) + - " to raise event \"PropertyChanged\" because Foo() should cause the event to get raised, but it did not."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected object " + Formatter.ToString(subject) + + " to raise event \"PropertyChanged\" because Foo() should cause the event to get raised, but it did not."); + } - [Fact] - public void When_the_expected_event_was_raised_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithoutSender(); + [Fact] + public void When_the_expected_event_was_raised_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithoutSender(); - // Act - Action act = () => monitor.Should().Raise("PropertyChanged"); + // Act + Action act = () => monitor.Should().Raise("PropertyChanged"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_an_unexpected_event_was_raised_it_should_throw_and_use_the_reason() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithoutSender(); - - // Act - Action act = () => - monitor.Should().NotRaise("PropertyChanged", "{0} should cause the event to get raised", "Foo()"); - - // Assert - act.Should().Throw() - .WithMessage("Expected object " + Formatter.ToString(subject) + - " to not raise event \"PropertyChanged\" because Foo() should cause the event to get raised, but it did."); - } + [Fact] + public void When_an_unexpected_event_was_raised_it_should_throw_and_use_the_reason() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithoutSender(); - [Fact] - public void When_an_unexpected_event_was_not_raised_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); + // Act + Action act = () => + monitor.Should().NotRaise("PropertyChanged", "{0} should cause the event to get raised", "Foo()"); - // Act - Action act = () => monitor.Should().NotRaise("PropertyChanged"); + // Assert + act.Should().Throw() + .WithMessage("Expected object " + Formatter.ToString(subject) + + " to not raise event \"PropertyChanged\" because Foo() should cause the event to get raised, but it did."); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_an_unexpected_event_was_not_raised_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); - [Fact] - public void When_the_event_sender_is_not_the_expected_object_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithoutSender(); + // Act + Action act = () => monitor.Should().NotRaise("PropertyChanged"); - // Act - Action act = () => monitor.Should().Raise("PropertyChanged").WithSender(subject); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw() - .WithMessage($"Expected sender {Formatter.ToString(subject)}, but found {{}}."); - } + [Fact] + public void When_the_event_sender_is_not_the_expected_object_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithoutSender(); - [Fact] - public void When_the_event_sender_is_the_expected_object_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSender(); + // Act + Action act = () => monitor.Should().Raise("PropertyChanged").WithSender(subject); - // Act - Action act = () => monitor.Should().Raise("PropertyChanged").WithSender(subject); + // Assert + act.Should().Throw() + .WithMessage($"Expected sender {Formatter.ToString(subject)}, but found {{}}."); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_the_event_sender_is_the_expected_object_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSender(); - [Fact] - public void When_injecting_a_null_predicate_into_WithArgs_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - - // Act - Action act = () => monitor.Should() - .Raise("NonConventionalEvent") - .WithArgs(predicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("predicate"); - } + // Act + Action act = () => monitor.Should().Raise("PropertyChanged").WithSender(subject); - [Fact] - public void When_the_event_parameters_dont_match_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithoutSender(); - - // Act - Action act = () => monitor - .Should().Raise("PropertyChanged") - .WithArgs(args => args.PropertyName == "SomeProperty"); - - // Assert - act - .Should().Throw() - .WithMessage( - "Expected at least one event with arguments matching (args.PropertyName == \"SomeProperty\"), but found none."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_event_args_are_of_a_different_type_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - - // Act - Action act = () => monitor - .Should().Raise("PropertyChanged") - .WithArgs(args => args.Cancel); - - // Assert - act - .Should().Throw() - .WithMessage("No argument of event PropertyChanged is of type *CancelEventArgs>*"); - } + [Fact] + public void When_injecting_a_null_predicate_into_WithArgs_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - [Fact] - public void When_the_event_parameters_do_match_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - - // Act - Action act = () => monitor - .Should().Raise("PropertyChanged") - .WithArgs(args => args.PropertyName == "SomeProperty"); - - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => monitor.Should() + .Raise("NonConventionalEvent") + .WithArgs(predicate: null); - [Fact] - public void When_running_in_parallel_it_should_not_throw() - { - // Arrange - void Action(int _) + // Assert + act.Should().ThrowExactly() + .WithParameterName("predicate"); + } + + [Fact] + public void When_the_event_parameters_dont_match_it_should_throw() { - EventRaisingClass subject = new EventRaisingClass(); + // Arrange + var subject = new EventRaisingClass(); using var monitor = subject.Monitor(); - subject.RaiseEventWithSender(); - monitor.Should().Raise("PropertyChanged"); + subject.RaiseEventWithoutSender(); + + // Act + Action act = () => monitor + .Should().Raise("PropertyChanged") + .WithArgs(args => args.PropertyName == "SomeProperty"); + + // Assert + act + .Should().Throw() + .WithMessage( + "Expected at least one event with arguments matching (args.PropertyName == \"SomeProperty\"), but found none."); } - // Act - Action act = () => Enumerable.Range(0, 1000) - .AsParallel() - .ForAll(Action); + [Fact] + public void When_the_event_args_are_of_a_different_type_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => monitor + .Should().Raise("PropertyChanged") + .WithArgs(args => args.Cancel); - [Fact] - public void When_a_monitored_class_event_has_fired_it_should_be_possible_to_reset_the_event_monitor() - { - // Arrange - var subject = new EventRaisingClass(); - using var eventMonitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); + // Assert + act + .Should().Throw() + .WithMessage("No argument of event PropertyChanged is of type *CancelEventArgs>*"); + } - // Act - eventMonitor.Clear(); + [Fact] + public void When_the_event_parameters_do_match_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - // Assert - eventMonitor.Should().NotRaise("PropertyChanged"); - } + // Act + Action act = () => monitor + .Should().Raise("PropertyChanged") + .WithArgs(args => args.PropertyName == "SomeProperty"); - [Fact] - public void When_a_non_conventional_event_with_a_specific_argument_was_raised_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - - // Act - Action act = () => monitor - .Should().Raise("NonConventionalEvent") - .WithArgs(args => args == "third argument"); - - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_non_conventional_event_with_many_specific_arguments_was_raised_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - - // Act - Action act = () => monitor - .Should().Raise("NonConventionalEvent") - .WithArgs(null, args => args == "third argument"); - - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_running_in_parallel_it_should_not_throw() + { + // Arrange + void Action(int _) + { + EventRaisingClass subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSender(); + monitor.Should().Raise("PropertyChanged"); + } - [Fact] - public void When_a_predicate_based_parameter_assertion_expects_more_parameters_then_an_event_has_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - - // Act - Action act = () => monitor - .Should().Raise(nameof(EventRaisingClass.NonConventionalEvent)) - .WithArgs(null, null, null, args => args == "fourth argument"); - - // Assert - act.Should().Throw().WithMessage("*4 parameters*String*, but*2*"); - } + // Act + Action act = () => Enumerable.Range(0, 1000) + .AsParallel() + .ForAll(Action); - [Fact] - public void When_a_non_conventional_event_with_a_specific_argument_was_not_raised_it_should_throw() - { - // Arrange - const int wrongArgument = 3; - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - - // Act - Action act = () => monitor - .Should().Raise("NonConventionalEvent") - .WithArgs(args => args == wrongArgument); - - // Assert - act.Should().Throw().WithMessage( - "Expected at least one event with arguments matching (args == " + wrongArgument + "), but found none."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_non_conventional_event_with_many_specific_arguments_was_not_raised_it_should_throw() - { - // Arrange - const string wrongArgument = "not a third argument"; - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - - // Act - Action act = () => monitor - .Should().Raise("NonConventionalEvent") - .WithArgs(null, args => args == wrongArgument); - - // Assert - act.Should().Throw().WithMessage( - "Expected at least one event with arguments matching \"(args == \"" + wrongArgument + - "\")\", but found none."); - } + [Fact] + public void When_a_monitored_class_event_has_fired_it_should_be_possible_to_reset_the_event_monitor() + { + // Arrange + var subject = new EventRaisingClass(); + using var eventMonitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - [Fact] - public void When_a_specific_event_is_expected_it_should_return_only_relevant_events() - { - // Arrange - var observable = new EventRaisingClass(); - using var monitor = observable.Monitor(); - - // Act - observable.RaiseEventWithSpecificSender("Foo"); - observable.RaiseEventWithSpecificSender("Bar"); - observable.RaiseNonConventionalEvent("don't care", 123, "don't care"); - - // Assert - var recording = monitor - .Should() - .Raise(nameof(observable.PropertyChanged)); - - recording.EventName.Should().Be(nameof(observable.PropertyChanged)); - recording.EventObject.Should().BeSameAs(observable); - recording.EventHandlerType.Should().Be(typeof(PropertyChangedEventHandler)); - recording.Should().HaveCount(2, "because only two property changed events were raised"); - } + // Act + eventMonitor.Clear(); - [Fact] - public void When_a_specific_sender_is_expected_it_should_return_only_relevant_events() - { - // Arrange - var observable = new EventRaisingClass(); - using var monitor = observable.Monitor(); + // Assert + eventMonitor.Should().NotRaise("PropertyChanged"); + } - // Act - observable.RaiseEventWithSpecificSender(observable); - observable.RaiseEventWithSpecificSender(new object()); + [Fact] + public void When_a_non_conventional_event_with_a_specific_argument_was_raised_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - // Assert - var recording = monitor - .Should() - .Raise(nameof(observable.PropertyChanged)) - .WithSender(observable); + // Act + Action act = () => monitor + .Should().Raise("NonConventionalEvent") + .WithArgs(args => args == "third argument"); - recording.Should().ContainSingle().Which.Parameters.First().Should().BeSameAs(observable); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_constraints_are_specified_it_should_filter_the_events_based_on_those_constraints() - { - // Arrange - var observable = new EventRaisingClass(); - using var monitor = observable.Monitor(); - - // Act - observable.RaiseEventWithSenderAndPropertyName("Foo"); - observable.RaiseEventWithSenderAndPropertyName("Boo"); - - // Assert - var recording = monitor - .Should() - .Raise(nameof(observable.PropertyChanged)) - .WithSender(observable) - .WithArgs(args => args.PropertyName == "Boo"); - - recording - .Should().ContainSingle("because we were expecting a specific property change") - .Which.Parameters.Last().Should().BeOfType() - .Which.PropertyName.Should().Be("Boo"); - } + [Fact] + public void When_a_non_conventional_event_with_many_specific_arguments_was_raised_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - [Fact] - public void When_events_are_raised_regardless_of_time_tick_it_should_return_by_invokation_order() - { - // Arrange - var observable = new TestEventRaisingInOrder(); - var utcNow = 11.January(2022).At(12, 00).AsUtc(); - using var monitor = observable.Monitor(() => utcNow); + // Act + Action act = () => monitor + .Should().Raise("NonConventionalEvent") + .WithArgs(null, args => args == "third argument"); - // Act - observable.RaiseAllEvents(); + // Assert + act.Should().NotThrow(); + } - // Assert - monitor.OccurredEvents[0].EventName.Should().Be(nameof(TestEventRaisingInOrder.InterfaceEvent)); - monitor.OccurredEvents[0].Sequence.Should().Be(0); + [Fact] + public void When_a_predicate_based_parameter_assertion_expects_more_parameters_then_an_event_has_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - monitor.OccurredEvents[1].EventName.Should().Be(nameof(TestEventRaisingInOrder.Interface2Event)); - monitor.OccurredEvents[1].Sequence.Should().Be(1); + // Act + Action act = () => monitor + .Should().Raise(nameof(EventRaisingClass.NonConventionalEvent)) + .WithArgs(null, null, null, args => args == "fourth argument"); - monitor.OccurredEvents[2].EventName.Should().Be(nameof(TestEventRaisingInOrder.Interface3Event)); - monitor.OccurredEvents[2].Sequence.Should().Be(2); - } + // Assert + act.Should().Throw().WithMessage("*4 parameters*String*, but*2*"); + } - #endregion + [Fact] + public void When_a_non_conventional_event_with_a_specific_argument_was_not_raised_it_should_throw() + { + // Arrange + const int wrongArgument = 3; + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - #region Should(Not)RaisePropertyChanged events + // Act + Action act = () => monitor + .Should().Raise("NonConventionalEvent") + .WithArgs(args => args == wrongArgument); - [Fact] - public void When_a_property_changed_event_was_raised_for_the_expected_property_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - subject.RaiseEventWithSenderAndPropertyName("SomeOtherProperty"); + // Assert + act.Should().Throw().WithMessage( + "Expected at least one event with arguments matching (args == " + wrongArgument + "), but found none."); + } - // Act - Action act = () => monitor.Should().RaisePropertyChangeFor(x => x.SomeProperty); + [Fact] + public void When_a_non_conventional_event_with_many_specific_arguments_was_not_raised_it_should_throw() + { + // Arrange + const string wrongArgument = "not a third argument"; + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseNonConventionalEvent("first argument", 2, "third argument"); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => monitor + .Should().Raise("NonConventionalEvent") + .WithArgs(null, args => args == wrongArgument); - [Fact] - public void When_an_expected_property_changed_event_was_raised_for_all_properties_it_should_not_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName(null); + // Assert + act.Should().Throw().WithMessage( + "Expected at least one event with arguments matching \"(args == \"" + wrongArgument + + "\")\", but found none."); + } - // Act - Action act = () => monitor.Should().RaisePropertyChangeFor(null); + [Fact] + public void When_a_specific_event_is_expected_it_should_return_only_relevant_events() + { + // Arrange + var observable = new EventRaisingClass(); + using var monitor = observable.Monitor(); + + // Act + observable.RaiseEventWithSpecificSender("Foo"); + observable.RaiseEventWithSpecificSender("Bar"); + observable.RaiseNonConventionalEvent("don't care", 123, "don't care"); + + // Assert + var recording = monitor + .Should() + .Raise(nameof(observable.PropertyChanged)); + + recording.EventName.Should().Be(nameof(observable.PropertyChanged)); + recording.EventObject.Should().BeSameAs(observable); + recording.EventHandlerType.Should().Be(typeof(PropertyChangedEventHandler)); + recording.Should().HaveCount(2, "because only two property changed events were raised"); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_a_specific_sender_is_expected_it_should_return_only_relevant_events() + { + // Arrange + var observable = new EventRaisingClass(); + using var monitor = observable.Monitor(); - [Fact] - public void When_a_property_changed_event_was_raised_by_monitored_class_it_should_be_possible_to_reset_the_event_monitor() - { - // Arrange - var subject = new EventRaisingClass(); - using var eventMonitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); + // Act + observable.RaiseEventWithSpecificSender(observable); + observable.RaiseEventWithSpecificSender(new object()); - // Act - eventMonitor.Clear(); + // Assert + var recording = monitor + .Should() + .Raise(nameof(observable.PropertyChanged)) + .WithSender(observable); - // Assert - eventMonitor.Should().NotRaisePropertyChangeFor(e => e.SomeProperty); - } + recording.Should().ContainSingle().Which.Parameters.First().Should().BeSameAs(observable); + } - [Fact] - public void When_a_property_changed_event_for_an_unexpected_property_was_raised_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - - // Act - Action act = () => monitor.Should().NotRaisePropertyChangeFor(x => x.SomeProperty, "nothing happened"); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect object " + Formatter.ToString(subject) + - " to raise the \"PropertyChanged\" event for property \"SomeProperty\" because nothing happened, but it did."); - } + [Fact] + public void When_constraints_are_specified_it_should_filter_the_events_based_on_those_constraints() + { + // Arrange + var observable = new EventRaisingClass(); + using var monitor = observable.Monitor(); + + // Act + observable.RaiseEventWithSenderAndPropertyName("Foo"); + observable.RaiseEventWithSenderAndPropertyName("Boo"); + + // Assert + var recording = monitor + .Should() + .Raise(nameof(observable.PropertyChanged)) + .WithSender(observable) + .WithArgs(args => args.PropertyName == "Boo"); + + recording + .Should().ContainSingle("because we were expecting a specific property change") + .Which.Parameters.Last().Should().BeOfType() + .Which.PropertyName.Should().Be("Boo"); + } - [Fact] - public void When_a_property_changed_event_for_a_specific_property_was_not_raised_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); + [Fact] + public void When_events_are_raised_regardless_of_time_tick_it_should_return_by_invokation_order() + { + // Arrange + var observable = new TestEventRaisingInOrder(); + var utcNow = 11.January(2022).At(12, 00).AsUtc(); + using var monitor = observable.Monitor(() => utcNow); - // Act - Action act = () => monitor.Should().RaisePropertyChangeFor(x => x.SomeProperty, "the property was changed"); + // Act + observable.RaiseAllEvents(); - // Assert - act.Should().Throw().WithMessage( - "Expected object " + Formatter.ToString(subject) + - " to raise event \"PropertyChanged\" for property \"SomeProperty\" because the property was changed, but it did not*"); - } + // Assert + monitor.OccurredEvents[0].EventName.Should().Be(nameof(TestEventRaisingInOrder.InterfaceEvent)); + monitor.OccurredEvents[0].Sequence.Should().Be(0); - [Fact] - public void When_a_property_agnostic_property_changed_event_for_was_not_raised_it_should_throw() - { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); + monitor.OccurredEvents[1].EventName.Should().Be(nameof(TestEventRaisingInOrder.Interface2Event)); + monitor.OccurredEvents[1].Sequence.Should().Be(1); + + monitor.OccurredEvents[2].EventName.Should().Be(nameof(TestEventRaisingInOrder.Interface3Event)); + monitor.OccurredEvents[2].Sequence.Should().Be(2); + } - // Act - Action act = () => monitor.Should().RaisePropertyChangeFor(null); + [Fact] + public void When_monitoring_a_class_it_should_be_possible_to_attach_to_additional_interfaces_on_the_same_object() + { + // Arrange + var subject = new TestEventRaising(); + using var outerMonitor = subject.Monitor(); + using var innerMonitor = subject.Monitor(); - // Assert - act.Should().Throw().WithMessage( - "Expected object " + Formatter.ToString(subject) + - " to raise event \"PropertyChanged\" for property , but it did not*"); + // Act + subject.RaiseBothEvents(); + + // Assert + outerMonitor.Should().Raise("InterfaceEvent"); + innerMonitor.Should().Raise("Interface2Event"); + } } - [Fact] - public void When_a_property_changed_event_for_another_than_the_unexpected_property_was_raised_it_should_not_throw() + public class ShouldRaisePropertyChanged { - // Arrange - var subject = new EventRaisingClass(); - using var monitor = subject.Monitor(); - subject.RaiseEventWithSenderAndPropertyName("SomeOtherProperty"); + [Fact] + public void When_a_property_changed_event_was_raised_for_the_expected_property_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); + subject.RaiseEventWithSenderAndPropertyName("SomeOtherProperty"); - // Act - Action act = () => monitor.Should().NotRaisePropertyChangeFor(x => x.SomeProperty); + // Act + Action act = () => monitor.Should().RaisePropertyChangeFor(x => x.SomeProperty); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_monitoring_a_class_it_should_be_possible_to_attach_to_additional_interfaces_on_the_same_object() - { - // Arrange - var subject = new TestEventRaising(); - using var outerMonitor = subject.Monitor(); - using var innerMonitor = subject.Monitor(); + [Fact] + public void When_an_expected_property_changed_event_was_raised_for_all_properties_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName(null); - // Act - subject.RaiseBothEvents(); + // Act + Action act = () => monitor.Should().RaisePropertyChangeFor(null); - // Assert - outerMonitor.Should().Raise("InterfaceEvent"); - innerMonitor.Should().Raise("Interface2Event"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_property_changed_event_was_raised_for_the_wrong_property_it_should_throw_and_include_the_actual_properties_raised() - { - // Arrange - var bar = new EventRaisingClass(); - using var monitor = bar.Monitor(); - bar.RaiseEventWithSenderAndPropertyName("OtherProperty1"); - bar.RaiseEventWithSenderAndPropertyName("OtherProperty2"); - bar.RaiseEventWithSenderAndPropertyName("OtherProperty2"); - - // Act - Action act = () => monitor.Should().RaisePropertyChangeFor(b => b.SomeProperty); - - // Assert - act.Should().Throw() - .WithMessage("Expected*property*SomeProperty*but*OtherProperty1*OtherProperty2*"); - } + [Fact] + public void When_a_property_changed_event_for_a_specific_property_was_not_raised_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); - #endregion + // Act + Action act = () => monitor.Should().RaisePropertyChangeFor(x => x.SomeProperty, "the property was changed"); - #region Precondition Checks + // Assert + act.Should().Throw().WithMessage( + "Expected object " + Formatter.ToString(subject) + + " to raise event \"PropertyChanged\" for property \"SomeProperty\" because the property was changed, but it did not*"); + } - [Fact] - public void When_monitoring_a_null_object_it_should_throw() - { - // Arrange - EventRaisingClass subject = null; + [Fact] + public void When_a_property_agnostic_property_changed_event_for_was_not_raised_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); - // Act - Action act = () => subject.Monitor(); + // Act + Action act = () => monitor.Should().RaisePropertyChangeFor(null); - // Assert - act.Should().Throw() - .WithMessage("Cannot monitor the events of a object*"); + // Assert + act.Should().Throw().WithMessage( + "Expected object " + Formatter.ToString(subject) + + " to raise event \"PropertyChanged\" for property , but it did not*"); + } + + [Fact] + public void When_the_property_changed_event_was_raised_for_the_wrong_property_it_should_throw_and_include_the_actual_properties_raised() + { + // Arrange + var bar = new EventRaisingClass(); + using var monitor = bar.Monitor(); + bar.RaiseEventWithSenderAndPropertyName("OtherProperty1"); + bar.RaiseEventWithSenderAndPropertyName("OtherProperty2"); + bar.RaiseEventWithSenderAndPropertyName("OtherProperty2"); + + // Act + Action act = () => monitor.Should().RaisePropertyChangeFor(b => b.SomeProperty); + + // Assert + act.Should().Throw() + .WithMessage("Expected*property*SomeProperty*but*OtherProperty1*OtherProperty2*"); + } } - [Fact] - public void When_nesting_monitoring_requests_scopes_should_be_isolated() + public class ShouldNotRaisePropertyChanged { - // Arrange - var eventSource = new EventRaisingClass(); - using var outerScope = eventSource.Monitor(); + [Fact] + public void When_a_property_changed_event_was_raised_by_monitored_class_it_should_be_possible_to_reset_the_event_monitor() + { + // Arrange + var subject = new EventRaisingClass(); + using var eventMonitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - // Act - using var innerScope = eventSource.Monitor(); + // Act + eventMonitor.Clear(); - // Assert - ((object)innerScope).Should().NotBeSameAs(outerScope); - } + // Assert + eventMonitor.Should().NotRaisePropertyChangeFor(e => e.SomeProperty); + } - [Fact] - public void When_monitoring_an_object_with_invalid_property_expression_it_should_throw() - { - // Arrange - var eventSource = new EventRaisingClass(); - using var monitor = eventSource.Monitor(); - Func func = e => e.SomeOtherProperty; + [Fact] + public void When_a_property_changed_event_for_an_unexpected_property_was_raised_it_should_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeProperty"); - // Act - Action act = () => monitor.Should().RaisePropertyChangeFor(e => func(e)); + // Act + Action act = () => monitor.Should().NotRaisePropertyChangeFor(x => x.SomeProperty, "nothing happened"); - // Assert - act.Should().Throw() - .WithParameterName("expression"); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect object " + Formatter.ToString(subject) + + " to raise the \"PropertyChanged\" event for property \"SomeProperty\" because nothing happened, but it did."); + } - #endregion + [Fact] + public void When_a_property_changed_event_for_another_than_the_unexpected_property_was_raised_it_should_not_throw() + { + // Arrange + var subject = new EventRaisingClass(); + using var monitor = subject.Monitor(); + subject.RaiseEventWithSenderAndPropertyName("SomeOtherProperty"); - #region Metadata + // Act + Action act = () => monitor.Should().NotRaisePropertyChangeFor(x => x.SomeProperty); - [Fact] - public void When_monitoring_an_object_it_should_monitor_all_the_events_it_exposes() + // Assert + act.Should().NotThrow(); + } + } + + public class PreconditionChecks { - // Arrange - var eventSource = new ClassThatRaisesEventsItself(); - using var eventMonitor = eventSource.Monitor(); + [Fact] + public void When_monitoring_a_null_object_it_should_throw() + { + // Arrange + EventRaisingClass subject = null; - // Act - EventMetadata[] metadata = eventMonitor.MonitoredEvents; + // Act + Action act = () => subject.Monitor(); + + // Assert + act.Should().Throw() + .WithMessage("Cannot monitor the events of a object*"); + } - // Assert - metadata.Should().BeEquivalentTo(new[] + [Fact] + public void When_nesting_monitoring_requests_scopes_should_be_isolated() { - new - { - EventName = nameof(ClassThatRaisesEventsItself.InterfaceEvent), - HandlerType = typeof(EventHandler) - }, - new - { - EventName = nameof(ClassThatRaisesEventsItself.PropertyChanged), - HandlerType = typeof(PropertyChangedEventHandler) - } - }); + // Arrange + var eventSource = new EventRaisingClass(); + using var outerScope = eventSource.Monitor(); + + // Act + using var innerScope = eventSource.Monitor(); + + // Assert + ((object)innerScope).Should().NotBeSameAs(outerScope); + } + + [Fact] + public void When_monitoring_an_object_with_invalid_property_expression_it_should_throw() + { + // Arrange + var eventSource = new EventRaisingClass(); + using var monitor = eventSource.Monitor(); + Func func = e => e.SomeOtherProperty; + + // Act + Action act = () => monitor.Should().RaisePropertyChangeFor(e => func(e)); + + // Assert + act.Should().Throw() + .WithParameterName("expression"); + } } - [Fact] - public void When_monitoring_an_object_through_an_interface_it_should_monitor_only_the_events_it_exposes() + public class Metadata { - // Arrange - var eventSource = new ClassThatRaisesEventsItself(); - using var monitor = eventSource.Monitor(); + [Fact] + public void When_monitoring_an_object_it_should_monitor_all_the_events_it_exposes() + { + // Arrange + var eventSource = new ClassThatRaisesEventsItself(); + using var eventMonitor = eventSource.Monitor(); - // Act - EventMetadata[] metadata = monitor.MonitoredEvents; + // Act + EventMetadata[] metadata = eventMonitor.MonitoredEvents; - // Assert - metadata.Should().BeEquivalentTo(new[] + // Assert + metadata.Should().BeEquivalentTo(new[] + { + new + { + EventName = nameof(ClassThatRaisesEventsItself.InterfaceEvent), + HandlerType = typeof(EventHandler) + }, + new + { + EventName = nameof(ClassThatRaisesEventsItself.PropertyChanged), + HandlerType = typeof(PropertyChangedEventHandler) + } + }); + } + + [Fact] + public void When_monitoring_an_object_through_an_interface_it_should_monitor_only_the_events_it_exposes() { - new + // Arrange + var eventSource = new ClassThatRaisesEventsItself(); + using var monitor = eventSource.Monitor(); + + // Act + EventMetadata[] metadata = monitor.MonitoredEvents; + + // Assert + metadata.Should().BeEquivalentTo(new[] { - EventName = nameof(IEventRaisingInterface.InterfaceEvent), - HandlerType = typeof(EventHandler) - } - }); - } + new + { + EventName = nameof(IEventRaisingInterface.InterfaceEvent), + HandlerType = typeof(EventHandler) + } + }); + } #if NETFRAMEWORK // DefineDynamicAssembly is obsolete in .NET Core - [Fact] - public void When_an_object_doesnt_expose_any_events_it_should_throw() - { - // Arrange - object eventSource = CreateProxyObject(); + [Fact] + public void When_an_object_doesnt_expose_any_events_it_should_throw() + { + // Arrange + object eventSource = CreateProxyObject(); - // Act - Action act = () => eventSource.Monitor(); + // Act + Action act = () => eventSource.Monitor(); - // Assert - act.Should().Throw().WithMessage("*not expose any events*"); - } + // Assert + act.Should().Throw().WithMessage("*not expose any events*"); + } - [Fact] - public void When_monitoring_interface_of_a_class_and_no_recorder_exists_for_an_event_it_should_throw() - { - // Arrange - var eventSource = (IEventRaisingInterface)CreateProxyObject(); - using var eventMonitor = eventSource.Monitor(); + [Fact] + public void When_monitoring_interface_of_a_class_and_no_recorder_exists_for_an_event_it_should_throw() + { + // Arrange + var eventSource = (IEventRaisingInterface)CreateProxyObject(); + using var eventMonitor = eventSource.Monitor(); - // Act - Action action = () => eventMonitor.GetRecordingFor("SomeEvent"); + // Act + Action action = () => eventMonitor.GetRecordingFor("SomeEvent"); - // Assert - action.Should().Throw() - .WithMessage("Not monitoring any events named \"SomeEvent\"."); - } + // Assert + action.Should().Throw() + .WithMessage("Not monitoring any events named \"SomeEvent\"."); + } - private object CreateProxyObject() - { - Type baseType = typeof(EventRaisingClass); - Type interfaceType = typeof(IEventRaisingInterface); - AssemblyName assemblyName = new AssemblyName { Name = baseType.Assembly.FullName + ".GeneratedForTest" }; - AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, - AssemblyBuilderAccess.Run); - ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, false); - string typeName = baseType.Name + "_GeneratedForTest"; - TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public, baseType, new[] { interfaceType }); - - MethodBuilder addHandler = EmitAddRemoveEventHandler("add"); - typeBuilder.DefineMethodOverride(addHandler, interfaceType.GetMethod("add_InterfaceEvent")); - MethodBuilder removeHandler = EmitAddRemoveEventHandler("remove"); - typeBuilder.DefineMethodOverride(removeHandler, interfaceType.GetMethod("remove_InterfaceEvent")); - - Type generatedType = typeBuilder.CreateType(); - return Activator.CreateInstance(generatedType); - - MethodBuilder EmitAddRemoveEventHandler(string methodName) - { - MethodBuilder method = - typeBuilder.DefineMethod($"{interfaceType.FullName}.{methodName}_InterfaceEvent", - MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | - MethodAttributes.HideBySig | - MethodAttributes.NewSlot); - method.SetReturnType(typeof(void)); - method.SetParameters(typeof(EventHandler)); - ILGenerator gen = method.GetILGenerator(); - gen.Emit(OpCodes.Ret); - return method; + private object CreateProxyObject() + { + Type baseType = typeof(EventRaisingClass); + Type interfaceType = typeof(IEventRaisingInterface); + AssemblyName assemblyName = new AssemblyName { Name = baseType.Assembly.FullName + ".GeneratedForTest" }; + AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, + AssemblyBuilderAccess.Run); + ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, false); + string typeName = baseType.Name + "_GeneratedForTest"; + TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public, baseType, new[] { interfaceType }); + + MethodBuilder addHandler = EmitAddRemoveEventHandler("add"); + typeBuilder.DefineMethodOverride(addHandler, interfaceType.GetMethod("add_InterfaceEvent")); + MethodBuilder removeHandler = EmitAddRemoveEventHandler("remove"); + typeBuilder.DefineMethodOverride(removeHandler, interfaceType.GetMethod("remove_InterfaceEvent")); + + Type generatedType = typeBuilder.CreateType(); + return Activator.CreateInstance(generatedType); + + MethodBuilder EmitAddRemoveEventHandler(string methodName) + { + MethodBuilder method = + typeBuilder.DefineMethod($"{interfaceType.FullName}.{methodName}_InterfaceEvent", + MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | + MethodAttributes.HideBySig | + MethodAttributes.NewSlot); + method.SetReturnType(typeof(void)); + method.SetParameters(typeof(EventHandler)); + ILGenerator gen = method.GetILGenerator(); + gen.Emit(OpCodes.Ret); + return method; + } } - } #endif - [Fact] - public void When_event_exists_on_class_but_not_on_monitored_interface_it_should_not_allow_monitoring_it() - { - // Arrange - var eventSource = new ClassThatRaisesEventsItself(); - using var eventMonitor = eventSource.Monitor(); + [Fact] + public void When_event_exists_on_class_but_not_on_monitored_interface_it_should_not_allow_monitoring_it() + { + // Arrange + var eventSource = new ClassThatRaisesEventsItself(); + using var eventMonitor = eventSource.Monitor(); - // Act - Action action = () => eventMonitor.GetRecordingFor("PropertyChanged"); + // Act + Action action = () => eventMonitor.GetRecordingFor("PropertyChanged"); - // Assert - action.Should().Throw() - .WithMessage("Not monitoring any events named \"PropertyChanged\"."); - } + // Assert + action.Should().Throw() + .WithMessage("Not monitoring any events named \"PropertyChanged\"."); + } - [Fact] - public void When_an_object_raises_two_events_it_should_provide_the_data_about_those_occurrences() - { - // Arrange - DateTime utcNow = 17.September(2017).At(21, 00).AsUtc(); + [Fact] + public void When_an_object_raises_two_events_it_should_provide_the_data_about_those_occurrences() + { + // Arrange + DateTime utcNow = 17.September(2017).At(21, 00).AsUtc(); - var eventSource = new EventRaisingClass(); - using var monitor = eventSource.Monitor(() => utcNow); + var eventSource = new EventRaisingClass(); + using var monitor = eventSource.Monitor(() => utcNow); - // Act - eventSource.RaiseEventWithSenderAndPropertyName("theProperty"); + // Act + eventSource.RaiseEventWithSenderAndPropertyName("theProperty"); - utcNow += 1.Hours(); + utcNow += 1.Hours(); - eventSource.RaiseNonConventionalEvent("first", 123, "third"); + eventSource.RaiseNonConventionalEvent("first", 123, "third"); - // Assert - monitor.OccurredEvents.Should().BeEquivalentTo(new[] - { - new - { - EventName = "PropertyChanged", - TimestampUtc = utcNow - 1.Hours(), - Parameters = new object[] { eventSource, new PropertyChangedEventArgs("theProperty") } - }, - new + // Assert + monitor.OccurredEvents.Should().BeEquivalentTo(new[] { - EventName = "NonConventionalEvent", - TimestampUtc = utcNow, - Parameters = new object[] { "first", 123, "third" } - } - }, o => o.WithStrictOrdering()); - } + new + { + EventName = "PropertyChanged", + TimestampUtc = utcNow - 1.Hours(), + Parameters = new object[] { eventSource, new PropertyChangedEventArgs("theProperty") } + }, + new + { + EventName = "NonConventionalEvent", + TimestampUtc = utcNow, + Parameters = new object[] { "first", 123, "third" } + } + }, o => o.WithStrictOrdering()); + } - [Fact] - public void When_monitoring_interface_with_inherited_event_it_should_not_throw() - { - // Arrange - var eventSource = (IInheritsEventRaisingInterface)new ClassThatRaisesEventsItself(); + [Fact] + public void When_monitoring_interface_with_inherited_event_it_should_not_throw() + { + // Arrange + var eventSource = (IInheritsEventRaisingInterface)new ClassThatRaisesEventsItself(); - // Act - Action action = () => eventSource.Monitor(); + // Act + Action action = () => eventSource.Monitor(); - // Assert - action.Should().NotThrow(); + // Assert + action.Should().NotThrow(); + } } - #endregion - public class ClassThatRaisesEventsItself : IInheritsEventRaisingInterface { public event PropertyChangedEventHandler PropertyChanged; From 4e98b0d63a6c4f3af7a01810644d64a1d43f80aa Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Fri, 22 Apr 2022 15:36:14 +0200 Subject: [PATCH 37/48] Seperate all `Specialized` assertions into nested classes --- .../Specialized/AssemblyAssertionSpecs.cs | 480 ++++++----- .../ExecutionTimeAssertionsSpecs.cs | 807 +++++++++--------- .../Specialized/TaskOfTAssertionSpecs.cs | 565 ++++++------ 3 files changed, 927 insertions(+), 925 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Specialized/AssemblyAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/AssemblyAssertionSpecs.cs index b5bbaebb70..34a7886eac 100644 --- a/Tests/FluentAssertions.Specs/Specialized/AssemblyAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/AssemblyAssertionSpecs.cs @@ -10,259 +10,255 @@ namespace FluentAssertions.Specs.Specialized { public class AssemblyAssertionSpecs { - #region NotReference - - [Fact] - public void When_an_assembly_is_not_referenced_and_should_not_reference_is_asserted_it_should_succeed() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - var assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyB.Should().NotReference(assemblyA); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_assembly_is_not_referenced_it_should_allow_chaining() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - var assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyB.Should().NotReference(assemblyA) - .And.NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_assembly_is_referenced_and_should_not_reference_is_asserted_it_should_fail() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - var assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().NotReference(assemblyB); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_subject_is_null_not_reference_should_fail() - { - // Arrange - Assembly assemblyA = null; - Assembly assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().NotReference(assemblyB, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected assembly not to reference assembly \"AssemblyB\" *failure message*, but assemblyA is ."); - } - - [Fact] - public void When_an_assembly_is_not_referencing_null_it_should_throw() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().NotReference(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("assembly"); - } - - #endregion - - #region Reference - - [Fact] - public void When_an_assembly_is_referenced_and_should_reference_is_asserted_it_should_succeed() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - var assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().Reference(assemblyB); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_assembly_is_referenced_it_should_allow_chaining() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - var assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().Reference(assemblyB) - .And.NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_assembly_is_not_referenced_and_should_reference_is_asserted_it_should_fail() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - var assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyB.Should().Reference(assemblyA); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_subject_is_null_reference_should_fail() - { - // Arrange - Assembly assemblyA = null; - Assembly assemblyB = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().Reference(assemblyB, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected assembly to reference assembly \"AssemblyB\" *failure message*, but assemblyA is ."); - } - - [Fact] - public void When_an_assembly_is_referencing_null_it_should_throw() - { - // Arrange - var assemblyA = FindAssembly.Containing(); - - // Act - Action act = () => assemblyA.Should().Reference(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("assembly"); - } - - #endregion - - #region DefineType - - [Fact] - public void When_an_assembly_defines_a_type_and_Should_DefineType_is_asserted_it_should_succeed() - { - // Arrange - var thisAssembly = GetType().Assembly; - - // Act - Action act = () => thisAssembly - .Should().DefineType(GetType().Namespace, typeof(WellKnownClassWithAttribute).Name) - .Which.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_assembly_does_not_define_a_type_and_Should_DefineType_is_asserted_it_should_fail_with_a_useful_message() - { - // Arrange - var thisAssembly = GetType().Assembly; - - // Act - Action act = () => thisAssembly.Should().DefineType("FakeNamespace", "FakeName", - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage($"Expected assembly \"{thisAssembly.FullName}\" " + - "to define type \"FakeNamespace\".\"FakeName\" " + - "because we want to test the failure message, but it does not."); - } - - [Fact] - public void When_subject_is_null_define_type_should_fail() + public class NotReference { - // Arrange - Assembly thisAssembly = null; - - // Act - Action act = () => - thisAssembly.Should().DefineType(GetType().Namespace, "WellKnownClassWithAttribute", - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected assembly to define type *.\"WellKnownClassWithAttribute\" *failure message*" + - ", but thisAssembly is ."); + [Fact] + public void When_an_assembly_is_not_referenced_and_should_not_reference_is_asserted_it_should_succeed() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + var assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyB.Should().NotReference(assemblyA); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_an_assembly_is_not_referenced_it_should_allow_chaining() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + var assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyB.Should().NotReference(assemblyA) + .And.NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_an_assembly_is_referenced_and_should_not_reference_is_asserted_it_should_fail() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + var assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().NotReference(assemblyB); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_subject_is_null_not_reference_should_fail() + { + // Arrange + Assembly assemblyA = null; + Assembly assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().NotReference(assemblyB, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected assembly not to reference assembly \"AssemblyB\" *failure message*, but assemblyA is ."); + } + + [Fact] + public void When_an_assembly_is_not_referencing_null_it_should_throw() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().NotReference(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("assembly"); + } } - [Fact] - public void When_an_assembly_defining_a_type_with_a_null_name_it_should_throw() + public class Reference { - // Arrange - var thisAssembly = GetType().Assembly; - - // Act - Action act = () => thisAssembly.Should().DefineType(GetType().Namespace, null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); + [Fact] + public void When_an_assembly_is_referenced_and_should_reference_is_asserted_it_should_succeed() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + var assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().Reference(assemblyB); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_an_assembly_is_referenced_it_should_allow_chaining() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + var assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().Reference(assemblyB) + .And.NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_an_assembly_is_not_referenced_and_should_reference_is_asserted_it_should_fail() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + var assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyB.Should().Reference(assemblyA); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_subject_is_null_reference_should_fail() + { + // Arrange + Assembly assemblyA = null; + Assembly assemblyB = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().Reference(assemblyB, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected assembly to reference assembly \"AssemblyB\" *failure message*, but assemblyA is ."); + } + + [Fact] + public void When_an_assembly_is_referencing_null_it_should_throw() + { + // Arrange + var assemblyA = FindAssembly.Containing(); + + // Act + Action act = () => assemblyA.Should().Reference(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("assembly"); + } } - [Fact] - public void When_an_assembly_defining_a_type_with_an_empty_name_it_should_throw() + public class DefineType { - // Arrange - var thisAssembly = GetType().Assembly; - - // Act - Action act = () => thisAssembly.Should().DefineType(GetType().Namespace, string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); + [Fact] + public void When_an_assembly_defines_a_type_and_Should_DefineType_is_asserted_it_should_succeed() + { + // Arrange + var thisAssembly = GetType().Assembly; + + // Act + Action act = () => thisAssembly + .Should().DefineType(GetType().Namespace, typeof(WellKnownClassWithAttribute).Name) + .Which.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_an_assembly_does_not_define_a_type_and_Should_DefineType_is_asserted_it_should_fail_with_a_useful_message() + { + // Arrange + var thisAssembly = GetType().Assembly; + + // Act + Action act = () => thisAssembly.Should().DefineType("FakeNamespace", "FakeName", + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage($"Expected assembly \"{thisAssembly.FullName}\" " + + "to define type \"FakeNamespace\".\"FakeName\" " + + "because we want to test the failure message, but it does not."); + } + + [Fact] + public void When_subject_is_null_define_type_should_fail() + { + // Arrange + Assembly thisAssembly = null; + + // Act + Action act = () => + thisAssembly.Should().DefineType(GetType().Namespace, "WellKnownClassWithAttribute", + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected assembly to define type *.\"WellKnownClassWithAttribute\" *failure message*" + + ", but thisAssembly is ."); + } + + [Fact] + public void When_an_assembly_defining_a_type_with_a_null_name_it_should_throw() + { + // Arrange + var thisAssembly = GetType().Assembly; + + // Act + Action act = () => thisAssembly.Should().DefineType(GetType().Namespace, null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_an_assembly_defining_a_type_with_an_empty_name_it_should_throw() + { + // Arrange + var thisAssembly = GetType().Assembly; + + // Act + Action act = () => thisAssembly.Should().DefineType(GetType().Namespace, string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - #endregion - - #region BeNull - - [Fact] - public void When_an_assembly_is_null_and_Should_BeNull_is_asserted_it_should_succeed() + public class BeNull { - // Arrange - Assembly thisAssembly = null; - - // Act - Action act = () => thisAssembly - .Should().BeNull(); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_an_assembly_is_null_and_Should_BeNull_is_asserted_it_should_succeed() + { + // Arrange + Assembly thisAssembly = null; + + // Act + Action act = () => thisAssembly + .Should().BeNull(); + + // Assert + act.Should().NotThrow(); + } } - - #endregion } [DummyClass("name", true)] diff --git a/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs index 64c291e032..a027e5f2b5 100644 --- a/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs @@ -10,536 +10,541 @@ namespace FluentAssertions.Specs.Specialized { public class ExecutionTimeAssertionsSpecs { - #region BeLessThanOrEqualTo - [Fact] - public void When_the_execution_time_of_a_member_is_not_less_than_or_equal_to_a_limit_it_should_throw() + public class BeLessThanOrEqualTo { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_not_less_than_or_equal_to_a_limit_it_should_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(610)).Should().BeLessThanOrEqualTo(500.Milliseconds(), - "we like speed"); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(610)).Should().BeLessThanOrEqualTo(500.Milliseconds(), + "we like speed"); - // Assert - act.Should().Throw().WithMessage( - "*(s.Sleep(610)) should be less than or equal to 500ms because we like speed, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*(s.Sleep(610)) should be less than or equal to 500ms because we like speed, but it required*"); + } - [Fact] - public void When_the_execution_time_of_a_member_is_less_than_or_equal_to_a_limit_it_should_not_throw() - { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_less_than_or_equal_to_a_limit_it_should_not_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(0)).Should().BeLessThanOrEqualTo(500.Milliseconds()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(0)).Should().BeLessThanOrEqualTo(500.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_execution_time_of_an_action_is_not_less_than_or_equal_to_a_limit_it_should_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(510); + [Fact] + public void When_the_execution_time_of_an_action_is_not_less_than_or_equal_to_a_limit_it_should_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(510); - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThanOrEqualTo(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThanOrEqualTo(100.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be less than or equal to 100ms, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*action should be less than or equal to 100ms, but it required*"); + } - [Fact] - public void When_the_execution_time_of_an_action_is_less_than_or_equal_to_a_limit_it_should_not_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(100); + [Fact] + public void When_the_execution_time_of_an_action_is_less_than_or_equal_to_a_limit_it_should_not_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(100); - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThanOrEqualTo(1.Seconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThanOrEqualTo(1.Seconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_there_is_less_than_or_equal_condition() - { - // Arrange - Action someAction = () => + [Fact] + public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_there_is_less_than_or_equal_condition() { + // Arrange + Action someAction = () => + { // lets cause a deadlock - var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore - semaphore.WaitOne(); // oops - }; + var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore + semaphore.WaitOne(); // oops + }; - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThanOrEqualTo(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThanOrEqualTo(100.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be less than or equal to 100ms, but it required more than*"); + // Assert + act.Should().Throw().WithMessage( + "*action should be less than or equal to 100ms, but it required more than*"); + } } - #endregion - #region BeLessThan - [Fact] - public void When_the_execution_time_of_a_member_is_not_less_than_a_limit_it_should_throw() + public class BeLessThan { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_not_less_than_a_limit_it_should_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(610)).Should().BeLessThan(500.Milliseconds(), - "we like speed"); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(610)).Should().BeLessThan(500.Milliseconds(), + "we like speed"); - // Assert - act.Should().Throw().WithMessage( - "*(s.Sleep(610)) should be less than 500ms because we like speed, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*(s.Sleep(610)) should be less than 500ms because we like speed, but it required*"); + } - [Fact] - public void When_the_execution_time_of_a_member_is_less_than_a_limit_it_should_not_throw() - { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_less_than_a_limit_it_should_not_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(0)).Should().BeLessThan(500.Milliseconds()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(0)).Should().BeLessThan(500.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_execution_time_of_an_action_is_not_less_than_a_limit_it_should_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(510); + [Fact] + public void When_the_execution_time_of_an_action_is_not_less_than_a_limit_it_should_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(510); - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(100.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be less than 100ms, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*action should be less than 100ms, but it required*"); + } - [Fact] - public void When_the_execution_time_of_an_async_action_is_not_less_than_a_limit_it_should_throw() - { - // Arrange - Func someAction = () => Task.Delay(TimeSpan.FromMilliseconds(150)); + [Fact] + public void When_the_execution_time_of_an_async_action_is_not_less_than_a_limit_it_should_throw() + { + // Arrange + Func someAction = () => Task.Delay(TimeSpan.FromMilliseconds(150)); - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(100.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be less than 100ms, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*action should be less than 100ms, but it required*"); + } - [Fact] - public void When_the_execution_time_of_an_action_is_less_than_a_limit_it_should_not_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(100); + [Fact] + public void When_the_execution_time_of_an_action_is_less_than_a_limit_it_should_not_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(100); - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(2.Seconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(2.Seconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_execution_time_of_an_async_action_is_less_than_a_limit_it_should_not_throw() - { - // Arrange - Func someAction = () => Task.Delay(TimeSpan.FromMilliseconds(100)); + [Fact] + public void When_the_execution_time_of_an_async_action_is_less_than_a_limit_it_should_not_throw() + { + // Arrange + Func someAction = () => Task.Delay(TimeSpan.FromMilliseconds(100)); - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(20.Seconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(20.Seconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_there_is_less_than_condition() - { - // Arrange - Action someAction = () => + [Fact] + public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_there_is_less_than_condition() { + // Arrange + Action someAction = () => + { // lets cause a deadlock - var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore - semaphore.WaitOne(); // oops - }; + var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore + semaphore.WaitOne(); // oops + }; - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(100.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be less than 100ms, but it required more than*"); + // Assert + act.Should().Throw().WithMessage( + "*action should be less than 100ms, but it required more than*"); + } } - #endregion - #region BeGreaterThanOrEqualTo - [Fact] - public void When_the_execution_time_of_a_member_is_not_greater_than_or_equal_to_a_limit_it_should_throw() + public class BeGreaterThanOrEqualTo { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_not_greater_than_or_equal_to_a_limit_it_should_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(100)).Should().BeGreaterThanOrEqualTo(1.Seconds(), - "we like speed"); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(100)).Should().BeGreaterThanOrEqualTo(1.Seconds(), + "we like speed"); - // Assert - act.Should().Throw().WithMessage( - "*(s.Sleep(100)) should be greater than or equal to 1s because we like speed, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*(s.Sleep(100)) should be greater than or equal to 1s because we like speed, but it required*"); + } - [Fact] - public void When_the_execution_time_of_a_member_is_greater_than_or_equal_to_a_limit_it_should_not_throw() - { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_greater_than_or_equal_to_a_limit_it_should_not_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(100)).Should().BeGreaterThanOrEqualTo(50.Milliseconds()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(100)).Should().BeGreaterThanOrEqualTo(50.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_execution_time_of_an_action_is_not_greater_than_or_equal_to_a_limit_it_should_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(100); + [Fact] + public void When_the_execution_time_of_an_action_is_not_greater_than_or_equal_to_a_limit_it_should_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(100); - // Act - Action act = () => someAction.ExecutionTime().Should().BeGreaterThanOrEqualTo(1.Seconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeGreaterThanOrEqualTo(1.Seconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be greater than or equal to 1s, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*action should be greater than or equal to 1s, but it required*"); + } - [Fact] - public void When_the_execution_time_of_an_action_is_greater_than_or_equal_to_a_limit_it_should_not_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(100); + [Fact] + public void When_the_execution_time_of_an_action_is_greater_than_or_equal_to_a_limit_it_should_not_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(100); - // Act - Action act = () => someAction.ExecutionTime().Should().BeGreaterThanOrEqualTo(50.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeGreaterThanOrEqualTo(50.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_action_runs_indefinitely_it_should_be_stopped_and_not_throw_if_there_is_greater_than_or_equal_condition() - { - // Arrange - Action someAction = () => + [Fact] + public void When_action_runs_indefinitely_it_should_be_stopped_and_not_throw_if_there_is_greater_than_or_equal_condition() { + // Arrange + Action someAction = () => + { // lets cause a deadlock - var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore - semaphore.WaitOne(); // oops - }; + var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore + semaphore.WaitOne(); // oops + }; - // Act - Action act = () => someAction.ExecutionTime().Should().BeGreaterThanOrEqualTo(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeGreaterThanOrEqualTo(100.Milliseconds()); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - #endregion - #region BeGreaterThan - [Fact] - public void When_the_execution_time_of_a_member_is_not_greater_than_a_limit_it_should_throw() + public class BeGreaterThan { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_not_greater_than_a_limit_it_should_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(100)).Should().BeGreaterThan(1.Seconds(), - "we like speed"); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(100)).Should().BeGreaterThan(1.Seconds(), + "we like speed"); - // Assert - act.Should().Throw().WithMessage( - "*(s.Sleep(100)) should be greater than 1s because we like speed, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*(s.Sleep(100)) should be greater than 1s because we like speed, but it required*"); + } - [Fact] - public void When_the_execution_time_of_a_member_is_greater_than_a_limit_it_should_not_throw() - { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_greater_than_a_limit_it_should_not_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(200)).Should().BeGreaterThan(100.Milliseconds()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(200)).Should().BeGreaterThan(100.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_execution_time_of_an_action_is_not_greater_than_a_limit_it_should_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(100); + [Fact] + public void When_the_execution_time_of_an_action_is_not_greater_than_a_limit_it_should_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(100); - // Act - Action act = () => someAction.ExecutionTime().Should().BeGreaterThan(1.Seconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeGreaterThan(1.Seconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be greater than 1s, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*action should be greater than 1s, but it required*"); + } - [Fact] - public void When_the_execution_time_of_an_action_is_greater_than_a_limit_it_should_not_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(200); + [Fact] + public void When_the_execution_time_of_an_action_is_greater_than_a_limit_it_should_not_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(200); - // Act - Action act = () => someAction.ExecutionTime().Should().BeGreaterThan(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeGreaterThan(100.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_action_runs_indefinitely_it_should_be_stopped_and_not_throw_if_there_is_greater_than_condition() - { - // Arrange - Action someAction = () => + [Fact] + public void When_action_runs_indefinitely_it_should_be_stopped_and_not_throw_if_there_is_greater_than_condition() { + // Arrange + Action someAction = () => + { // lets cause a deadlock - var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore - semaphore.WaitOne(); // oops - }; + var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore + semaphore.WaitOne(); // oops + }; - // Act - Action act = () => someAction.ExecutionTime().Should().BeGreaterThan(100.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeGreaterThan(100.Milliseconds()); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - #endregion - #region BeCloseTo - [Fact] - public void When_asserting_that_execution_time_is_close_to_a_negative_precision_it_should_throw() + public class BeCloseTo { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_asserting_that_execution_time_is_close_to_a_negative_precision_it_should_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(200)).Should().BeCloseTo(100.Milliseconds(), - -1.Ticks()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(200)).Should().BeCloseTo(100.Milliseconds(), + -1.Ticks()); - // Assert - act.Should().Throw() - .WithMessage("* value of precision must be non-negative*"); - } + // Assert + act.Should().Throw() + .WithMessage("* value of precision must be non-negative*"); + } - [Fact] - public void When_the_execution_time_of_a_member_is_not_close_to_a_limit_it_should_throw() - { - // Arrange - var subject = new SleepingClass(); + [Fact] + public void When_the_execution_time_of_a_member_is_not_close_to_a_limit_it_should_throw() + { + // Arrange + var subject = new SleepingClass(); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(200)).Should().BeCloseTo(100.Milliseconds(), - 50.Milliseconds(), - "we like speed"); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(200)).Should().BeCloseTo(100.Milliseconds(), + 50.Milliseconds(), + "we like speed"); - // Assert - act.Should().Throw().WithMessage( - "*(s.Sleep(200)) should be within 50ms from 100ms because we like speed, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*(s.Sleep(200)) should be within 50ms from 100ms because we like speed, but it required*"); + } - [Fact] - public void When_the_execution_time_of_a_member_is_close_to_a_limit_it_should_not_throw() - { - // Arrange - var subject = new SleepingClass(); - var timer = new TestTimer(() => 210.Milliseconds()); + [Fact] + public void When_the_execution_time_of_a_member_is_close_to_a_limit_it_should_not_throw() + { + // Arrange + var subject = new SleepingClass(); + var timer = new TestTimer(() => 210.Milliseconds()); - // Act - Action act = () => subject.ExecutionTimeOf(s => s.Sleep(0), () => timer).Should().BeCloseTo(200.Milliseconds(), - 150.Milliseconds()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.Sleep(0), () => timer).Should().BeCloseTo(200.Milliseconds(), + 150.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_execution_time_of_an_action_is_not_close_to_a_limit_it_should_throw() - { - // Arrange - Action someAction = () => Thread.Sleep(200); + [Fact] + public void When_the_execution_time_of_an_action_is_not_close_to_a_limit_it_should_throw() + { + // Arrange + Action someAction = () => Thread.Sleep(200); - // Act - Action act = () => someAction.ExecutionTime().Should().BeCloseTo(100.Milliseconds(), 50.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeCloseTo(100.Milliseconds(), 50.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be within 50ms from 100ms, but it required*"); - } + // Assert + act.Should().Throw().WithMessage( + "*action should be within 50ms from 100ms, but it required*"); + } - [Fact] - public void When_the_execution_time_of_an_action_is_close_to_a_limit_it_should_not_throw() - { - // Arrange - Action someAction = () => { }; - var timer = new TestTimer(() => 210.Milliseconds()); + [Fact] + public void When_the_execution_time_of_an_action_is_close_to_a_limit_it_should_not_throw() + { + // Arrange + Action someAction = () => { }; + var timer = new TestTimer(() => 210.Milliseconds()); - // Act - Action act = () => someAction.ExecutionTime(() => timer).Should().BeCloseTo(200.Milliseconds(), 15.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime(() => timer).Should().BeCloseTo(200.Milliseconds(), 15.Milliseconds()); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_there_is_be_close_to_condition() - { - // Arrange - Action someAction = () => + [Fact] + public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_there_is_be_close_to_condition() { + // Arrange + Action someAction = () => + { // lets cause a deadlock - var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore - semaphore.WaitOne(); // oops - }; + var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore + semaphore.WaitOne(); // oops + }; - // Act - Action act = () => someAction.ExecutionTime().Should().BeCloseTo(100.Milliseconds(), 50.Milliseconds()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeCloseTo(100.Milliseconds(), 50.Milliseconds()); - // Assert - act.Should().Throw().WithMessage( - "*action should be within 50ms from 100ms, but it required*"); + // Assert + act.Should().Throw().WithMessage( + "*action should be within 50ms from 100ms, but it required*"); + } } - #endregion - #region ExecutionTime - [Fact] - public void When_action_runs_inside_execution_time_exceptions_are_captured_and_rethrown() + public class ExecutingTime { - // Arrange - Action someAction = () => throw new ArgumentException("Let's say somebody called the wrong method."); - - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(200.Milliseconds()); + [Fact] + public void When_action_runs_inside_execution_time_exceptions_are_captured_and_rethrown() + { + // Arrange + Action someAction = () => throw new ArgumentException("Let's say somebody called the wrong method."); - // Assert - act.Should().Throw().WithMessage("Let's say somebody called the wrong method."); - } + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(200.Milliseconds()); - [Fact] - public void Stopwatch_is_not_stopped_after_first_execution_time_assertion() - { - // Arrange - Action someAction = () => Thread.Sleep(300); + // Assert + act.Should().Throw().WithMessage("Let's say somebody called the wrong method."); + } - // Act - Action act = () => + [Fact] + public void Stopwatch_is_not_stopped_after_first_execution_time_assertion() { + // Arrange + Action someAction = () => Thread.Sleep(300); + + // Act + Action act = () => + { // I know it's not meant to be used like this, // but since you can, it should still give consistent results - ExecutionTime time = someAction.ExecutionTime(); - time.Should().BeGreaterThan(100.Milliseconds()); - time.Should().BeGreaterThan(200.Milliseconds()); - }; + ExecutionTime time = someAction.ExecutionTime(); + time.Should().BeGreaterThan(100.Milliseconds()); + time.Should().BeGreaterThan(200.Milliseconds()); + }; - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_on_null_execution_it_should_throw() - { - // Arrange - ExecutionTime executionTime = null; + [Fact] + public void When_asserting_on_null_execution_it_should_throw() + { + // Arrange + ExecutionTime executionTime = null; - // Act - Func act = () => new ExecutionTimeAssertions(executionTime); + // Act + Func act = () => new ExecutionTimeAssertions(executionTime); - // Assert - act.Should().Throw() - .WithParameterName("executionTime"); - } + // Assert + act.Should().Throw() + .WithParameterName("executionTime"); + } - [Fact] - public void When_asserting_on_null_action_it_should_throw() - { - // Arrange - Action someAction = null; + [Fact] + public void When_asserting_on_null_action_it_should_throw() + { + // Arrange + Action someAction = null; - // Act - Action act = () => someAction.ExecutionTime().Should().BeLessThan(1.Days()); + // Act + Action act = () => someAction.ExecutionTime().Should().BeLessThan(1.Days()); - // Assert - act.Should().ThrowExactly() - .WithParameterName("action"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("action"); + } - [Fact] - public void When_asserting_on_null_func_it_should_throw() - { - // Arrange - Func someFunc = null; + [Fact] + public void When_asserting_on_null_func_it_should_throw() + { + // Arrange + Func someFunc = null; - // Act - Action act = () => someFunc.ExecutionTime().Should().BeLessThan(1.Days()); + // Act + Action act = () => someFunc.ExecutionTime().Should().BeLessThan(1.Days()); - // Assert - act.Should().ThrowExactly() - .WithParameterName("action"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("action"); + } - [Fact] - public void When_asserting_execution_time_of_null_action_it_should_throw() - { - // Arrange - object subject = null; + [Fact] + public void When_asserting_execution_time_of_null_action_it_should_throw() + { + // Arrange + object subject = null; - // Act - Action act = () => subject.ExecutionTimeOf(s => s.ToString()).Should().BeLessThan(1.Days()); + // Act + Action act = () => subject.ExecutionTimeOf(s => s.ToString()).Should().BeLessThan(1.Days()); - // Assert - act.Should().ThrowExactly() - .WithParameterName("subject"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("subject"); + } - [Fact] - public void When_asserting_execution_time_of_null_it_should_throw() - { - // Arrange - var subject = new object(); + [Fact] + public void When_asserting_execution_time_of_null_it_should_throw() + { + // Arrange + var subject = new object(); - // Act - Action act = () => subject.ExecutionTimeOf(null).Should().BeLessThan(1.Days()); + // Act + Action act = () => subject.ExecutionTimeOf(null).Should().BeLessThan(1.Days()); - // Assert - act.Should().ThrowExactly() - .WithParameterName("action"); + // Assert + act.Should().ThrowExactly() + .WithParameterName("action"); + } } - #endregion - internal class SleepingClass { public void Sleep(int milliseconds) diff --git a/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs index d713c177f0..dca1d40afb 100644 --- a/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/TaskOfTAssertionSpecs.cs @@ -13,188 +13,161 @@ namespace FluentAssertions.Specs.Specialized { public class TaskOfTAssertionSpecs { - #region CompleteWithinAsync - - [Fact] - public async Task When_subject_is_null_when_expecting_to_complete_async_it_should_throw() - { - // Arrange - var timeSpan = 0.Milliseconds(); - Func> action = null; - - // Act - Func testAction = () => action.Should().CompleteWithinAsync( - timeSpan, "because we want to test the failure {0}", "message"); - - // Assert - await testAction.Should().ThrowAsync() - .WithMessage("*because we want to test the failure message*found *"); - } - - [Fact] - public async Task When_task_completes_fast_async_it_should_succeed() + public class CompleteWithinAsync { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); - - // Act - Func action = async () => + [Fact] + public async Task When_subject_is_null_when_expecting_to_complete_async_it_should_throw() { - Func> func = () => taskFactory.Task; - - (await func.Should(timer).CompleteWithinAsync(100.Milliseconds())) - .Which.Should().Be(42); - }; - - taskFactory.SetResult(42); - timer.Complete(); + // Arrange + var timeSpan = 0.Milliseconds(); + Func> action = null; - // Assert - await action.Should().NotThrowAsync(); - } + // Act + Func testAction = () => action.Should().CompleteWithinAsync( + timeSpan, "because we want to test the failure {0}", "message"); - [Fact] - public async Task When_task_completes_async_and_result_is_not_expected_it_should_throw() - { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); + // Assert + await testAction.Should().ThrowAsync() + .WithMessage("*because we want to test the failure message*found *"); + } - // Act - Func action = async () => + [Fact] + public async Task When_task_completes_fast_async_it_should_succeed() { - Func> funcSubject = () => taskFactory.Task; + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - (await funcSubject.Should(timer).CompleteWithinAsync(100.Milliseconds())) - .Which.Should().Be(42); - }; + // Act + Func action = async () => + { + Func> func = () => taskFactory.Task; - taskFactory.SetResult(99); - timer.Complete(); + (await func.Should(timer).CompleteWithinAsync(100.Milliseconds())) + .Which.Should().Be(42); + }; - // Assert - // TODO message currently shows "Expected (await funcSubject to be...", but should be "Expected funcSubject to be...", - // maybe with or without await. - await action.Should().ThrowAsync().WithMessage("*to be 42, but found 99 (difference of 57)."); - } + taskFactory.SetResult(42); + timer.Complete(); - [Fact] - public async Task When_task_completes_async_and_async_result_is_not_expected_it_should_throw() - { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); + // Assert + await action.Should().NotThrowAsync(); + } - // Act - Func action = async () => + [Fact] + public async Task When_task_completes_async_and_result_is_not_expected_it_should_throw() { - Func> funcSubject = () => taskFactory.Task; + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - await funcSubject.Should(timer).CompleteWithinAsync(100.Milliseconds()).WithResult(42); - }; + // Act + Func action = async () => + { + Func> funcSubject = () => taskFactory.Task; - taskFactory.SetResult(99); - timer.Complete(); + (await funcSubject.Should(timer).CompleteWithinAsync(100.Milliseconds())) + .Which.Should().Be(42); + }; - // Assert - await action.Should().ThrowAsync().WithMessage("Expected funcSubject to be 42, but found 99."); - } + taskFactory.SetResult(99); + timer.Complete(); - [Fact] - public async Task When_task_completes_slow_async_it_should_fail() - { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); + // Assert + // TODO message currently shows "Expected (await funcSubject to be...", but should be "Expected funcSubject to be...", + // maybe with or without await. + await action.Should().ThrowAsync().WithMessage("*to be 42, but found 99 (difference of 57)."); + } - // Act - Func action = () => + [Fact] + public async Task When_task_completes_async_and_async_result_is_not_expected_it_should_throw() { - Func> func = () => taskFactory.Task; + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - return func.Should(timer).CompleteWithinAsync(100.Milliseconds()); - }; + // Act + Func action = async () => + { + Func> funcSubject = () => taskFactory.Task; - timer.Complete(); + await funcSubject.Should(timer).CompleteWithinAsync(100.Milliseconds()).WithResult(42); + }; - // Assert - await action.Should().ThrowAsync(); - } + taskFactory.SetResult(99); + timer.Complete(); - [Fact] - public async Task Sync_work_in_async_method_is_taken_into_account() - { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); + // Assert + await action.Should().ThrowAsync().WithMessage("Expected funcSubject to be 42, but found 99."); + } - // Act - Func action = () => + [Fact] + public async Task When_task_completes_slow_async_it_should_fail() { - Func> func = () => + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); + + // Act + Func action = () => { - timer.Delay(101.Milliseconds()); - return taskFactory.Task; - }; + Func> func = () => taskFactory.Task; - return func.Should(timer).CompleteWithinAsync(100.Milliseconds()); - }; + return func.Should(timer).CompleteWithinAsync(100.Milliseconds()); + }; - taskFactory.SetResult(99); - timer.Complete(); + timer.Complete(); - // Assert - await action.Should().ThrowAsync(); - } + // Assert + await action.Should().ThrowAsync(); + } - #endregion + [Fact] + public async Task Sync_work_in_async_method_is_taken_into_account() + { + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); - #region NotThrowAfterAsync + // Act + Func action = () => + { + Func> func = () => + { + timer.Delay(101.Milliseconds()); + return taskFactory.Task; + }; - [Fact] - public async Task When_subject_is_null_when_expecting_to_not_throw_async_it_should_throw() - { - // Arrange - Func> action = null; + return func.Should(timer).CompleteWithinAsync(100.Milliseconds()); + }; - // Act - Func testAction = () => action.Should().NotThrowAsync( - "because we want to test the failure {0}", "message"); + taskFactory.SetResult(99); + timer.Complete(); - // Assert - await testAction.Should().ThrowAsync() - .WithMessage("*because we want to test the failure message*found *"); + // Assert + await action.Should().ThrowAsync(); + } } - [Fact] - public async Task When_task_does_not_throw_async_it_should_succeed() + public class NotThrowAsync { - // Arrange - var timer = new FakeClock(); - var taskFactory = new TaskCompletionSource(); - - // Act - Func action = async () => + [Fact] + public async Task When_subject_is_null_when_expecting_to_not_throw_async_it_should_throw() { - Func> func = () => taskFactory.Task; - - (await func.Should(timer).NotThrowAsync()) - .Which.Should().Be(42); - }; + // Arrange + Func> action = null; - taskFactory.SetResult(42); - timer.Complete(); + // Act + Func testAction = () => action.Should().NotThrowAsync( + "because we want to test the failure {0}", "message"); - // Assert - await action.Should().NotThrowAsync(); - } + // Assert + await testAction.Should().ThrowAsync() + .WithMessage("*because we want to test the failure message*found *"); + } - [Collection("UIFacts")] - public partial class UIFacts - { - [UIFact] - public async Task When_task_does_not_throw_async_on_UI_thread_it_should_succeed() + [Fact] + public async Task When_task_does_not_throw_async_it_should_succeed() { // Arrange var timer = new FakeClock(); @@ -215,30 +188,36 @@ public async Task When_task_does_not_throw_async_on_UI_thread_it_should_succeed( // Assert await action.Should().NotThrowAsync(); } - } - - [Fact] - public async Task When_task_throws_async_it_should_fail() - { - // Arrange - var timer = new FakeClock(); - // Act - Func action = () => + [Collection("UIFacts")] + public partial class UIFacts { - Func> func = () => throw new AggregateException(); + [UIFact] + public async Task When_task_does_not_throw_async_on_UI_thread_it_should_succeed() + { + // Arrange + var timer = new FakeClock(); + var taskFactory = new TaskCompletionSource(); + + // Act + Func action = async () => + { + Func> func = () => taskFactory.Task; - return func.Should(timer).NotThrowAsync(); - }; + (await func.Should(timer).NotThrowAsync()) + .Which.Should().Be(42); + }; - // Assert - await action.Should().ThrowAsync(); - } + taskFactory.SetResult(42); + timer.Complete(); - public partial class UIFacts - { - [UIFact] - public async Task When_task_throws_async_on_UI_thread_it_should_fail() + // Assert + await action.Should().NotThrowAsync(); + } + } + + [Fact] + public async Task When_task_throws_async_it_should_fail() { // Arrange var timer = new FakeClock(); @@ -254,114 +233,104 @@ public async Task When_task_throws_async_on_UI_thread_it_should_fail() // Assert await action.Should().ThrowAsync(); } - } - [Fact] - public async Task When_subject_is_null_and_expecting_to_not_throw_async_it_should_throw() - { - // Arrange - var waitTime = 0.Milliseconds(); - var pollInterval = 0.Milliseconds(); - Func> action = null; - - // Act - Func testAction = () => action.Should().NotThrowAfterAsync( - waitTime, pollInterval, "because we want to test the failure {0}", "message"); - - // Assert - await testAction.Should().ThrowAsync() - .WithMessage("*because we want to test the failure message*found *"); - } - - [Fact] - public async Task When_wait_time_is_negative_and_expecting_to_not_throw_async_it_should_throw() - { - // Arrange - var waitTime = -1.Milliseconds(); - var pollInterval = 10.Milliseconds(); + public partial class UIFacts + { + [UIFact] + public async Task When_task_throws_async_on_UI_thread_it_should_fail() + { + // Arrange + var timer = new FakeClock(); - var asyncObject = new AsyncClass(); - Func> someFunc = () => asyncObject.ReturnTaskInt(); + // Act + Func action = () => + { + Func> func = () => throw new AggregateException(); - // Act - Func act = () => someFunc.Should().NotThrowAfterAsync(waitTime, pollInterval); + return func.Should(timer).NotThrowAsync(); + }; - // Assert - await act.Should().ThrowAsync() - .WithMessage("* value of waitTime must be non-negative*"); + // Assert + await action.Should().ThrowAsync(); + } + } } - [Fact] - public async Task When_poll_interval_is_negative_and_expecting_to_not_throw_async_it_should_throw() + public class NotThrowAfterAsync { - // Arrange - var waitTime = 10.Milliseconds(); - var pollInterval = -1.Milliseconds(); + [Fact] + public async Task When_subject_is_null_and_expecting_to_not_throw_async_it_should_throw() + { + // Arrange + var waitTime = 0.Milliseconds(); + var pollInterval = 0.Milliseconds(); + Func> action = null; - var asyncObject = new AsyncClass(); - Func> someFunc = () => asyncObject.ReturnTaskInt(); + // Act + Func testAction = () => action.Should().NotThrowAfterAsync( + waitTime, pollInterval, "because we want to test the failure {0}", "message"); - // Act - Func act = () => someFunc.Should().NotThrowAfterAsync(waitTime, pollInterval); + // Assert + await testAction.Should().ThrowAsync() + .WithMessage("*because we want to test the failure message*found *"); + } - // Assert - await act.Should().ThrowAsync() - .WithMessage("* value of pollInterval must be non-negative*"); - } + [Fact] + public async Task When_wait_time_is_negative_and_expecting_to_not_throw_async_it_should_throw() + { + // Arrange + var waitTime = -1.Milliseconds(); + var pollInterval = 10.Milliseconds(); - [Fact] - public async Task When_no_exception_should_be_thrown_async_for_null_after_wait_time_it_should_throw() - { - // Arrange - var waitTime = 2.Seconds(); - var pollInterval = 10.Milliseconds(); + var asyncObject = new AsyncClass(); + Func> someFunc = () => asyncObject.ReturnTaskInt(); - Func> func = null; + // Act + Func act = () => someFunc.Should().NotThrowAfterAsync(waitTime, pollInterval); - // Act - Func action = () => func.Should() - .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); + // Assert + await act.Should().ThrowAsync() + .WithMessage("* value of waitTime must be non-negative*"); + } - // Assert - await action.Should().ThrowAsync() - .WithMessage("*but found *"); - } + [Fact] + public async Task When_poll_interval_is_negative_and_expecting_to_not_throw_async_it_should_throw() + { + // Arrange + var waitTime = 10.Milliseconds(); + var pollInterval = -1.Milliseconds(); - [Fact] - public async Task When_no_exception_should_be_thrown_async_after_wait_time_but_it_was_it_should_throw() - { - // Arrange - var waitTime = 2.Seconds(); - var pollInterval = 10.Milliseconds(); + var asyncObject = new AsyncClass(); + Func> someFunc = () => asyncObject.ReturnTaskInt(); + + // Act + Func act = () => someFunc.Should().NotThrowAfterAsync(waitTime, pollInterval); - var clock = new FakeClock(); - var timer = clock.StartTimer(); - clock.CompleteAfter(waitTime); + // Assert + await act.Should().ThrowAsync() + .WithMessage("* value of pollInterval must be non-negative*"); + } - Func> throwLongerThanWaitTime = async () => + [Fact] + public async Task When_no_exception_should_be_thrown_async_for_null_after_wait_time_it_should_throw() { - if (timer.Elapsed <= waitTime.Multiply(1.5)) - { - throw new ArgumentException("An exception was forced"); - } + // Arrange + var waitTime = 2.Seconds(); + var pollInterval = 10.Milliseconds(); - await Task.Yield(); - return 42; - }; + Func> func = null; - // Act - Func action = () => throwLongerThanWaitTime.Should(clock) - .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); + // Act + Func action = () => func.Should() + .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); - // Assert - await action.Should().ThrowAsync() - .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); - } + // Assert + await action.Should().ThrowAsync() + .WithMessage("*but found *"); + } - public partial class UIFacts - { - [UIFact] - public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_but_it_was_it_should_throw() + [Fact] + public async Task When_no_exception_should_be_thrown_async_after_wait_time_but_it_was_it_should_throw() { // Arrange var waitTime = 2.Seconds(); @@ -390,45 +359,43 @@ public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wa await action.Should().ThrowAsync() .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); } - } - - [Fact] - public async Task When_no_exception_should_be_thrown_async_after_wait_time_and_none_was_it_should_not_throw() - { - // Arrange - var waitTime = 6.Seconds(); - var pollInterval = 10.Milliseconds(); - - var clock = new FakeClock(); - var timer = clock.StartTimer(); - clock.Delay(waitTime); - Func> throwShorterThanWaitTime = async () => + public partial class UIFacts { - if (timer.Elapsed <= waitTime.Divide(12)) + [UIFact] + public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_but_it_was_it_should_throw() { - throw new ArgumentException("An exception was forced"); - } - - await Task.Yield(); - return 42; - }; + // Arrange + var waitTime = 2.Seconds(); + var pollInterval = 10.Milliseconds(); - // Act - Func act = async () => - { - (await throwShorterThanWaitTime.Should(clock).NotThrowAfterAsync(waitTime, pollInterval)) - .Which.Should().Be(42); - }; + var clock = new FakeClock(); + var timer = clock.StartTimer(); + clock.CompleteAfter(waitTime); - // Assert - await act.Should().NotThrowAsync(); - } + Func> throwLongerThanWaitTime = async () => + { + if (timer.Elapsed <= waitTime.Multiply(1.5)) + { + throw new ArgumentException("An exception was forced"); + } + + await Task.Yield(); + return 42; + }; + + // Act + Func action = () => throwLongerThanWaitTime.Should(clock) + .NotThrowAfterAsync(waitTime, pollInterval, "we passed valid arguments"); + + // Assert + await action.Should().ThrowAsync() + .WithMessage("Did not expect any exceptions after 2s because we passed valid arguments*"); + } + } - public partial class UIFacts - { - [UIFact] - public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_and_none_was_it_should_not_throw() + [Fact] + public async Task When_no_exception_should_be_thrown_async_after_wait_time_and_none_was_it_should_not_throw() { // Arrange var waitTime = 6.Seconds(); @@ -459,8 +426,42 @@ public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wa // Assert await act.Should().NotThrowAsync(); } - } - #endregion + public partial class UIFacts + { + [UIFact] + public async Task When_no_exception_should_be_thrown_async_on_UI_thread_after_wait_time_and_none_was_it_should_not_throw() + { + // Arrange + var waitTime = 6.Seconds(); + var pollInterval = 10.Milliseconds(); + + var clock = new FakeClock(); + var timer = clock.StartTimer(); + clock.Delay(waitTime); + + Func> throwShorterThanWaitTime = async () => + { + if (timer.Elapsed <= waitTime.Divide(12)) + { + throw new ArgumentException("An exception was forced"); + } + + await Task.Yield(); + return 42; + }; + + // Act + Func act = async () => + { + (await throwShorterThanWaitTime.Should(clock).NotThrowAfterAsync(waitTime, pollInterval)) + .Which.Should().Be(42); + }; + + // Assert + await act.Should().NotThrowAsync(); + } + } + } } } From 59fd88aba83292628f2069b7ac840b016e28a27b Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Fri, 22 Apr 2022 15:36:24 +0200 Subject: [PATCH 38/48] Seperate all `Stream` assertions into nested classes --- .../Streams/BufferedStreamAssertionSpecs.cs | 158 +- .../Streams/StreamAssertionSpecs.cs | 1310 +++++++++-------- 2 files changed, 742 insertions(+), 726 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Streams/BufferedStreamAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Streams/BufferedStreamAssertionSpecs.cs index ae314b98be..14415d13bf 100644 --- a/Tests/FluentAssertions.Specs/Streams/BufferedStreamAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Streams/BufferedStreamAssertionSpecs.cs @@ -11,103 +11,105 @@ namespace FluentAssertions.Specs.Streams public class BufferedStreamAssertionSpecs { #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1 - #region HaveBufferSize / NotHaveBufferSize - - [Fact] - public void When_a_stream_has_the_expected_buffer_size_it_should_succeed() + public class HaveBufferSize { - // Arrange - using var stream = new BufferedStream(new MemoryStream(), 10); + [Fact] + public void When_a_stream_has_the_expected_buffer_size_it_should_succeed() + { + // Arrange + using var stream = new BufferedStream(new MemoryStream(), 10); - // Act - Action act = () => - stream.Should().HaveBufferSize(10); + // Act + Action act = () => + stream.Should().HaveBufferSize(10); - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_stream_has_an_unexpected_buffer_size_should_fail() - { - // Arrange - using var stream = new BufferedStream(new MemoryStream(), 1); + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().HaveBufferSize(10, "we want to test the failure {0}", "message"); + [Fact] + public void When_a_stream_has_an_unexpected_buffer_size_should_fail() + { + // Arrange + using var stream = new BufferedStream(new MemoryStream(), 1); - // Assert - act.Should().Throw() - .WithMessage("Expected the buffer size of stream to be 10 *failure message*, but it was 1."); - } + // Act + Action act = () => + stream.Should().HaveBufferSize(10, "we want to test the failure {0}", "message"); - [Fact] - public void When_null_have_buffer_size_should_fail() - { - // Arrange - BufferedStream stream = null; + // Assert + act.Should().Throw() + .WithMessage("Expected the buffer size of stream to be 10 *failure message*, but it was 1."); + } - // Act - Action act = () => + [Fact] + public void When_null_have_buffer_size_should_fail() { - using var _ = new AssertionScope(); - stream.Should().HaveBufferSize(10, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected the buffer size of stream to be 10 *failure message*, but found a reference."); + // Arrange + BufferedStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().HaveBufferSize(10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected the buffer size of stream to be 10 *failure message*, but found a reference."); + } } - [Fact] - public void When_a_stream_does_not_have_an_unexpected_buffer_size_it_should_succeed() + public class NotHaveBufferSize { - // Arrange - using var stream = new BufferedStream(new MemoryStream(), 1); + [Fact] + public void When_a_stream_does_not_have_an_unexpected_buffer_size_it_should_succeed() + { + // Arrange + using var stream = new BufferedStream(new MemoryStream(), 1); - // Act - Action act = () => - stream.Should().NotHaveBufferSize(10); + // Act + Action act = () => + stream.Should().NotHaveBufferSize(10); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_stream_does_have_the_unexpected_buffer_size_it_should_fail() - { - // Arrange - using var stream = new BufferedStream(new MemoryStream(), 10); + [Fact] + public void When_a_stream_does_have_the_unexpected_buffer_size_it_should_fail() + { + // Arrange + using var stream = new BufferedStream(new MemoryStream(), 10); - // Act - Action act = () => - stream.Should().NotHaveBufferSize(10, "we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().NotHaveBufferSize(10, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected the buffer size of stream not to be 10 *failure message*, but it was."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected the buffer size of stream not to be 10 *failure message*, but it was."); + } - [Fact] - public void When_null_not_have_buffer_size_should_fail() - { - // Arrange - BufferedStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_null_not_have_buffer_size_should_fail() { - using var _ = new AssertionScope(); - stream.Should().NotHaveBufferSize(10, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected the buffer size of stream not to be 10 *failure message*, but found a reference."); + // Arrange + BufferedStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotHaveBufferSize(10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected the buffer size of stream not to be 10 *failure message*, but found a reference."); + } } - - #endregion #endif } } diff --git a/Tests/FluentAssertions.Specs/Streams/StreamAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Streams/StreamAssertionSpecs.cs index 65f2d17941..83734545a0 100644 --- a/Tests/FluentAssertions.Specs/Streams/StreamAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Streams/StreamAssertionSpecs.cs @@ -9,833 +9,847 @@ namespace FluentAssertions.Specs.Streams { public class StreamAssertionSpecs { - #region BeWritable / NotBeWritable - - [Fact] - public void When_having_a_writable_stream_be_writable_should_succeed() + public class BeWritable { - // Arrange - using var stream = new TestStream { Writable = true }; + [Fact] + public void When_having_a_writable_stream_be_writable_should_succeed() + { + // Arrange + using var stream = new TestStream { Writable = true }; - // Act - Action act = () => - stream.Should().BeWritable(); + // Act + Action act = () => + stream.Should().BeWritable(); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_having_a_non_writable_stream_be_writable_should_fail() - { - // Arrange - using var stream = new TestStream { Writable = false }; + [Fact] + public void When_having_a_non_writable_stream_be_writable_should_fail() + { + // Arrange + using var stream = new TestStream { Writable = false }; - // Act - Action act = () => - stream.Should().BeWritable("we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().BeWritable("we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be writable *failure message*, but it was not."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be writable *failure message*, but it was not."); + } - [Fact] - public void When_null_be_writable_should_fail() - { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_null_be_writable_should_fail() { - using var _ = new AssertionScope(); - stream.Should().BeWritable("we want to test the failure {0}", "message"); - }; + // Arrange + TestStream stream = null; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be writable *failure message*, but found a reference."); - } - - [Fact] - public void When_having_a_non_writable_stream_be_not_writable_should_succeed() - { - // Arrange - using var stream = new TestStream { Writable = false }; + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().BeWritable("we want to test the failure {0}", "message"); + }; - // Act - Action act = () => - stream.Should().NotBeWritable(); - - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be writable *failure message*, but found a reference."); + } } - [Fact] - public void When_having_a_writable_stream_be_not_writable_should_fail() + public class NotBeWritable { - // Arrange - using var stream = new TestStream { Writable = true }; + [Fact] + public void When_having_a_non_writable_stream_be_not_writable_should_succeed() + { + // Arrange + using var stream = new TestStream { Writable = false }; - // Act - Action act = () => - stream.Should().NotBeWritable("we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().NotBeWritable(); - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be writable *failure message*, but it was."); - } - - [Fact] - public void When_null_not_be_writable_should_fail() - { - // Arrange - TestStream stream = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => + [Fact] + public void When_having_a_writable_stream_be_not_writable_should_fail() { - using var _ = new AssertionScope(); - stream.Should().NotBeWritable("we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Writable = true }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be writable *failure message*, but found a reference."); - } - - #endregion + // Act + Action act = () => + stream.Should().NotBeWritable("we want to test the failure {0}", "message"); - #region BeSeekable / NotBeSeekable + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be writable *failure message*, but it was."); + } - [Fact] - public void When_having_a_seekable_stream_be_seekable_should_succeed() - { - // Arrange - using var stream = new TestStream { Seekable = true }; + [Fact] + public void When_null_not_be_writable_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().BeSeekable(); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotBeWritable("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be writable *failure message*, but found a reference."); + } } - [Fact] - public void When_having_a_non_seekable_stream_be_seekable_should_fail() + public class BeSeekable { - // Arrange - using var stream = new TestStream { Seekable = false }; - - // Act - Action act = () => - stream.Should().BeSeekable("we want to test the failure {0}", "message"); + [Fact] + public void When_having_a_seekable_stream_be_seekable_should_succeed() + { + // Arrange + using var stream = new TestStream { Seekable = true }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be seekable *failure message*, but it was not."); - } + // Act + Action act = () => + stream.Should().BeSeekable(); - [Fact] - public void When_null_be_seekable_should_fail() - { - // Arrange - TestStream stream = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => + [Fact] + public void When_having_a_non_seekable_stream_be_seekable_should_fail() { - using var _ = new AssertionScope(); - stream.Should().BeSeekable("we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Seekable = false }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be seekable *failure message*, but found a reference."); - } - - [Fact] - public void When_having_a_non_seekable_stream_be_not_seekable_should_succeed() - { - // Arrange - using var stream = new TestStream { Seekable = false }; + // Act + Action act = () => + stream.Should().BeSeekable("we want to test the failure {0}", "message"); - // Act - Action act = () => - stream.Should().NotBeSeekable(); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be seekable *failure message*, but it was not."); + } - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_having_a_seekable_stream_be_not_seekable_should_fail() - { - // Arrange - using var stream = new TestStream { Seekable = true }; + [Fact] + public void When_null_be_seekable_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().NotBeSeekable("we want to test the failure {0}", "message"); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().BeSeekable("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be seekable *failure message*, but it was."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be seekable *failure message*, but found a reference."); + } } - [Fact] - public void When_null_not_be_seekable_should_fail() + public class NotBeSeekable { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_non_seekable_stream_be_not_seekable_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().NotBeSeekable("we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Seekable = false }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be seekable *failure message*, but found a reference."); - } - - #endregion + // Act + Action act = () => + stream.Should().NotBeSeekable(); - #region BeReadable / NotBeReadable + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_having_a_readable_stream_be_readable_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = true }; + [Fact] + public void When_having_a_seekable_stream_be_not_seekable_should_fail() + { + // Arrange + using var stream = new TestStream { Seekable = true }; - // Act - Action act = () => - stream.Should().BeReadable(); + // Act + Action act = () => + stream.Should().NotBeSeekable("we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be seekable *failure message*, but it was."); + } - [Fact] - public void When_having_a_non_readable_stream_be_readable_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = false }; + [Fact] + public void When_null_not_be_seekable_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().BeReadable("we want to test the failure {0}", "message"); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotBeSeekable("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be readable *failure message*, but it was not."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be seekable *failure message*, but found a reference."); + } } - [Fact] - public void When_null_be_readable_should_fail() + public class BeReadable { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_readable_stream_be_readable_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().BeReadable("we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Readable = true }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be readable *failure message*, but found a reference."); - } + // Act + Action act = () => + stream.Should().BeReadable(); - [Fact] - public void When_having_a_non_readable_stream_be_not_readable_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = false }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotBeReadable(); + [Fact] + public void When_having_a_non_readable_stream_be_readable_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = false }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + stream.Should().BeReadable("we want to test the failure {0}", "message"); - [Fact] - public void When_having_a_readable_stream_be_not_readable_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = true }; + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be readable *failure message*, but it was not."); + } - // Act - Action act = () => - stream.Should().NotBeReadable("we want to test the failure {0}", "message"); + [Fact] + public void When_null_be_readable_should_fail() + { + // Arrange + TestStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().BeReadable("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be readable *failure message*, but it was."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be readable *failure message*, but found a reference."); + } } - [Fact] - public void When_null_not_be_readable_should_fail() + public class NotBeReadable { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_non_readable_stream_be_not_readable_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().NotBeReadable("we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Readable = false }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be readable *failure message*, but found a reference."); - } - - #endregion + // Act + Action act = () => + stream.Should().NotBeReadable(); - #region HavePosition / NotHavePosition + // Assert + act.Should().NotThrow(); + } - public static IEnumerable GetPositionExceptions() - { - // https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.position#exceptions - yield return new object[] { new IOException("GetPositionExceptionMessage") }; - yield return new object[] { new NotSupportedException("GetPositionExceptionMessage") }; - yield return new object[] { new ObjectDisposedException("GetPositionExceptionMessage") }; - } - - [Fact] - public void When_a_stream_has_the_expected_position_it_should_succeed() - { - // Arrange - using var stream = new TestStream { Seekable = true, Position = 10 }; + [Fact] + public void When_having_a_readable_stream_be_not_readable_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = true }; - // Act - Action act = () => - stream.Should().HavePosition(10); + // Act + Action act = () => + stream.Should().NotBeReadable("we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be readable *failure message*, but it was."); + } - [Fact] - public void When_a_stream_has_the_unexpected_position_it_should_fail() - { - // Arrange - using var stream = new TestStream { Seekable = true, Position = 1 }; + [Fact] + public void When_null_not_be_readable_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().HavePosition(10, "we want to test the failure {0}", "message"); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotBeReadable("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected the position of stream to be 10* *failure message*, but it was 1*."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be readable *failure message*, but found a reference."); + } } - [Theory] - [MemberData(nameof(GetPositionExceptions))] - public void When_a_throwing_stream_should_have_a_position_it_should_fail(Exception exception) + public class HavePosition { - // Arrange - using var stream = new ExceptingStream(exception); + [Fact] + public void When_a_stream_has_the_expected_position_it_should_succeed() + { + // Arrange + using var stream = new TestStream { Seekable = true, Position = 10 }; - // Act - Action act = () => - stream.Should().HavePosition(10, "we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().HavePosition(10); - // Assert - act.Should().Throw() - .WithMessage("Expected the position of stream to be 10* *failure message*, " + - "but it failed with*GetPositionExceptionMessage*"); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_null_have_position_should_fail() - { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_a_stream_has_the_unexpected_position_it_should_fail() { - using var _ = new AssertionScope(); - stream.Should().HavePosition(10, "we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Seekable = true, Position = 1 }; - // Assert - act.Should().Throw() - .WithMessage("Expected the position of stream to be 10* *failure message*, but found a reference."); - } + // Act + Action act = () => + stream.Should().HavePosition(10, "we want to test the failure {0}", "message"); - [Fact] - public void When_a_stream_does_not_have_an_unexpected_position_it_should_succeed() - { - // Arrange - using var stream = new TestStream { Seekable = true, Position = 1 }; + // Assert + act.Should().Throw() + .WithMessage("Expected the position of stream to be 10* *failure message*, but it was 1*."); + } - // Act - Action act = () => - stream.Should().NotHavePosition(10); + [Fact] + public void When_null_have_position_should_fail() + { + // Arrange + TestStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().HavePosition(10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected the position of stream to be 10* *failure message*, but found a reference."); + } + + [Theory] + [MemberData(nameof(StreamAssertionSpecs.GetPositionExceptions), MemberType = typeof(StreamAssertionSpecs))] + public void When_a_throwing_stream_should_have_a_position_it_should_fail(Exception exception) + { + // Arrange + using var stream = new ExceptingStream(exception); - // Assert - act.Should().NotThrow(); + // Act + Action act = () => + stream.Should().HavePosition(10, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the position of stream to be 10* *failure message*, " + + "but it failed with*GetPositionExceptionMessage*"); + } } - [Fact] - public void When_a_stream_does_have_the_unexpected_position_it_should_fail() + public class NotHavePosition { - // Arrange - using var stream = new TestStream { Seekable = true, Position = 10 }; - - // Act - Action act = () => - stream.Should().NotHavePosition(10, "we want to test the failure {0}", "message"); + [Fact] + public void When_a_stream_does_not_have_an_unexpected_position_it_should_succeed() + { + // Arrange + using var stream = new TestStream { Seekable = true, Position = 1 }; - // Assert - act.Should().Throw() - .WithMessage("Expected the position of stream not to be 10* *failure message*, but it was."); - } + // Act + Action act = () => + stream.Should().NotHavePosition(10); - [Theory] - [MemberData(nameof(GetPositionExceptions))] - public void When_a_throwing_stream_should_not_have_a_position_it_should_fail(Exception exception) - { - // Arrange - using var stream = new ExceptingStream(exception); + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotHavePosition(10, "we want to test the failure {0}", "message"); + [Fact] + public void When_a_stream_does_have_the_unexpected_position_it_should_fail() + { + // Arrange + using var stream = new TestStream { Seekable = true, Position = 10 }; - // Assert - act.Should().Throw() - .WithMessage("Expected the position of stream not to be 10* *failure message*, " + - "but it failed with*GetPositionExceptionMessage*"); - } + // Act + Action act = () => + stream.Should().NotHavePosition(10, "we want to test the failure {0}", "message"); - [Fact] - public void When_null_not_have_position_should_fail() - { - // Arrange - TestStream stream = null; + // Assert + act.Should().Throw() + .WithMessage("Expected the position of stream not to be 10* *failure message*, but it was."); + } - // Act - Action act = () => + [Fact] + public void When_null_not_have_position_should_fail() { - using var _ = new AssertionScope(); - stream.Should().NotHavePosition(10, "we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected the position of stream not to be 10* *failure message*, but found a reference."); - } + // Arrange + TestStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotHavePosition(10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected the position of stream not to be 10* *failure message*, but found a reference."); + } + + [Theory] + [MemberData(nameof(StreamAssertionSpecs.GetPositionExceptions), MemberType = typeof(StreamAssertionSpecs))] + public void When_a_throwing_stream_should_not_have_a_position_it_should_fail(Exception exception) + { + // Arrange + using var stream = new ExceptingStream(exception); - #endregion + // Act + Action act = () => + stream.Should().NotHavePosition(10, "we want to test the failure {0}", "message"); - #region HaveLength / NotHaveLength + // Assert + act.Should().Throw() + .WithMessage("Expected the position of stream not to be 10* *failure message*, " + + "but it failed with*GetPositionExceptionMessage*"); + } + } - public static IEnumerable GetLengthExceptions() + public static IEnumerable GetPositionExceptions() { - // https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.length#exceptions - yield return new object[] { new IOException("GetLengthExceptionMessage") }; - yield return new object[] { new NotSupportedException("GetLengthExceptionMessage") }; - yield return new object[] { new ObjectDisposedException("GetLengthExceptionMessage") }; + // https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.position#exceptions + yield return new object[] { new IOException("GetPositionExceptionMessage") }; + yield return new object[] { new NotSupportedException("GetPositionExceptionMessage") }; + yield return new object[] { new ObjectDisposedException("GetPositionExceptionMessage") }; } - [Fact] - public void When_a_stream_has_the_expected_length_it_should_succeed() + public class HaveLength { - // Arrange - using var stream = new TestStream { Seekable = true, WithLength = 10 }; + [Fact] + public void When_a_stream_has_the_expected_length_it_should_succeed() + { + // Arrange + using var stream = new TestStream { Seekable = true, WithLength = 10 }; - // Act - Action act = () => - stream.Should().HaveLength(10); + // Act + Action act = () => + stream.Should().HaveLength(10); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_stream_has_an_unexpected_length_it_should_fail() - { - // Arrange - using var stream = new TestStream { Seekable = true, WithLength = 1 }; + [Fact] + public void When_a_stream_has_an_unexpected_length_it_should_fail() + { + // Arrange + using var stream = new TestStream { Seekable = true, WithLength = 1 }; - // Act - Action act = () => - stream.Should().HaveLength(10, "we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().HaveLength(10, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected the length of stream to be 10* *failure message*, but it was 1*."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected the length of stream to be 10* *failure message*, but it was 1*."); + } - [Theory] - [MemberData(nameof(GetLengthExceptions))] - public void When_a_throwing_stream_should_have_a_length_it_should_fail(Exception exception) - { - // Arrange - using var stream = new ExceptingStream(exception); + [Fact] + public void When_null_have_length_should_fail() + { + // Arrange + TestStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().HaveLength(10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected the length of stream to be 10* *failure message*, but found a reference."); + } + + [Theory] + [MemberData(nameof(StreamAssertionSpecs.GetLengthExceptions), MemberType = typeof(StreamAssertionSpecs))] + public void When_a_throwing_stream_should_have_a_length_it_should_fail(Exception exception) + { + // Arrange + using var stream = new ExceptingStream(exception); - // Act - Action act = () => - stream.Should().HaveLength(10, "we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().HaveLength(10, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected the length of stream to be 10* *failure message*, " + - "but it failed with*GetLengthExceptionMessage*"); + // Assert + act.Should().Throw() + .WithMessage("Expected the length of stream to be 10* *failure message*, " + + "but it failed with*GetLengthExceptionMessage*"); + } } - [Fact] - public void When_null_have_length_should_fail() + public class NotHaveLength { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_a_stream_does_not_have_an_unexpected_length_it_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().HaveLength(10, "we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Seekable = true, WithLength = 1 }; - // Assert - act.Should().Throw() - .WithMessage("Expected the length of stream to be 10* *failure message*, but found a reference."); - } + // Act + Action act = () => + stream.Should().NotHaveLength(10); - [Fact] - public void When_a_stream_does_not_have_an_unexpected_length_it_should_succeed() - { - // Arrange - using var stream = new TestStream { Seekable = true, WithLength = 1 }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotHaveLength(10); + [Fact] + public void When_a_stream_does_have_the_unexpected_length_it_should_fail() + { + // Arrange + using var stream = new TestStream { Seekable = true, WithLength = 10 }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + stream.Should().NotHaveLength(10, "we want to test the failure {0}", "message"); - [Fact] - public void When_a_stream_does_have_the_unexpected_length_it_should_fail() - { - // Arrange - using var stream = new TestStream { Seekable = true, WithLength = 10 }; + // Assert + act.Should().Throw() + .WithMessage("Expected the length of stream not to be 10* *failure message*, but it was."); + } + + [Fact] + public void When_null_not_have_length_should_fail() + { + // Arrange + TestStream stream = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotHaveLength(10, "we want to test the failure {0}", "message"); + }; + + // Assert + act.Should().Throw() + .WithMessage("Expected the length of stream not to be 10* *failure message*, but found a reference."); + } + + [Theory] + [MemberData(nameof(StreamAssertionSpecs.GetLengthExceptions), MemberType = typeof(StreamAssertionSpecs))] + public void When_a_throwing_stream_should_not_have_a_length_it_should_fail(Exception exception) + { + // Arrange + using var stream = new ExceptingStream(exception); - // Act - Action act = () => - stream.Should().NotHaveLength(10, "we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().NotHaveLength(10, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected the length of stream not to be 10* *failure message*, but it was."); + // Assert + act.Should().Throw() + .WithMessage("Expected the length of stream not to be 10* *failure message*, " + + "but it failed with*GetLengthExceptionMessage*"); + } } - [Theory] - [MemberData(nameof(GetLengthExceptions))] - public void When_a_throwing_stream_should_not_have_a_length_it_should_fail(Exception exception) + public static IEnumerable GetLengthExceptions() { - // Arrange - using var stream = new ExceptingStream(exception); - - // Act - Action act = () => - stream.Should().NotHaveLength(10, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the length of stream not to be 10* *failure message*, " + - "but it failed with*GetLengthExceptionMessage*"); + // https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.length#exceptions + yield return new object[] { new IOException("GetLengthExceptionMessage") }; + yield return new object[] { new NotSupportedException("GetLengthExceptionMessage") }; + yield return new object[] { new ObjectDisposedException("GetLengthExceptionMessage") }; } - [Fact] - public void When_null_not_have_length_should_fail() + public class BeReadOnly { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_readonly_stream_be_read_only_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().NotHaveLength(10, "we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Readable = true, Writable = false }; - // Assert - act.Should().Throw() - .WithMessage("Expected the length of stream not to be 10* *failure message*, but found a reference."); - } + // Act + Action act = () => + stream.Should().BeReadOnly(); - #endregion + // Assert + act.Should().NotThrow(); + } - #region BeReadOnly / NotBeReadOnly + [Fact] + public void When_having_a_writable_stream_be_read_only_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = true, Writable = true }; - [Fact] - public void When_having_a_readonly_stream_be_read_only_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = true, Writable = false }; + // Act + Action act = () => + stream.Should().BeReadOnly("we want to test the failure {0}", "message"); - // Act - Action act = () => - stream.Should().BeReadOnly(); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be read-only *failure message*, but it was writable or not readable."); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_having_a_non_readable_stream_be_read_only_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = false, Writable = false }; - [Fact] - public void When_having_a_writable_stream_be_read_only_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = true, Writable = true }; + // Act + Action act = () => + stream.Should().BeReadOnly("we want to test the failure {0}", "message"); - // Act - Action act = () => - stream.Should().BeReadOnly("we want to test the failure {0}", "message"); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be read-only *failure message*, but it was writable or not readable."); + } - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be read-only *failure message*, but it was writable or not readable."); - } - - [Fact] - public void When_having_a_non_readable_stream_be_read_only_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = false, Writable = false }; + [Fact] + public void When_null_be_read_only_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().BeReadOnly("we want to test the failure {0}", "message"); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().BeReadOnly("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be read-only *failure message*, but it was writable or not readable."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be read-only *failure message*, but found a reference."); + } } - [Fact] - public void When_null_be_read_only_should_fail() + public class NotBeReadOnly { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_non_readable_stream_be_not_read_only_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().BeReadOnly("we want to test the failure {0}", "message"); - }; + // Arrange + using var stream = new TestStream { Readable = false, Writable = false }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be read-only *failure message*, but found a reference."); - } + // Act + Action act = () => + stream.Should().NotBeReadOnly(); - [Fact] - public void When_having_a_non_readable_stream_be_not_read_only_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = false, Writable = false }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotBeReadOnly(); + [Fact] + public void When_having_a_writable_stream_be_not_read_only_should_succeed() + { + // Arrange + using var stream = new TestStream { Readable = true, Writable = true }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + stream.Should().NotBeReadOnly(); - [Fact] - public void When_having_a_writable_stream_be_not_read_only_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = true, Writable = true }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotBeReadOnly(); + [Fact] + public void When_having_a_readonly_stream_be_not_read_only_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = true, Writable = false }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + stream.Should().NotBeReadOnly("we want to test the failure {0}", "message"); - [Fact] - public void When_having_a_readonly_stream_be_not_read_only_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = true, Writable = false }; + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be read-only *failure message*, but it was."); + } + + [Fact] + public void When_null_not_be_read_only_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().NotBeReadOnly("we want to test the failure {0}", "message"); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotBeReadOnly("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be read-only *failure message*, but it was."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be read-only *failure message*, but found a reference."); + } } - [Fact] - public void When_null_not_be_read_only_should_fail() + public class BeWriteOnly { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_writeonly_stream_be_write_only_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().NotBeReadOnly("we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be read-only *failure message*, but found a reference."); - } + // Arrange + using var stream = new TestStream { Readable = false, Writable = true }; - #endregion + // Act + Action act = () => + stream.Should().BeWriteOnly(); - #region BeWriteOnly / NotBeWriteOnly + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_having_a_writeonly_stream_be_write_only_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = false, Writable = true }; + [Fact] + public void When_having_a_readable_stream_be_write_only_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = true, Writable = true }; - // Act - Action act = () => - stream.Should().BeWriteOnly(); + // Act + Action act = () => + stream.Should().BeWriteOnly("we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be write-only *failure message*, but it was readable or not writable."); + } - [Fact] - public void When_having_a_readable_stream_be_write_only_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = true, Writable = true }; + [Fact] + public void When_having_a_non_writable_stream_be_write_only_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = false, Writable = false }; - // Act - Action act = () => - stream.Should().BeWriteOnly("we want to test the failure {0}", "message"); + // Act + Action act = () => + stream.Should().BeWriteOnly("we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be write-only *failure message*, but it was readable or not writable."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be write-only *failure message*, but it was readable or not writable."); + } - [Fact] - public void When_having_a_non_writable_stream_be_write_only_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = false, Writable = false }; + [Fact] + public void When_null_be_write_only_should_fail() + { + // Arrange + TestStream stream = null; - // Act - Action act = () => - stream.Should().BeWriteOnly("we want to test the failure {0}", "message"); + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().BeWriteOnly("we want to test the failure {0}", "message"); + }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be write-only *failure message*, but it was readable or not writable."); + // Assert + act.Should().Throw() + .WithMessage("Expected stream to be write-only *failure message*, but found a reference."); + } } - [Fact] - public void When_null_be_write_only_should_fail() + public class NotBeWriteOnly { - // Arrange - TestStream stream = null; - - // Act - Action act = () => + [Fact] + public void When_having_a_non_writable_stream_be_not_write_only_should_succeed() { - using var _ = new AssertionScope(); - stream.Should().BeWriteOnly("we want to test the failure {0}", "message"); - }; - - // Assert - act.Should().Throw() - .WithMessage("Expected stream to be write-only *failure message*, but found a reference."); - } - - [Fact] - public void When_having_a_non_writable_stream_be_not_write_only_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = false, Writable = false }; - - // Act - Action act = () => - stream.Should().NotBeWriteOnly(); + // Arrange + using var stream = new TestStream { Readable = false, Writable = false }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + stream.Should().NotBeWriteOnly(); - [Fact] - public void When_having_a_readable_stream_be_not_write_only_should_succeed() - { - // Arrange - using var stream = new TestStream { Readable = true, Writable = true }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotBeWriteOnly(); + [Fact] + public void When_having_a_readable_stream_be_not_write_only_should_succeed() + { + // Arrange + using var stream = new TestStream { Readable = true, Writable = true }; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + stream.Should().NotBeWriteOnly(); - [Fact] - public void When_having_a_writeonly_stream_be_not_write_only_should_fail() - { - // Arrange - using var stream = new TestStream { Readable = false, Writable = true }; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - stream.Should().NotBeWriteOnly("we want to test the failure {0}", "message"); + [Fact] + public void When_having_a_writeonly_stream_be_not_write_only_should_fail() + { + // Arrange + using var stream = new TestStream { Readable = false, Writable = true }; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be write-only *failure message*, but it was."); - } + // Act + Action act = () => + stream.Should().NotBeWriteOnly("we want to test the failure {0}", "message"); - [Fact] - public void When_null_not_be_write_only_should_fail() - { - // Arrange - TestStream stream = null; + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be write-only *failure message*, but it was."); + } - // Act - Action act = () => + [Fact] + public void When_null_not_be_write_only_should_fail() { - using var _ = new AssertionScope(); - stream.Should().NotBeWriteOnly("we want to test the failure {0}", "message"); - }; + // Arrange + TestStream stream = null; - // Assert - act.Should().Throw() - .WithMessage("Expected stream not to be write-only *failure message*, but found a reference."); - } + // Act + Action act = () => + { + using var _ = new AssertionScope(); + stream.Should().NotBeWriteOnly("we want to test the failure {0}", "message"); + }; - #endregion + // Assert + act.Should().Throw() + .WithMessage("Expected stream not to be write-only *failure message*, but found a reference."); + } + } } internal class ExceptingStream : Stream From 68f41b931d6f72ace3b3c56a1aa4798265b03a5a Mon Sep 17 00:00:00 2001 From: ITaluone <44049228+ITaluone@users.noreply.github.com> Date: Sat, 23 Apr 2022 14:40:08 +0200 Subject: [PATCH 39/48] Add overload to `HaveElement()` to be able to assert on occurrences for `XDocument` and `XElement` (#1880) --- .../Xml/XDocumentAssertions.cs | 99 ++++++++++- .../Xml/XElementAssertions.cs | 78 ++++++++ .../FluentAssertions/net47.verified.txt | 4 + .../FluentAssertions/net6.0.verified.txt | 4 + .../netcoreapp2.1.verified.txt | 4 + .../netcoreapp3.0.verified.txt | 4 + .../netstandard2.0.verified.txt | 4 + .../netstandard2.1.verified.txt | 4 + .../Xml/XDocumentAssertionSpecs.cs | 166 ++++++++++++++++++ .../Xml/XElementAssertionSpecs.cs | 146 +++++++++++++++ docs/_pages/releases.md | 1 + docs/_pages/xml.md | 2 + 12 files changed, 510 insertions(+), 6 deletions(-) diff --git a/Src/FluentAssertions/Xml/XDocumentAssertions.cs b/Src/FluentAssertions/Xml/XDocumentAssertions.cs index dd41a59357..668e5cebfb 100644 --- a/Src/FluentAssertions/Xml/XDocumentAssertions.cs +++ b/Src/FluentAssertions/Xml/XDocumentAssertions.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Xml; using System.Xml.Linq; @@ -132,7 +134,7 @@ public AndConstraint NotBeEquivalentTo(XDocument unexpected params object[] becauseArgs) { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), - "Cannot assert the document has a root element if the expected name is *"); + "Cannot assert the document has a root element if the expected name is ."); return HaveRoot(XNamespace.None + expected, because, becauseArgs); } @@ -157,7 +159,7 @@ public AndConstraint NotBeEquivalentTo(XDocument unexpected } Guard.ThrowIfArgumentIsNull(expected, nameof(expected), - "Cannot assert the document has a root element if the expected name is *"); + "Cannot assert the document has a root element if the expected name is ."); XElement root = Subject.Root; @@ -176,7 +178,7 @@ public AndConstraint NotBeEquivalentTo(XDocument unexpected /// child element with the specified name. /// /// - /// The name of the expected child element of the current document's Root element. + /// The name of the expected child element of the current document's element. /// /// /// A formatted phrase as is supported by explaining why the assertion @@ -189,17 +191,43 @@ public AndConstraint NotBeEquivalentTo(XDocument unexpected params object[] becauseArgs) { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), - "Cannot assert the document has an element if the expected name is *"); + "Cannot assert the document has an element if the expected name is ."); return HaveElement(XNamespace.None + expected, because, becauseArgs); } + /// + /// Asserts that the element of the current has the specified occurrence of + /// child elements with the specified name. + /// + /// + /// The name of the expected child element of the current document's element. + /// + /// + /// A constraint specifying the number of times the specified elements should appear. + /// + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public AndWhichConstraint> HaveElement(string expected, + OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull(expected, nameof(expected), + "Cannot assert the document has an element if the expected name is ."); + + return HaveElement(XNamespace.None + expected, occurrenceConstraint, because, becauseArgs); + } + /// /// Asserts that the element of the current has a direct /// child element with the specified name. /// /// - /// The full name of the expected child element of the current document's Root element. + /// The full name of the expected child element of the current document's element. /// /// /// A formatted phrase as is supported by explaining why the assertion @@ -217,7 +245,7 @@ public AndConstraint NotBeEquivalentTo(XDocument unexpected } Guard.ThrowIfArgumentIsNull(expected, nameof(expected), - "Cannot assert the document has an element if the expected name is *"); + "Cannot assert the document has an element if the expected name is ."); Execute.Assertion .ForCondition(Subject.Root is not null) @@ -237,6 +265,65 @@ public AndConstraint NotBeEquivalentTo(XDocument unexpected return new AndWhichConstraint(this, xElement); } + /// + /// Asserts that the element of the current has the specified occurrence of + /// child elements with the specified name. + /// + /// + /// The full name of the expected child element of the current document's element. + /// + /// + /// A constraint specifying the number of times the specified elements should appear. + /// + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public AndWhichConstraint> HaveElement(XName expected, + OccurrenceConstraint occurrenceConstraint, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull(expected, nameof(expected), + "Cannot assert the document has an element count if the element name is ."); + + bool success = Execute.Assertion + .ForCondition(Subject is not null) + .BecauseOf(because, becauseArgs) + .FailWith("Cannot assert the count if the document itself is ."); + + IEnumerable xElements = Enumerable.Empty(); + + if (success) + { + var root = Subject.Root; + success = Execute.Assertion + .ForCondition(root is not null) + .BecauseOf(because, becauseArgs) + .FailWith( + "Expected {context:subject} to have root element containing a child {0}{reason}, but it has no root element.", + expected.ToString()); + + if (success) + { + xElements = root.Elements(expected); + int actual = xElements.Count(); + + Execute.Assertion + .ForConstraint(occurrenceConstraint, actual) + .BecauseOf(because, becauseArgs) + .FailWith( + $"Expected {{context:subject}} to have a root element containing a child {{0}} " + + $"{{expectedOccurrence}}{{reason}}, but found it {actual.Times()}.", + expected.ToString()); + } + } + + return new AndWhichConstraint>(this, xElements); + } + /// /// Returns the type of the subject the assertion applies on. /// diff --git a/Src/FluentAssertions/Xml/XElementAssertions.cs b/Src/FluentAssertions/Xml/XElementAssertions.cs index c0f2a0d4cb..4e9b6e2876 100644 --- a/Src/FluentAssertions/Xml/XElementAssertions.cs +++ b/Src/FluentAssertions/Xml/XElementAssertions.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Xml; using System.Xml.Linq; using FluentAssertions.Common; @@ -288,6 +290,82 @@ public AndConstraint HaveValue(string expected, string becau return new AndWhichConstraint(this, xElement); } + /// + /// Asserts that the of the current has the specified occurrence of + /// child elements with the specified name. + /// + /// + /// The full name of the expected child element of the current element's . + /// + /// + /// A constraint specifying the number of times the specified elements should appear. + /// + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public AndWhichConstraint> HaveElement(XName expected, + OccurrenceConstraint occurrenceConstraint, string because = "", + params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull(expected, nameof(expected), + "Cannot assert the element has an element count if the element name is ."); + + bool success = Execute.Assertion + .ForCondition(Subject is not null) + .BecauseOf(because, becauseArgs) + .FailWith( + "Expected {context:subject} to have an element with count of {0}{reason}, but the element itself is .", + expected.ToString()); + + IEnumerable xElements = Enumerable.Empty(); + + if (success) + { + xElements = Subject.Elements(expected); + int actual = xElements.Count(); + + Execute.Assertion + .ForConstraint(occurrenceConstraint, actual) + .BecauseOf(because, becauseArgs) + .FailWith( + $"Expected {{context:subject}} to have an element {{0}} {{expectedOccurrence}}" + + $"{{reason}}, but found it {actual.Times()}.", + expected.ToString()); + } + + return new AndWhichConstraint>(this, xElements); + } + + /// + /// Asserts that the of the current has the specified occurrence of + /// child elements with the specified name. + /// + /// + /// The name of the expected child element of the current element's . + /// + /// + /// A constraint specifying the number of times the specified elements should appear. + /// + /// + /// A formatted phrase as is supported by explaining why the assertion + /// is needed. If the phrase does not start with the word because, it is prepended automatically. + /// + /// + /// Zero or more objects to format using the placeholders in . + /// + public AndWhichConstraint> HaveElement(string expected, + OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) + { + Guard.ThrowIfArgumentIsNull(expected, nameof(expected), + "Cannot assert the element has an element if the expected name is ."); + + return HaveElement(XNamespace.None + expected, occurrenceConstraint, because, becauseArgs); + } + /// /// Returns the type of the subject the assertion applies on. /// diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt index a86a4adf5e..8a2d1f8e14 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net47.verified.txt @@ -2685,6 +2685,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint BeEquivalentTo(System.Xml.Linq.XDocument expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XDocument unexpected, string because = "", params object[] becauseArgs) { } @@ -2700,6 +2702,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint HaveAttribute(System.Xml.Linq.XName expectedName, string expectedValue, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBeEquivalentTo(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt index 45386470fb..1b6faed215 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/net6.0.verified.txt @@ -2805,6 +2805,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint BeEquivalentTo(System.Xml.Linq.XDocument expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XDocument unexpected, string because = "", params object[] becauseArgs) { } @@ -2820,6 +2822,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint HaveAttribute(System.Xml.Linq.XName expectedName, string expectedValue, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBeEquivalentTo(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt index 32f7082f3f..a9f68eb68d 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp2.1.verified.txt @@ -2687,6 +2687,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint BeEquivalentTo(System.Xml.Linq.XDocument expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XDocument unexpected, string because = "", params object[] becauseArgs) { } @@ -2702,6 +2704,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint HaveAttribute(System.Xml.Linq.XName expectedName, string expectedValue, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBeEquivalentTo(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt index cd16c72a15..8c7f8490bc 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netcoreapp3.0.verified.txt @@ -2687,6 +2687,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint BeEquivalentTo(System.Xml.Linq.XDocument expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XDocument unexpected, string because = "", params object[] becauseArgs) { } @@ -2702,6 +2704,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint HaveAttribute(System.Xml.Linq.XName expectedName, string expectedValue, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBeEquivalentTo(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt index e7ef120517..1fc893363c 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.0.verified.txt @@ -2637,6 +2637,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint BeEquivalentTo(System.Xml.Linq.XDocument expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XDocument unexpected, string because = "", params object[] becauseArgs) { } @@ -2652,6 +2654,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint HaveAttribute(System.Xml.Linq.XName expectedName, string expectedValue, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBeEquivalentTo(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } diff --git a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt index f17275a93c..dedd54bad1 100644 --- a/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt +++ b/Tests/Approval.Tests/ApprovedApi/FluentAssertions/netstandard2.1.verified.txt @@ -2687,6 +2687,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint BeEquivalentTo(System.Xml.Linq.XDocument expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveRoot(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XDocument unexpected, string because = "", params object[] becauseArgs) { } @@ -2702,6 +2704,8 @@ namespace FluentAssertions.Xml public FluentAssertions.AndConstraint HaveAttribute(System.Xml.Linq.XName expectedName, string expectedValue, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndWhichConstraint HaveElement(System.Xml.Linq.XName expected, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(string expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } + public FluentAssertions.AndWhichConstraint> HaveElement(System.Xml.Linq.XName expected, FluentAssertions.OccurrenceConstraint occurrenceConstraint, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint HaveValue(string expected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBe(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } public FluentAssertions.AndConstraint NotBeEquivalentTo(System.Xml.Linq.XElement unexpected, string because = "", params object[] becauseArgs) { } diff --git a/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs index e7c9767ad4..837a6b0422 100644 --- a/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs @@ -1,5 +1,6 @@ using System; using System.Xml.Linq; +using FluentAssertions.Execution; using FluentAssertions.Formatting; using Xunit; using Xunit.Sdk; @@ -1158,5 +1159,170 @@ public void When_asserting_a_document_has_an_element_with_a_null_xname_it_should } #endregion + + #region HaveElement (with occurrence) + + [Fact] + public void When_asserting_document_has_two_child_elements_and_it_does_it_succeeds() + { + // Arrange + var document = XDocument.Parse( + @" + + + "); + + // Act / Assert + document.Should().HaveElement("child", Exactly.Twice()); + } + + [Fact] + public void Asserting_document_null_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() + { + // Arrange + XDocument document = null; + + // Act + Action act = () => + { + using (new AssertionScope()) + { + document.Should().HaveElement("child", Exactly.Twice()); + document.Should().HaveElement("child", Exactly.Twice()); + } + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Asserting_with_document_root_null_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() + { + // Arrange + XDocument document = new(); + + // Act + Action act = () => + { + using (new AssertionScope()) + { + document.Should().HaveElement("child", Exactly.Twice()); + document.Should().HaveElement("child", Exactly.Twice()); + } + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_document_has_two_child_elements_but_it_does_have_three_it_fails() + { + // Arrange + var document = XDocument.Parse( + @" + + + + "); + + // Act + Action act = () => document.Should().HaveElement("child", Exactly.Twice()); + + // Assert + act.Should().Throw() + .WithMessage("Expected document to have a root element containing a child \"child\"*exactly*2 times, but found it 3 times*"); + } + + [Fact] + public void Document_is_valid_and_expected_null_with_string_overload_it_fails() + { + // Arrange + var document = XDocument.Parse( + @" + + + + "); + + // Act + Action act = () => document.Should().HaveElement(null, Exactly.Twice()); + + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has an element if the expected name is .*"); + } + + [Fact] + public void Document_is_valid_and_expected_null_with_x_name_overload_it_fails() + { + // Arrange + var document = XDocument.Parse( + @" + + + + "); + + // Act + Action act = () => document.Should().HaveElement((XName)null, Exactly.Twice()); + + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has an element count if the element name is .*"); + } + + [Fact] + public void Chaining_after_a_successful_occurrence_check_does_continue_the_assertion() + { + // Arrange + var document = XDocument.Parse( + @" + + + + "); + + // Act / Assert + document.Should().HaveElement("child", AtLeast.Twice()) + .Which.Should().NotBeNull(); + } + + [Fact] + public void Chaining_after_a_non_successful_occurrence_check_does_not_continue_the_assertion() + { + // Arrange + var document = XDocument.Parse( + @" + + + + "); + + // Act + Action act = () => document.Should().HaveElement("child", Exactly.Once()) + .Which.Should().NotBeNull(); + + // Assert + act.Should().Throw() + .WithMessage("Expected document to have a root element containing a child \"child\"*exactly*1 time, but found it 3 times."); + } + + [Fact] + public void When_asserting_a_null_document_to_have_an_element_count_it_should_fail() + { + // Arrange + XDocument xDocument = null; + + // Act + Action act = () => xDocument.Should().HaveElement("child", AtLeast.Once()); + + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the count if the document itself is ."); + } + + #endregion } } diff --git a/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs index 3f3364b47a..176bd01d27 100644 --- a/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs @@ -1,5 +1,6 @@ using System; using System.Xml.Linq; +using FluentAssertions.Execution; using Xunit; using Xunit.Sdk; @@ -1228,5 +1229,150 @@ public void When_asserting_element_has_a_child_element_with_an_empty_name_it_sho } #endregion + + #region HaveElement (with occurrence) + + [Fact] + public void Element_has_two_child_elements_and_it_expected_does_it_succeeds() + { + // Arrange + var element = XElement.Parse( + @" + + + "); + + // Act / Assert + element.Should().HaveElement("child", Exactly.Twice()); + } + + [Fact] + public void Asserting_element_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() + { + // Arrange + XElement element = null; + + // Act + Action act = () => + { + using (new AssertionScope()) + { + element.Should().HaveElement("child", Exactly.Twice()); + element.Should().HaveElement("child", Exactly.Twice()); + } + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Element_has_two_child_elements_and_three_expected_it_fails() + { + // Arrange + var element = XElement.Parse( + @" + + + + "); + + // Act + Action act = () => element.Should().HaveElement("child", Exactly.Twice()); + + // Assert + act.Should().Throw() + .WithMessage("Expected element to have an element \"child\"*exactly*2 times, but found it 3 times."); + } + + [Fact] + public void Element_is_valid_and_expected_null_with_string_overload_it_fails() + { + // Arrange + var element = XElement.Parse( + @" + + + + "); + + // Act + Action act = () => element.Should().HaveElement(null, Exactly.Twice()); + + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the element has an element if the expected name is .*"); + } + + [Fact] + public void Element_is_valid_and_expected_null_with_x_name_overload_it_fails() + { + // Arrange + var element = XElement.Parse( + @" + + + + "); + + // Act + Action act = () => element.Should().HaveElement((XName)null, Exactly.Twice()); + + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the element has an element count if the element name is .*"); + } + + [Fact] + public void Chaining_after_a_successful_occurrence_check_does_continue_the_assertion() + { + // Arrange + var element = XElement.Parse( + @" + + + + "); + + // Act / Assert + element.Should().HaveElement("child", AtLeast.Twice()) + .Which.Should().NotBeNull(); + } + + [Fact] + public void Chaining_after_a_non_successful_occurrence_check_does_not_continue_the_assertion() + { + // Arrange + var element = XElement.Parse( + @" + + + + "); + + // Act + Action act = () => element.Should().HaveElement("child", Exactly.Once()) + .Which.Should().NotBeNull(); + + // Assert + act.Should().Throw() + .WithMessage("Expected element to have an element \"child\"*exactly*1 time, but found it 3 times."); + } + + [Fact] + public void Null_element_is_expected_to_have_an_element_count_it_should_fail() + { + // Arrange + XElement xElement = null; + + // Act + Action act = () => xElement.Should().HaveElement("child", AtLeast.Once()); + + // Assert + act.Should().Throw().WithMessage( + "Expected* to have an element with count of *, but the element itself is ."); + } + + #endregion } } diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index 4953f2f24f..3011877865 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -14,6 +14,7 @@ sidebar: * Added the ability to exclude fields & properties marked as non-browsable in the code editor from structural equality comparisons - [#1807](https://github.com/fluentassertions/fluentassertions/pull/1807) & [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) * Assertions on the collection types in System.Data (`DataSet.Tables`, `DataTable.Columns`, `DataTable.Rows`) have been restored - [#1812](https://github.com/fluentassertions/fluentassertions/pull/1812) * Add `For`/`Exclude` to allow exclusion of members inside a collection - [#1782](https://github.com/fluentassertions/fluentassertions/pull/1782) +* Added overload for `HaveElement` for `XDocument` and `XElement` to assert on number of XML nodes - [#1880](https://github.com/fluentassertions/fluentassertions/pull/1880) ## 6.6.0 diff --git a/docs/_pages/xml.md b/docs/_pages/xml.md index a1447f0c5b..b01a40ba40 100644 --- a/docs/_pages/xml.md +++ b/docs/_pages/xml.md @@ -12,6 +12,8 @@ Fluent Assertions has support for assertions on several of the LINQ-to-XML class ```csharp xDocument.Should().HaveRoot("configuration"); xDocument.Should().HaveElement("settings"); +xDocument.Should().HaveElement("settings", Exactly.Once()); +xDocument.Should().HaveElement("settings", AtLeast.Twice()); xElement.Should().HaveValue("36"); xElement.Should().HaveAttribute("age", "36"); From 28883bad06ac61b732b1043c27451fca2cc4b931 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Sat, 23 Apr 2022 21:03:01 +0200 Subject: [PATCH 40/48] Seperate all `Xml` assertions into nested classes --- .../Xml/XAttributeAssertionSpecs.cs | 603 ++--- .../Xml/XDocumentAssertionSpecs.cs | 2027 ++++++++-------- .../Xml/XElementAssertionSpecs.cs | 2142 +++++++++-------- .../Xml/XmlElementAssertionSpecs.cs | 844 +++---- .../Xml/XmlNodeAssertionSpecs.cs | 1065 ++++---- 5 files changed, 3347 insertions(+), 3334 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Xml/XAttributeAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XAttributeAssertionSpecs.cs index f0958a42f9..46b318cef2 100644 --- a/Tests/FluentAssertions.Specs/Xml/XAttributeAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XAttributeAssertionSpecs.cs @@ -7,319 +7,322 @@ namespace FluentAssertions.Specs.Xml { public class XAttributeAssertionSpecs { - #region Be / NotBe - - [Fact] - public void When_asserting_an_xml_attribute_is_equal_to_the_same_xml_attribute_it_should_succeed() - { - // Arrange - var attribute = new XAttribute("name", "value"); - var sameXAttribute = new XAttribute("name", "value"); - - // Act - Action act = () => - attribute.Should().Be(sameXAttribute); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_attribute_is_equal_to_a_different_xml_attribute_it_should_fail_with_descriptive_message() - { - // Arrange - var theAttribute = new XAttribute("name", "value"); - var otherAttribute = new XAttribute("name2", "value"); - - // Act - Action act = () => - theAttribute.Should().Be(otherAttribute, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - $"Expected theAttribute to be {otherAttribute} because we want to test the failure message, but found {theAttribute}."); - } - - [Fact] - public void When_both_subject_and_expected_are_null_it_succeeds() - { - XAttribute theAttribute = null; - - // Act - Action act = () => theAttribute.Should().Be(null); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_the_expected_attribute_is_null_then_it_fails() - { - XAttribute theAttribute = null; - - // Act - Action act = () => - theAttribute.Should().Be(new XAttribute("name", "value"), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected theAttribute to be name=\"value\" *failure message*, but found ."); - } - - [Fact] - public void When_the_attribute_is_expected_to_equal_null_it_fails() - { - XAttribute theAttribute = new XAttribute("name", "value"); - - // Act - Action act = () => theAttribute.Should().Be(null, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected theAttribute to be *failure message*, but found name=\"value\"."); - } - - [Fact] - public void When_asserting_an_xml_attribute_is_not_equal_to_a_different_xml_attribute_it_should_succeed() - { - // Arrange - var attribute = new XAttribute("name", "value"); - var otherXAttribute = new XAttribute("name2", "value"); - - // Act - Action act = () => - attribute.Should().NotBe(otherXAttribute); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_attribute_is_not_equal_to_the_same_xml_attribute_it_should_throw() - { - // Arrange - var theAttribute = new XAttribute("name", "value"); - var sameXAttribute = theAttribute; - - // Act - Action act = () => - theAttribute.Should().NotBe(sameXAttribute); - - // Assert - act.Should().Throw().WithMessage( - "Did not expect theAttribute to be name=\"value\"."); - } - - [Fact] - public void When_asserting_an_xml_attribute_is_not_equal_to_the_same_xml_attribute_it_should_throw_with_descriptive_message() - { - // Arrange - var theAttribute = new XAttribute("name", "value"); - var sameAttribute = theAttribute; - - // Act - Action act = () => - theAttribute.Should().NotBe(sameAttribute, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - $"Did not expect theAttribute to be {sameAttribute} because we want to test the failure message."); - } - - [Fact] - public void When_a_null_attribute_is_not_supposed_to_be_an_attribute_it_succeeds() - { - // Arrange - XAttribute theAttribute = null; - - // Act - Action act = () => theAttribute.Should().NotBe(new XAttribute("name", "value")); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_an_attribute_is_not_supposed_to_be_null_it_succeeds() - { - // Arrange - XAttribute theAttribute = new XAttribute("name", "value"); - - // Act - Action act = () => theAttribute.Should().NotBe(null); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_null_attribute_is_not_supposed_to_be_null_it_fails() - { - // Arrange - XAttribute theAttribute = null; - - // Act - Action act = () => theAttribute.Should().NotBe(null, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect theAttribute to be *failure message*."); - } - - #endregion - - #region BeNull / NotBeNull - - [Fact] - public void When_asserting_a_null_xml_attribute_is_null_it_should_succeed() - { - // Arrange - XAttribute attribute = null; - - // Act - Action act = () => - attribute.Should().BeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_non_null_xml_attribute_is_null_it_should_fail() - { - // Arrange - var theAttribute = new XAttribute("name", "value"); - - // Act - Action act = () => - theAttribute.Should().BeNull(); - - // Assert - act.Should().Throw().WithMessage( - "Expected theAttribute to be , but found name=\"value\"."); - } - - [Fact] - public void When_asserting_a_non_null_xml_attribute_is_null_it_should_fail_with_descriptive_message() - { - // Arrange - var theAttribute = new XAttribute("name", "value"); - - // Act - Action act = () => - theAttribute.Should().BeNull("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - $"Expected theAttribute to be because we want to test the failure message, but found {theAttribute}."); - } - - [Fact] - public void When_asserting_a_non_null_xml_attribute_is_not_null_it_should_succeed() - { - // Arrange - var attribute = new XAttribute("name", "value"); - - // Act - Action act = () => - attribute.Should().NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_null_xml_attribute_is_not_null_it_should_fail() + public class Be { - // Arrange - XAttribute theAttribute = null; - - // Act - Action act = () => - theAttribute.Should().NotBeNull(); - - // Assert - act.Should().Throw().WithMessage( - "Expected theAttribute not to be ."); - } - - [Fact] - public void When_asserting_a_null_xml_attribute_is_not_null_it_should_fail_with_descriptive_message() - { - // Arrange - XAttribute theAttribute = null; - - // Act - Action act = () => - theAttribute.Should().NotBeNull("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theAttribute not to be because we want to test the failure message."); + [Fact] + public void When_asserting_an_xml_attribute_is_equal_to_the_same_xml_attribute_it_should_succeed() + { + // Arrange + var attribute = new XAttribute("name", "value"); + var sameXAttribute = new XAttribute("name", "value"); + + // Act + Action act = () => + attribute.Should().Be(sameXAttribute); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_attribute_is_equal_to_a_different_xml_attribute_it_should_fail_with_descriptive_message() + { + // Arrange + var theAttribute = new XAttribute("name", "value"); + var otherAttribute = new XAttribute("name2", "value"); + + // Act + Action act = () => + theAttribute.Should().Be(otherAttribute, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + $"Expected theAttribute to be {otherAttribute} because we want to test the failure message, but found {theAttribute}."); + } + + [Fact] + public void When_both_subject_and_expected_are_null_it_succeeds() + { + XAttribute theAttribute = null; + + // Act + Action act = () => theAttribute.Should().Be(null); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_the_expected_attribute_is_null_then_it_fails() + { + XAttribute theAttribute = null; + + // Act + Action act = () => + theAttribute.Should().Be(new XAttribute("name", "value"), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected theAttribute to be name=\"value\" *failure message*, but found ."); + } + + [Fact] + public void When_the_attribute_is_expected_to_equal_null_it_fails() + { + XAttribute theAttribute = new XAttribute("name", "value"); + + // Act + Action act = () => theAttribute.Should().Be(null, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected theAttribute to be *failure message*, but found name=\"value\"."); + } } - #endregion - - #region HaveValue - - [Fact] - public void When_asserting_attribute_has_a_specific_value_and_it_does_it_should_succeed() + public class NotBe { - // Arrange - var attribute = new XAttribute("age", "36"); - - // Act - Action act = () => - attribute.Should().HaveValue("36"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_an_xml_attribute_is_not_equal_to_a_different_xml_attribute_it_should_succeed() + { + // Arrange + var attribute = new XAttribute("name", "value"); + var otherXAttribute = new XAttribute("name2", "value"); + + // Act + Action act = () => + attribute.Should().NotBe(otherXAttribute); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_attribute_is_not_equal_to_the_same_xml_attribute_it_should_throw() + { + // Arrange + var theAttribute = new XAttribute("name", "value"); + var sameXAttribute = theAttribute; + + // Act + Action act = () => + theAttribute.Should().NotBe(sameXAttribute); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect theAttribute to be name=\"value\"."); + } + + [Fact] + public void When_asserting_an_xml_attribute_is_not_equal_to_the_same_xml_attribute_it_should_throw_with_descriptive_message() + { + // Arrange + var theAttribute = new XAttribute("name", "value"); + var sameAttribute = theAttribute; + + // Act + Action act = () => + theAttribute.Should().NotBe(sameAttribute, "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + $"Did not expect theAttribute to be {sameAttribute} because we want to test the failure message."); + } + + [Fact] + public void When_a_null_attribute_is_not_supposed_to_be_an_attribute_it_succeeds() + { + // Arrange + XAttribute theAttribute = null; + + // Act + Action act = () => theAttribute.Should().NotBe(new XAttribute("name", "value")); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_an_attribute_is_not_supposed_to_be_null_it_succeeds() + { + // Arrange + XAttribute theAttribute = new XAttribute("name", "value"); + + // Act + Action act = () => theAttribute.Should().NotBe(null); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_null_attribute_is_not_supposed_to_be_null_it_fails() + { + // Arrange + XAttribute theAttribute = null; + + // Act + Action act = () => theAttribute.Should().NotBe(null, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect theAttribute to be *failure message*."); + } } - [Fact] - public void When_asserting_attribute_has_a_specific_value_but_it_has_a_different_value_it_should_throw() + public class BeNull { - // Arrange - var theAttribute = new XAttribute("age", "36"); - - // Act - Action act = () => - theAttribute.Should().HaveValue("16"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theAttribute \"age\" to have value \"16\", but found \"36\"."); + [Fact] + public void When_asserting_a_null_xml_attribute_is_null_it_should_succeed() + { + // Arrange + XAttribute attribute = null; + + // Act + Action act = () => + attribute.Should().BeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_non_null_xml_attribute_is_null_it_should_fail() + { + // Arrange + var theAttribute = new XAttribute("name", "value"); + + // Act + Action act = () => + theAttribute.Should().BeNull(); + + // Assert + act.Should().Throw().WithMessage( + "Expected theAttribute to be , but found name=\"value\"."); + } + + [Fact] + public void When_asserting_a_non_null_xml_attribute_is_null_it_should_fail_with_descriptive_message() + { + // Arrange + var theAttribute = new XAttribute("name", "value"); + + // Act + Action act = () => + theAttribute.Should().BeNull("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + $"Expected theAttribute to be because we want to test the failure message, but found {theAttribute}."); + } } - [Fact] - public void When_asserting_attribute_has_a_specific_value_but_it_has_a_different_value_it_should_throw_with_descriptive_message() + public class NotBeNull { - // Arrange - var theAttribute = new XAttribute("age", "36"); - - // Act - Action act = () => - theAttribute.Should().HaveValue("16", "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theAttribute \"age\" to have value \"16\" because we want to test the failure message, but found \"36\"."); + [Fact] + public void When_asserting_a_non_null_xml_attribute_is_not_null_it_should_succeed() + { + // Arrange + var attribute = new XAttribute("name", "value"); + + // Act + Action act = () => + attribute.Should().NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_null_xml_attribute_is_not_null_it_should_fail() + { + // Arrange + XAttribute theAttribute = null; + + // Act + Action act = () => + theAttribute.Should().NotBeNull(); + + // Assert + act.Should().Throw().WithMessage( + "Expected theAttribute not to be ."); + } + + [Fact] + public void When_asserting_a_null_xml_attribute_is_not_null_it_should_fail_with_descriptive_message() + { + // Arrange + XAttribute theAttribute = null; + + // Act + Action act = () => + theAttribute.Should().NotBeNull("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theAttribute not to be because we want to test the failure message."); + } } - [Fact] - public void When_an_attribute_is_null_then_have_value_should_fail() + public class HaveValue { - XAttribute theAttribute = null; - - // Act - Action act = () => - theAttribute.Should().HaveValue("value", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the attribute to have value \"value\" *failure message*, but theAttribute is ."); + [Fact] + public void When_asserting_attribute_has_a_specific_value_and_it_does_it_should_succeed() + { + // Arrange + var attribute = new XAttribute("age", "36"); + + // Act + Action act = () => + attribute.Should().HaveValue("36"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_attribute_has_a_specific_value_but_it_has_a_different_value_it_should_throw() + { + // Arrange + var theAttribute = new XAttribute("age", "36"); + + // Act + Action act = () => + theAttribute.Should().HaveValue("16"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theAttribute \"age\" to have value \"16\", but found \"36\"."); + } + + [Fact] + public void When_asserting_attribute_has_a_specific_value_but_it_has_a_different_value_it_should_throw_with_descriptive_message() + { + // Arrange + var theAttribute = new XAttribute("age", "36"); + + // Act + Action act = () => + theAttribute.Should().HaveValue("16", "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theAttribute \"age\" to have value \"16\" because we want to test the failure message, but found \"36\"."); + } + + [Fact] + public void When_an_attribute_is_null_then_have_value_should_fail() + { + XAttribute theAttribute = null; + + // Act + Action act = () => + theAttribute.Should().HaveValue("value", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the attribute to have value \"value\" *failure message*, but theAttribute is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs index 837a6b0422..611b108557 100644 --- a/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs @@ -9,1320 +9,1323 @@ namespace FluentAssertions.Specs.Xml { public class XDocumentAssertionSpecs { - #region Be / NotBe - - [Fact] - public void When_asserting_a_xml_document_is_equal_to_the_same_xml_document_it_should_succeed() - { - // Arrange - var document = new XDocument(); - var sameXDocument = document; - - // Act - Action act = () => - document.Should().Be(sameXDocument); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_xml_document_is_equal_to_a_different_xml_document_it_should_fail() + public class Be { - // Arrange - var theDocument = new XDocument(); - var otherXDocument = new XDocument(); + [Fact] + public void When_asserting_a_xml_document_is_equal_to_the_same_xml_document_it_should_succeed() + { + // Arrange + var document = new XDocument(); + var sameXDocument = document; - // Act - Action act = () => - theDocument.Should().Be(otherXDocument); + // Act + Action act = () => + document.Should().Be(sameXDocument); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to be [XML document without root element], but found [XML document without root element]."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_the_expected_element_is_null_it_fails() - { - // Arrange - XDocument theDocument = null; + [Fact] + public void When_asserting_a_xml_document_is_equal_to_a_different_xml_document_it_should_fail() + { + // Arrange + var theDocument = new XDocument(); + var otherXDocument = new XDocument(); - // Act - Action act = () => theDocument.Should().Be(new XDocument(), "we want to test the failure {0}", "message"); + // Act + Action act = () => + theDocument.Should().Be(otherXDocument); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to be [XML document without root element] *failure message*, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to be [XML document without root element], but found [XML document without root element]."); + } - [Fact] - public void When_both_subject_and_expected_documents_are_null_it_succeeds() - { - // Arrange - XDocument theDocument = null; + [Fact] + public void When_the_expected_element_is_null_it_fails() + { + // Arrange + XDocument theDocument = null; - // Act - Action act = () => theDocument.Should().Be(null); + // Act + Action act = () => theDocument.Should().Be(new XDocument(), "we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to be [XML document without root element] *failure message*, but found ."); + } - [Fact] - public void When_a_document_is_expected_to_equal_null_it_fails() - { - // Arrange - XDocument theDocument = new XDocument(); + [Fact] + public void When_both_subject_and_expected_documents_are_null_it_succeeds() + { + // Arrange + XDocument theDocument = null; - // Act - Action act = () => theDocument.Should().Be(null, "we want to test the failure {0}", "message"); + // Act + Action act = () => theDocument.Should().Be(null); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to be *failure message*, but found [XML document without root element]."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_document_is_equal_to_a_different_xml_document_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + [Fact] + public void When_a_document_is_expected_to_equal_null_it_fails() + { + // Arrange + XDocument theDocument = new XDocument(); - // Act - Action act = () => - theDocument.Should().Be(otherXDocument, "because we want to test the failure {0}", "message"); + // Act + Action act = () => theDocument.Should().Be(null, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to be because we want to test the failure message, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to be *failure message*, but found [XML document without root element]."); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equal_to_a_different_xml_document_it_should_succeed() - { - // Arrange - var document = new XDocument(); - var otherXDocument = new XDocument(); + [Fact] + public void When_asserting_a_xml_document_is_equal_to_a_different_xml_document_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - // Act - Action act = () => - document.Should().NotBe(otherXDocument); + // Act + Action act = () => + theDocument.Should().Be(otherXDocument, "because we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to be because we want to test the failure message, but found ."); + } } - [Fact] - public void When_asserting_a_xml_document_is_not_equal_to_the_same_xml_document_it_should_fail() + public class NotBe { - // Arrange - var theDocument = new XDocument(); - var sameXDocument = theDocument; - - // Act - Action act = () => - theDocument.Should().NotBe(sameXDocument); + [Fact] + public void When_asserting_a_xml_document_is_not_equal_to_a_different_xml_document_it_should_succeed() + { + // Arrange + var document = new XDocument(); + var otherXDocument = new XDocument(); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be [XML document without root element]."); - } + // Act + Action act = () => + document.Should().NotBe(otherXDocument); - [Fact] - public void When_a_null_document_is_not_supposed_to_be_a_document_it_succeeds() - { - // Arrange - XDocument theDocument = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => theDocument.Should().NotBe(new XDocument()); + [Fact] + public void When_asserting_a_xml_document_is_not_equal_to_the_same_xml_document_it_should_fail() + { + // Arrange + var theDocument = new XDocument(); + var sameXDocument = theDocument; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + theDocument.Should().NotBe(sameXDocument); - [Fact] - public void When_a_document_is_not_supposed_to_be_null_it_succeeds() - { - // Arrange - XDocument theDocument = new XDocument(); + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be [XML document without root element]."); + } - // Act - Action act = () => theDocument.Should().NotBe(null); + [Fact] + public void When_a_null_document_is_not_supposed_to_be_a_document_it_succeeds() + { + // Arrange + XDocument theDocument = null; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => theDocument.Should().NotBe(new XDocument()); - [Fact] - public void When_a_null_document_is_not_supposed_to_be_equal_to_null_it_fails() - { - // Arrange - XDocument theDocument = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => theDocument.Should().NotBe(null, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect theDocument to be *failure message*."); - } + [Fact] + public void When_a_document_is_not_supposed_to_be_null_it_succeeds() + { + // Arrange + XDocument theDocument = new XDocument(); - [Fact] - public void When_asserting_a_xml_document_is_not_equal_to_the_same_xml_document_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var sameXDocument = theDocument; + // Act + Action act = () => theDocument.Should().NotBe(null); - // Act - Action act = () => - theDocument.Should().NotBe(sameXDocument, "we want to test the failure {0}", "message"); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be because we want to test the failure message."); - } + [Fact] + public void When_a_null_document_is_not_supposed_to_be_equal_to_null_it_fails() + { + // Arrange + XDocument theDocument = null; - #endregion + // Act + Action act = () => theDocument.Should().NotBe(null, "we want to test the failure {0}", "message"); - #region BeEquivalentTo / NotBeEquivalentTo + // Assert + act.Should().Throw() + .WithMessage("Did not expect theDocument to be *failure message*."); + } - [Fact] - public void When_asserting_a_xml_document_is_equivalent_to_the_same_xml_document_it_should_succeed() - { - // Arrange - var document = new XDocument(); - var sameXDocument = document; + [Fact] + public void When_asserting_a_xml_document_is_not_equal_to_the_same_xml_document_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var sameXDocument = theDocument; - // Act - Action act = () => - document.Should().BeEquivalentTo(sameXDocument); + // Act + Action act = () => + theDocument.Should().NotBe(sameXDocument, "we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be because we want to test the failure message."); + } } - [Fact] - public void When_asserting_a_xml_selfclosing_document_is_equivalent_to_a_different_xml_document_with_same_structure_it_should_succeed() + public class BeEquivalentTo { - // Arrange - var document = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); - - // Act - Action act = () => - document.Should().BeEquivalentTo(otherXDocument); - - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_asserting_a_xml_document_is_equivalent_to_the_same_xml_document_it_should_succeed() + { + // Arrange + var document = new XDocument(); + var sameXDocument = document; - [Fact] - public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_with_same_structure_it_should_succeed() - { - // Arrange - var document = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + // Act + Action act = () => + document.Should().BeEquivalentTo(sameXDocument); - // Act - Action act = () => - document.Should().BeEquivalentTo(otherXDocument); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_asserting_a_xml_selfclosing_document_is_equivalent_to_a_different_xml_document_with_same_structure_it_should_succeed() + { + // Arrange + var document = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - [Fact] - public void When_asserting_a_xml_document_is_equivalent_to_a_xml_document_with_elements_missing_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + // Act + Action act = () => + document.Should().BeEquivalentTo(otherXDocument); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(otherXDocument); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw().WithMessage( - "Expected EndElement \"parent\" in theDocument at \"/parent\", but found Element \"child2\"."); - } + [Fact] + public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_with_same_structure_it_should_succeed() + { + // Arrange + var document = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - [Fact] - public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_with_extra_elements_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); + // Act + Action act = () => + document.Should().BeEquivalentTo(otherXDocument); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw().WithMessage( - "Expected Element \"child2\" in theDocument at \"/parent\", but found EndElement \"parent\"."); - } + [Fact] + public void When_asserting_a_xml_document_is_equivalent_to_a_xml_document_with_elements_missing_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - [Fact] - public void When_asserting_a_xml_document_with_selfclosing_child_is_equivalent_to_a_different_xml_document_with_subchild_child_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(otherXDocument); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(otherXDocument); + // Assert + act.Should().Throw().WithMessage( + "Expected EndElement \"parent\" in theDocument at \"/parent\", but found Element \"child2\"."); + } - // Assert - act.Should().Throw().WithMessage( - "Expected Element \"child\" in theDocument at \"/parent/child\", but found EndElement \"parent\"."); - } + [Fact] + public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_with_extra_elements_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); - [Fact] - public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_elements_missing_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected EndElement \"parent\" in theDocument at \"/parent\" because we want to test the failure message," - + " but found Element \"child2\"."); - } + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected); - [Fact] - public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_with_extra_elements_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected Element \"child2\" in theDocument at \"/parent\" because we want to test the failure message," - + " but found EndElement \"parent\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected Element \"child2\" in theDocument at \"/parent\", but found EndElement \"parent\"."); + } - [Fact] - public void When_a_document_is_null_then_be_equivalent_to_null_succeeds() - { - XDocument theDocument = null; + [Fact] + public void When_asserting_a_xml_document_with_selfclosing_child_is_equivalent_to_a_different_xml_document_with_subchild_child_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - // Act - Action act = () => theDocument.Should().BeEquivalentTo(null); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(otherXDocument); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected Element \"child\" in theDocument at \"/parent/child\", but found EndElement \"parent\"."); + } - [Fact] - public void When_a_document_is_null_then_be_equivalent_to_a_document_fails() - { - XDocument theDocument = null; - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo( - XDocument.Parse(""), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected theDocument to be equivalent to *failure message*" + - ", but found \"\"."); - } - - [Fact] - public void When_a_document_is_equivalent_to_null_it_fails() - { - XDocument theDocument = XDocument.Parse(""); + [Fact] + public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_elements_missing_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected EndElement \"parent\" in theDocument at \"/parent\" because we want to test the failure message," + + " but found Element \"child2\"."); + } + + [Fact] + public void When_asserting_a_xml_document_is_equivalent_to_a_different_xml_document_with_extra_elements_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected Element \"child2\" in theDocument at \"/parent\" because we want to test the failure message," + + " but found EndElement \"parent\"."); + } + + [Fact] + public void When_a_document_is_null_then_be_equivalent_to_null_succeeds() + { + XDocument theDocument = null; - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(null, "we want to test the failure {0}", "message"); + // Act + Action act = () => theDocument.Should().BeEquivalentTo(null); - // Assert - act.Should().Throw() - .WithMessage( - "Expected theDocument to be equivalent to \"\" *failure message*" + - ", but found ."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_elements_missing_it_should_succeed() - { - // Arrange - var document = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + [Fact] + public void When_a_document_is_null_then_be_equivalent_to_a_document_fails() + { + XDocument theDocument = null; + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo( + XDocument.Parse(""), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected theDocument to be equivalent to *failure message*" + + ", but found \"\"."); + } + + [Fact] + public void When_a_document_is_equivalent_to_null_it_fails() + { + XDocument theDocument = XDocument.Parse(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(null, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected theDocument to be equivalent to \"\" *failure message*" + + ", but found ."); + } + + [Fact] + public void When_assertion_an_xml_document_is_equivalent_to_a_different_xml_document_with_different_namespace_prefix_it_should_succeed() + { + // Arrange + var subject = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - document.Should().NotBeEquivalentTo(otherXDocument); + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_extra_elements_it_should_succeed() - { - // Arrange - var document = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_a_different_xml_document_which_differs_only_on_unused_namespace_declaration_it_should_succeed() + { + // Arrange + var subject = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - document.Should().NotBeEquivalentTo(otherXDocument); + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_structure_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse(""); - var otherXDocument = XDocument.Parse(""); + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_lacks_attributes_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(otherXDocument); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be equivalent, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message, but found none."); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_the_same_xml_document_it_should_fail() - { - // Arrange - var theDocument = new XDocument(); - var sameXDocument = theDocument; + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_extra_attributes_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(sameXDocument); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be equivalent, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect to find attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message."); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_structure_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var otherDocument = XDocument.Parse(""); + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_different_attribute_values_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(otherDocument, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"a\" in theDocument at \"/xml/element\" to have value \"c\" because we want to test the failure message, but found \"b\"."); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_contents_but_different_ns_prefixes_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse(@""); - var otherXDocument = XDocument.Parse(@""); + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_attribute_with_different_namespace_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(otherXDocument, "because we want to test the failure {0}", "message"); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect to find attribute \"ns:a\" in theDocument at \"/xml/element\" because we want to test the failure message."); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_contents_but_extra_unused_xmlns_declaration_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse(@""); - var otherDocument = XDocument.Parse(""); + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_different_text_contents_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse("a"); + var expected = XDocument.Parse("b"); - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(otherDocument); + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be equivalent, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected content to be \"b\" in theDocument at \"/xml\" because we want to test the failure message, but found \"a\"."); + } - [Fact] - public void When_asserting_a_xml_document_is_not_equivalent_to_the_same_xml_document_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var sameXDocument = theDocument; + [Fact] + public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_with_different_comments_it_should_succeed() + { + // Arrange + var subject = XDocument.Parse(""); + var expected = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(sameXDocument, "we want to test the failure {0}", "message"); + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_assertion_an_xml_document_is_equivalent_to_a_different_xml_document_with_different_namespace_prefix_it_should_succeed() - { - // Arrange - var subject = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_equivalence_of_an_xml_document_but_has_different_attribute_value_it_should_fail_with_xpath_to_difference() + { + // Arrange + XDocument actual = XDocument.Parse(""); + XDocument expected = XDocument.Parse(""); - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); + // Act + Action act = () => actual.Should().BeEquivalentTo(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage("*\"/xml/b\"*"); + } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_a_different_xml_document_which_differs_only_on_unused_namespace_declaration_it_should_succeed() - { - // Arrange - var subject = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_equivalence_of_document_with_repeating_element_names_but_differs_it_should_fail_with_index_xpath_to_difference() + { + // Arrange + XDocument actual = XDocument.Parse( + ""); + XDocument expected = XDocument.Parse( + ""); - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); + // Act + Action act = () => actual.Should().BeEquivalentTo(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage("*\"/xml/xml2[3]/a[2]\"*"); + } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_lacks_attributes_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_equivalence_of_document_with_repeating_element_names_on_different_levels_but_differs_it_should_fail_with_index_xpath_to_difference() + { + // Arrange + XDocument actual = XDocument.Parse( + ""); + XDocument expected = XDocument.Parse( + ""); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => actual.Should().BeEquivalentTo(expected); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message, but found none."); - } + // Assert + act.Should().Throw().WithMessage("*\"/xml/xml[3]/xml[2]\"*"); + } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_extra_attributes_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_equivalence_of_document_with_repeating_element_names_with_different_parents_but_differs_it_should_fail_with_index_xpath_to_difference() + { + // Arrange + XDocument actual = XDocument.Parse( + ""); + XDocument expected = XDocument.Parse( + ""); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => actual.Should().BeEquivalentTo(expected); - // Assert - act.Should().Throw().WithMessage( - "Did not expect to find attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message."); + // Assert + act.Should().Throw().WithMessage("*\"/root/xml1[3]/xml2[2]\"*"); + } } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_different_attribute_values_it_should_fail_with_descriptive_message() + public class NotBeEquivalentTo { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_elements_missing_it_should_succeed() + { + // Arrange + var document = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + document.Should().NotBeEquivalentTo(otherXDocument); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"a\" in theDocument at \"/xml/element\" to have value \"c\" because we want to test the failure message, but found \"b\"."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_attribute_with_different_namespace_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_extra_elements_it_should_succeed() + { + // Arrange + var document = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + document.Should().NotBeEquivalentTo(otherXDocument); - // Assert - act.Should().Throw().WithMessage( - "Did not expect to find attribute \"ns:a\" in theDocument at \"/xml/element\" because we want to test the failure message."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_which_has_different_text_contents_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse("a"); - var expected = XDocument.Parse("b"); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_structure_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse(""); + var otherXDocument = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(otherXDocument); - // Assert - act.Should().Throw().WithMessage( - "Expected content to be \"b\" in theDocument at \"/xml\" because we want to test the failure message, but found \"a\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be equivalent, but it is."); + } - [Fact] - public void When_asserting_an_xml_document_is_equivalent_to_different_xml_document_with_different_comments_it_should_succeed() - { - // Arrange - var subject = XDocument.Parse(""); - var expected = XDocument.Parse(""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_the_same_xml_document_it_should_fail() + { + // Arrange + var theDocument = new XDocument(); + var sameXDocument = theDocument; - // Act - Action act = () => subject.Should().BeEquivalentTo(expected); + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(sameXDocument); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be equivalent, but it is."); + } - [Fact] - public void When_asserting_equivalence_of_an_xml_document_but_has_different_attribute_value_it_should_fail_with_xpath_to_difference() - { - // Arrange - XDocument actual = XDocument.Parse(""); - XDocument expected = XDocument.Parse(""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_structure_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var otherDocument = XDocument.Parse(""); - // Act - Action act = () => actual.Should().BeEquivalentTo(expected); + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(otherDocument, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage("*\"/xml/b\"*"); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); + } - [Fact] - public void When_asserting_equivalence_of_document_with_repeating_element_names_but_differs_it_should_fail_with_index_xpath_to_difference() - { - // Arrange - XDocument actual = XDocument.Parse( - ""); - XDocument expected = XDocument.Parse( - ""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_contents_but_different_ns_prefixes_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse(@""); + var otherXDocument = XDocument.Parse(@""); - // Act - Action act = () => actual.Should().BeEquivalentTo(expected); + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(otherXDocument, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage("*\"/xml/xml2[3]/a[2]\"*"); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); + } - [Fact] - public void When_asserting_equivalence_of_document_with_repeating_element_names_on_different_levels_but_differs_it_should_fail_with_index_xpath_to_difference() - { - // Arrange - XDocument actual = XDocument.Parse( - ""); - XDocument expected = XDocument.Parse( - ""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_a_different_xml_document_with_same_contents_but_extra_unused_xmlns_declaration_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse(@""); + var otherDocument = XDocument.Parse(""); - // Act - Action act = () => actual.Should().BeEquivalentTo(expected); + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(otherDocument); - // Assert - act.Should().Throw().WithMessage("*\"/xml/xml[3]/xml[2]\"*"); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be equivalent, but it is."); + } - [Fact] - public void When_asserting_equivalence_of_document_with_repeating_element_names_with_different_parents_but_differs_it_should_fail_with_index_xpath_to_difference() - { - // Arrange - XDocument actual = XDocument.Parse( - ""); - XDocument expected = XDocument.Parse( - ""); + [Fact] + public void When_asserting_a_xml_document_is_not_equivalent_to_the_same_xml_document_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); + var sameXDocument = theDocument; - // Act - Action act = () => actual.Should().BeEquivalentTo(expected); + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(sameXDocument, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage("*\"/root/xml1[3]/xml2[2]\"*"); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); + } - [Fact] - public void When_a_null_document_is_unexpected_equivalent_to_null_it_fails() - { - XDocument theDocument = null; + [Fact] + public void When_a_null_document_is_unexpected_equivalent_to_null_it_fails() + { + XDocument theDocument = null; - // Act - Action act = () => theDocument.Should().NotBeEquivalentTo(null, "we want to test the failure {0}", "message"); + // Act + Action act = () => theDocument.Should().NotBeEquivalentTo(null, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Did not expect theDocument to be equivalent *failure message*, but it is."); - } + // Assert + act.Should().Throw() + .WithMessage("Did not expect theDocument to be equivalent *failure message*, but it is."); + } - [Fact] - public void When_a_null_document_is_not_equivalent_to_a_document_it_succeeds() - { - XDocument theDocument = null; + [Fact] + public void When_a_null_document_is_not_equivalent_to_a_document_it_succeeds() + { + XDocument theDocument = null; - // Act - Action act = () => theDocument.Should().NotBeEquivalentTo(XDocument.Parse("")); + // Act + Action act = () => theDocument.Should().NotBeEquivalentTo(XDocument.Parse("")); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_document_is_not_equivalent_to_null_it_succeeds() - { - XDocument theDocument = XDocument.Parse(""); + [Fact] + public void When_a_document_is_not_equivalent_to_null_it_succeeds() + { + XDocument theDocument = XDocument.Parse(""); - // Act - Action act = () => theDocument.Should().NotBeEquivalentTo(null); + // Act + Action act = () => theDocument.Should().NotBeEquivalentTo(null); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - #endregion - - #region BeNull / NotBeNull - - [Fact] - public void When_asserting_a_null_xml_document_is_null_it_should_succeed() + public class BeNull { - // Arrange - XDocument document = null; + [Fact] + public void When_asserting_a_null_xml_document_is_null_it_should_succeed() + { + // Arrange + XDocument document = null; - // Act - Action act = () => - document.Should().BeNull(); + // Act + Action act = () => + document.Should().BeNull(); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_non_null_xml_document_is_null_it_should_fail() - { - // Arrange - var theDocument = new XDocument(); + [Fact] + public void When_asserting_a_non_null_xml_document_is_null_it_should_fail() + { + // Arrange + var theDocument = new XDocument(); - // Act - Action act = () => - theDocument.Should().BeNull(); + // Act + Action act = () => + theDocument.Should().BeNull(); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to be , but found [XML document without root element]."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to be , but found [XML document without root element]."); + } - [Fact] - public void When_asserting_a_non_null_xml_document_is_null_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse(""); + [Fact] + public void When_asserting_a_non_null_xml_document_is_null_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse(""); - // Act - Action act = () => - theDocument.Should().BeNull("because we want to test the failure {0}", "message"); + // Act + Action act = () => + theDocument.Should().BeNull("because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to be because we want to test the failure message, but found ."); + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to be because we want to test the failure message, but found ."); + } } - [Fact] - public void When_asserting_a_non_null_xml_document_is_not_null_it_should_succeed() + public class NotBeNull { - // Arrange - var document = new XDocument(); + [Fact] + public void When_asserting_a_non_null_xml_document_is_not_null_it_should_succeed() + { + // Arrange + var document = new XDocument(); - // Act - Action act = () => - document.Should().NotBeNull(); + // Act + Action act = () => + document.Should().NotBeNull(); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_null_xml_document_is_not_null_it_should_fail() - { - // Arrange - XDocument theDocument = null; + [Fact] + public void When_asserting_a_null_xml_document_is_not_null_it_should_fail() + { + // Arrange + XDocument theDocument = null; - // Act - Action act = () => - theDocument.Should().NotBeNull(); + // Act + Action act = () => + theDocument.Should().NotBeNull(); - // Assert - act.Should().Throw().WithMessage("Expected theDocument not to be ."); - } + // Assert + act.Should().Throw().WithMessage("Expected theDocument not to be ."); + } - [Fact] - public void When_asserting_a_null_xml_document_is_not_null_it_should_fail_with_descriptive_message() - { - // Arrange - XDocument theDocument = null; + [Fact] + public void When_asserting_a_null_xml_document_is_not_null_it_should_fail_with_descriptive_message() + { + // Arrange + XDocument theDocument = null; - // Act - Action act = () => - theDocument.Should().NotBeNull("because we want to test the failure {0}", "message"); + // Act + Action act = () => + theDocument.Should().NotBeNull("because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument not to be because we want to test the failure message."); + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument not to be because we want to test the failure message."); + } } - #endregion - - #region HaveRoot - - [Fact] - public void When_asserting_document_has_root_element_and_it_does_it_should_succeed_and_return_it_for_chaining() + public class HaveRoot { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_element_and_it_does_it_should_succeed_and_return_it_for_chaining() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - XElement root = document.Should().HaveRoot("parent").Subject; + // Act + XElement root = document.Should().HaveRoot("parent").Subject; - // Assert - root.Should().BeSameAs(document.Root); - } + // Assert + root.Should().BeSameAs(document.Root); + } - [Fact] - public void When_asserting_document_has_root_element_but_it_does_not_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_element_but_it_does_not_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => theDocument.Should().HaveRoot("unknown"); + // Act + Action act = () => theDocument.Should().HaveRoot("unknown"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to have root element \"unknown\", but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to have root element \"unknown\", but found ."); + } - [Fact] - public void When_asserting_document_has_root_element_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_element_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => - theDocument.Should().HaveRoot("unknown", "because we want to test the failure message"); + // Act + Action act = () => + theDocument.Should().HaveRoot("unknown", "because we want to test the failure message"); - // Assert - string expectedMessage = "Expected theDocument to have root element \"unknown\"" + - " because we want to test the failure message" + - $", but found {Formatter.ToString(theDocument)}."; + // Assert + string expectedMessage = "Expected theDocument to have root element \"unknown\"" + + " because we want to test the failure message" + + $", but found {Formatter.ToString(theDocument)}."; - act.Should().Throw().WithMessage(expectedMessage); - } + act.Should().Throw().WithMessage(expectedMessage); + } - [Fact] - public void When_asserting_a_null_document_has_root_element_it_should_fail() - { - // Arrange - XDocument theDocument = null; + [Fact] + public void When_asserting_a_null_document_has_root_element_it_should_fail() + { + // Arrange + XDocument theDocument = null; - // Act - Action act = () => theDocument.Should().HaveRoot("unknown"); + // Act + Action act = () => theDocument.Should().HaveRoot("unknown"); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has a root element if the document itself is ."); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has a root element if the document itself is ."); + } - [Fact] - public void When_asserting_a_document_has_a_root_element_with_a_null_name_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_a_document_has_a_root_element_with_a_null_name_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => theDocument.Should().HaveRoot(null); + // Act + Action act = () => theDocument.Should().HaveRoot(null); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has a root element if the expected name is *"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has a root element if the expected name is *"); + } - [Fact] - public void When_asserting_a_document_has_a_root_element_with_a_null_xname_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_a_document_has_a_root_element_with_a_null_xname_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => theDocument.Should().HaveRoot((XName)null); + // Act + Action act = () => theDocument.Should().HaveRoot((XName)null); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has a root element if the expected name is *"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has a root element if the expected name is *"); + } - [Fact] - public void When_asserting_document_has_root_element_with_ns_and_it_does_it_should_succeed() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_element_with_ns_and_it_does_it_should_succeed() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => - document.Should().HaveRoot(XName.Get("parent", "http://www.example.com/2012/test")); + // Act + Action act = () => + document.Should().HaveRoot(XName.Get("parent", "http://www.example.com/2012/test")); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_document_has_root_element_with_ns_but_it_does_not_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_element_with_ns_but_it_does_not_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => - theDocument.Should().HaveRoot(XName.Get("unknown", "http://www.example.com/2012/test")); + // Act + Action act = () => + theDocument.Should().HaveRoot(XName.Get("unknown", "http://www.example.com/2012/test")); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to have root element \"{http://www.example.com/2012/test}unknown\", but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to have root element \"{http://www.example.com/2012/test}unknown\", but found ."); + } - [Fact] - public void When_asserting_document_has_root_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => - theDocument.Should().HaveRoot(XName.Get("unknown", "http://www.example.com/2012/test"), - "because we want to test the failure message"); + // Act + Action act = () => + theDocument.Should().HaveRoot(XName.Get("unknown", "http://www.example.com/2012/test"), + "because we want to test the failure message"); - // Assert - string expectedMessage = - "Expected theDocument to have root element \"{http://www.example.com/2012/test}unknown\"" + - " because we want to test the failure message" + - $", but found {Formatter.ToString(theDocument)}."; + // Assert + string expectedMessage = + "Expected theDocument to have root element \"{http://www.example.com/2012/test}unknown\"" + + " because we want to test the failure message" + + $", but found {Formatter.ToString(theDocument)}."; - act.Should().Throw().WithMessage(expectedMessage); + act.Should().Throw().WithMessage(expectedMessage); + } } - #endregion - - #region HaveElement - - [Fact] - public void When_document_has_the_expected_child_element_it_should_not_throw_and_return_the_element_for_chaining() + public class HaveElement { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_document_has_the_expected_child_element_it_should_not_throw_and_return_the_element_for_chaining() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - XElement element = document.Should().HaveElement("child").Subject; + // Act + XElement element = document.Should().HaveElement("child").Subject; - // Assert - element.Should().BeSameAs(document.Element("parent").Element("child")); - } + // Assert + element.Should().BeSameAs(document.Element("parent").Element("child")); + } - [Fact] - public void When_asserting_document_has_root_with_child_element_but_it_does_not_it_should_fail() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_with_child_element_but_it_does_not_it_should_fail() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => - theDocument.Should().HaveElement("unknown"); + // Act + Action act = () => + theDocument.Should().HaveElement("unknown"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to have root element with child \"unknown\", but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to have root element with child \"unknown\", but no such child element was found."); + } - [Fact] - public void When_asserting_document_has_root_with_child_element_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_with_child_element_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => - theDocument.Should().HaveElement("unknown", "because we want to test the failure message"); + // Act + Action act = () => + theDocument.Should().HaveElement("unknown", "because we want to test the failure message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to have root element with child \"unknown\" because we want to test the failure message," - + " but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to have root element with child \"unknown\" because we want to test the failure message," + + " but no such child element was found."); + } - [Fact] - public void When_asserting_document_has_root_with_child_element_with_ns_and_it_does_it_should_succeed() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_with_child_element_with_ns_and_it_does_it_should_succeed() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => - document.Should().HaveElement(XName.Get("child", "http://www.example.org/2012/test")); + // Act + Action act = () => + document.Should().HaveElement(XName.Get("child", "http://www.example.org/2012/test")); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_document_has_root_with_child_element_with_ns_but_it_does_not_it_should_fail() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_with_child_element_with_ns_but_it_does_not_it_should_fail() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => - document.Should().HaveElement(XName.Get("unknown", "http://www.example.org/2012/test")); + // Act + Action act = () => + document.Should().HaveElement(XName.Get("unknown", "http://www.example.org/2012/test")); - // Assert - act.Should().Throw().WithMessage( - "Expected document to have root element with child \"{http://www.example.org/2012/test}unknown\"," - + " but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected document to have root element with child \"{http://www.example.org/2012/test}unknown\"," + + " but no such child element was found."); + } - [Fact] - public void When_asserting_document_has_root_with_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_with_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = XDocument.Parse( + @" "); - // Act - Action act = () => - theDocument.Should().HaveElement(XName.Get("unknown", "http://www.example.org/2012/test"), - "because we want to test the failure message"); + // Act + Action act = () => + theDocument.Should().HaveElement(XName.Get("unknown", "http://www.example.org/2012/test"), + "because we want to test the failure message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theDocument to have root element with child \"{http://www.example.org/2012/test}unknown\"" - + " because we want to test the failure message, but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theDocument to have root element with child \"{http://www.example.org/2012/test}unknown\"" + + " because we want to test the failure message, but no such child element was found."); + } - [Fact] - public void When_asserting_document_has_root_with_child_element_with_attributes_it_should_be_possible_to_use_which_to_assert_on_the_element() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_root_with_child_element_with_attributes_it_should_be_possible_to_use_which_to_assert_on_the_element() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - XElement matchedElement = document.Should().HaveElement("child").Subject; + // Act + XElement matchedElement = document.Should().HaveElement("child").Subject; - // Assert - matchedElement.Should().BeOfType().And.HaveAttribute("attr", "1"); - matchedElement.Name.Should().Be(XName.Get("child")); - } + // Assert + matchedElement.Should().BeOfType().And.HaveAttribute("attr", "1"); + matchedElement.Name.Should().Be(XName.Get("child")); + } - [Fact] - public void When_asserting_a_null_document_has_an_element_it_should_fail() - { - // Arrange - XDocument document = null; + [Fact] + public void When_asserting_a_null_document_has_an_element_it_should_fail() + { + // Arrange + XDocument document = null; - // Act - Action act = () => document.Should().HaveElement("unknown"); + // Act + Action act = () => document.Should().HaveElement("unknown"); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has an element if the document itself is ."); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has an element if the document itself is ."); + } - [Fact] - public void When_asserting_a_document_without_root_element_has_an_element_it_should_fail() - { - // Arrange - XDocument document = new(); + [Fact] + public void When_asserting_a_document_without_root_element_has_an_element_it_should_fail() + { + // Arrange + XDocument document = new(); - // Act - Action act = () => document.Should().HaveElement("unknown"); + // Act + Action act = () => document.Should().HaveElement("unknown"); - // Assert - act.Should().Throw().WithMessage( - "Expected document to have root element with child \"unknown\", but it has no root element."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected document to have root element with child \"unknown\", but it has no root element."); + } - [Fact] - public void When_asserting_a_document_has_an_element_with_a_null_name_it_should_fail() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_a_document_has_an_element_with_a_null_name_it_should_fail() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => document.Should().HaveElement(null); + // Act + Action act = () => document.Should().HaveElement(null); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has an element if the expected name is *"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has an element if the expected name is *"); + } - [Fact] - public void When_asserting_a_document_has_an_element_with_a_null_xname_it_should_fail() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_a_document_has_an_element_with_a_null_xname_it_should_fail() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => document.Should().HaveElement((XName)null); + // Act + Action act = () => document.Should().HaveElement((XName)null); - // Assert - act.Should().ThrowExactly().WithMessage( - "Cannot assert the document has an element if the expected name is *"); + // Assert + act.Should().ThrowExactly().WithMessage( + "Cannot assert the document has an element if the expected name is *"); + } } - #endregion - - #region HaveElement (with occurrence) - - [Fact] - public void When_asserting_document_has_two_child_elements_and_it_does_it_succeeds() + public class HaveElementWithOccurrence { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void When_asserting_document_has_two_child_elements_and_it_does_it_succeeds() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act / Assert - document.Should().HaveElement("child", Exactly.Twice()); - } - - [Fact] - public void Asserting_document_null_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() - { - // Arrange - XDocument document = null; + // Act / Assert + document.Should().HaveElement("child", Exactly.Twice()); + } - // Act - Action act = () => + [Fact] + public void Asserting_document_null_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() { - using (new AssertionScope()) - { - document.Should().HaveElement("child", Exactly.Twice()); - document.Should().HaveElement("child", Exactly.Twice()); - } - }; - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void Asserting_with_document_root_null_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() - { - // Arrange - XDocument document = new(); + // Arrange + XDocument document = null; - // Act - Action act = () => - { - using (new AssertionScope()) + // Act + Action act = () => { - document.Should().HaveElement("child", Exactly.Twice()); - document.Should().HaveElement("child", Exactly.Twice()); - } - }; - - // Assert - act.Should().NotThrow(); - } + using (new AssertionScope()) + { + document.Should().HaveElement("child", Exactly.Twice()); + document.Should().HaveElement("child", Exactly.Twice()); + } + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Asserting_with_document_root_null_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() + { + // Arrange + XDocument document = new(); - [Fact] - public void When_asserting_document_has_two_child_elements_but_it_does_have_three_it_fails() - { - // Arrange - var document = XDocument.Parse( - @" + // Act + Action act = () => + { + using (new AssertionScope()) + { + document.Should().HaveElement("child", Exactly.Twice()); + document.Should().HaveElement("child", Exactly.Twice()); + } + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_document_has_two_child_elements_but_it_does_have_three_it_fails() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => document.Should().HaveElement("child", Exactly.Twice()); + // Act + Action act = () => document.Should().HaveElement("child", Exactly.Twice()); - // Assert - act.Should().Throw() - .WithMessage("Expected document to have a root element containing a child \"child\"*exactly*2 times, but found it 3 times*"); - } + // Assert + act.Should().Throw() + .WithMessage("Expected document to have a root element containing a child \"child\"*exactly*2 times, but found it 3 times*"); + } - [Fact] - public void Document_is_valid_and_expected_null_with_string_overload_it_fails() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void Document_is_valid_and_expected_null_with_string_overload_it_fails() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => document.Should().HaveElement(null, Exactly.Twice()); + // Act + Action act = () => document.Should().HaveElement(null, Exactly.Twice()); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has an element if the expected name is .*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has an element if the expected name is .*"); + } - [Fact] - public void Document_is_valid_and_expected_null_with_x_name_overload_it_fails() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void Document_is_valid_and_expected_null_with_x_name_overload_it_fails() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => document.Should().HaveElement((XName)null, Exactly.Twice()); + // Act + Action act = () => document.Should().HaveElement((XName)null, Exactly.Twice()); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the document has an element count if the element name is .*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the document has an element count if the element name is .*"); + } - [Fact] - public void Chaining_after_a_successful_occurrence_check_does_continue_the_assertion() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void Chaining_after_a_successful_occurrence_check_does_continue_the_assertion() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act / Assert - document.Should().HaveElement("child", AtLeast.Twice()) - .Which.Should().NotBeNull(); - } + // Act / Assert + document.Should().HaveElement("child", AtLeast.Twice()) + .Which.Should().NotBeNull(); + } - [Fact] - public void Chaining_after_a_non_successful_occurrence_check_does_not_continue_the_assertion() - { - // Arrange - var document = XDocument.Parse( - @" + [Fact] + public void Chaining_after_a_non_successful_occurrence_check_does_not_continue_the_assertion() + { + // Arrange + var document = XDocument.Parse( + @" "); - // Act - Action act = () => document.Should().HaveElement("child", Exactly.Once()) - .Which.Should().NotBeNull(); + // Act + Action act = () => document.Should().HaveElement("child", Exactly.Once()) + .Which.Should().NotBeNull(); - // Assert - act.Should().Throw() - .WithMessage("Expected document to have a root element containing a child \"child\"*exactly*1 time, but found it 3 times."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected document to have a root element containing a child \"child\"*exactly*1 time, but found it 3 times."); + } - [Fact] - public void When_asserting_a_null_document_to_have_an_element_count_it_should_fail() - { - // Arrange - XDocument xDocument = null; + [Fact] + public void When_asserting_a_null_document_to_have_an_element_count_it_should_fail() + { + // Arrange + XDocument xDocument = null; - // Act - Action act = () => xDocument.Should().HaveElement("child", AtLeast.Once()); + // Act + Action act = () => xDocument.Should().HaveElement("child", AtLeast.Once()); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the count if the document itself is ."); + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the count if the document itself is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs index 176bd01d27..fc59b30b1b 100644 --- a/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XElementAssertionSpecs.cs @@ -8,1371 +8,1373 @@ namespace FluentAssertions.Specs.Xml { public class XElementAssertionSpecs { - #region Be / NotBe - - [Fact] - public void When_asserting_an_xml_element_is_equal_to_the_same_xml_element_it_should_succeed() + public class Be { - // Arrange - var theElement = new XElement("element"); - var sameElement = new XElement("element"); - - // Act - Action act = () => - theElement.Should().Be(sameElement); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_element_is_equal_to_a_different_xml_element_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = new XElement("element"); - var otherElement = new XElement("other"); - - // Act - Action act = () => - theElement.Should().Be(otherElement, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to be*other*because we want to test the failure message, but found *element*"); - } + [Fact] + public void When_asserting_an_xml_element_is_equal_to_the_same_xml_element_it_should_succeed() + { + // Arrange + var theElement = new XElement("element"); + var sameElement = new XElement("element"); - [Fact] - public void When_asserting_an_xml_element_is_equal_to_an_xml_element_with_a_deep_difference_it_should_fail() - { - // Arrange - var theElement = - new XElement("parent", - new XElement("child", - new XElement("grandChild2"))); - var expected = - new XElement("parent", - new XElement("child", - new XElement("grandChild"))); - - // Act - Action act = () => theElement.Should().Be(expected); - - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to be , but found ."); - } + // Act + Action act = () => + theElement.Should().Be(sameElement); - [Fact] - public void When_the_expected_element_is_null_it_fails() - { - // Arrange - XElement theElement = null; + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - theElement.Should().Be(new XElement("other"), "we want to test the failure {0}", "message"); + [Fact] + public void When_asserting_an_xml_element_is_equal_to_a_different_xml_element_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = new XElement("element"); + var otherElement = new XElement("other"); - // Assert - act.Should().Throw() - .WithMessage("Expected theElement to be *failure message*, but found ."); - } + // Act + Action act = () => + theElement.Should().Be(otherElement, "because we want to test the failure {0}", "message"); - [Fact] - public void When_element_is_expected_to_equal_null_it_fails() - { - // Arrange - XElement theElement = new XElement("element"); + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to be*other*because we want to test the failure message, but found *element*"); + } - // Act - Action act = () => theElement.Should().Be(null, "we want to test the failure {0}", "message"); + [Fact] + public void When_asserting_an_xml_element_is_equal_to_an_xml_element_with_a_deep_difference_it_should_fail() + { + // Arrange + var theElement = + new XElement("parent", + new XElement("child", + new XElement("grandChild2"))); + var expected = + new XElement("parent", + new XElement("child", + new XElement("grandChild"))); + + // Act + Action act = () => theElement.Should().Be(expected); + + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to be , but found ."); + } + + [Fact] + public void When_the_expected_element_is_null_it_fails() + { + // Arrange + XElement theElement = null; - // Assert - act.Should().Throw() - .WithMessage("Expected theElement to be *failure message*, but found ."); - } + // Act + Action act = () => + theElement.Should().Be(new XElement("other"), "we want to test the failure {0}", "message"); - [Fact] - public void When_both_subject_and_expected_are_null_it_succeeds() - { - // Arrange - XElement theElement = null; + // Assert + act.Should().Throw() + .WithMessage("Expected theElement to be *failure message*, but found ."); + } - // Act - Action act = () => theElement.Should().Be(null); + [Fact] + public void When_element_is_expected_to_equal_null_it_fails() + { + // Arrange + XElement theElement = new XElement("element"); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => theElement.Should().Be(null, "we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_an_xml_element_is_not_equal_to_a_different_xml_element_it_should_succeed() - { - // Arrange - var element = new XElement("element"); - var otherElement = new XElement("other"); + // Assert + act.Should().Throw() + .WithMessage("Expected theElement to be *failure message*, but found ."); + } - // Act - Action act = () => - element.Should().NotBe(otherElement); + [Fact] + public void When_both_subject_and_expected_are_null_it_succeeds() + { + // Arrange + XElement theElement = null; - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => theElement.Should().Be(null); - [Fact] - public void When_asserting_a_deep_xml_element_is_not_equal_to_a_different_xml_element_it_should_succeed() - { - // Arrange - var differentElement = - new XElement("parent", - new XElement("child", - new XElement("grandChild"))); - var element = - new XElement("parent", - new XElement("child", - new XElement("grandChild2"))); - - // Act - Action act = () => element.Should().NotBe(differentElement); - - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - [Fact] - public void When_asserting_an_xml_element_is_not_equal_to_the_same_xml_element_it_should_fail() + public class NotBe { - // Arrange - var theElement = new XElement("element"); - var sameElement = theElement; - - // Act - Action act = () => - theElement.Should().NotBe(sameElement, "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect theElement to be because we want to test the failure message."); - } + [Fact] + public void When_asserting_an_xml_element_is_not_equal_to_a_different_xml_element_it_should_succeed() + { + // Arrange + var element = new XElement("element"); + var otherElement = new XElement("other"); - [Fact] - public void When_an_element_is_not_supposed_to_be_null_it_succeeds() - { - // Arrange - XElement theElement = new XElement("element"); + // Act + Action act = () => + element.Should().NotBe(otherElement); - // Act - Action act = () => theElement.Should().NotBe(null); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_asserting_a_deep_xml_element_is_not_equal_to_a_different_xml_element_it_should_succeed() + { + // Arrange + var differentElement = + new XElement("parent", + new XElement("child", + new XElement("grandChild"))); + var element = + new XElement("parent", + new XElement("child", + new XElement("grandChild2"))); + + // Act + Action act = () => element.Should().NotBe(differentElement); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_element_is_not_equal_to_the_same_xml_element_it_should_fail() + { + // Arrange + var theElement = new XElement("element"); + var sameElement = theElement; - [Fact] - public void When_a_null_element_is_not_supposed_to_be_an_element_it_succeeds() - { - // Arrange - XElement theElement = null; + // Act + Action act = () => + theElement.Should().NotBe(sameElement, "because we want to test the failure {0}", "message"); - // Act - Action act = () => theElement.Should().NotBe(new XElement("other")); + // Assert + act.Should().Throw() + .WithMessage("Did not expect theElement to be because we want to test the failure message."); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_an_element_is_not_supposed_to_be_null_it_succeeds() + { + // Arrange + XElement theElement = new XElement("element"); - [Fact] - public void When_a_null_element_is_not_supposed_to_be_null_it_fails() - { - // Arrange - XElement theElement = null; + // Act + Action act = () => theElement.Should().NotBe(null); - // Act - Action act = () => theElement.Should().NotBe(null, "we want to test the failure {0}", "message"); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw() - .WithMessage("Did not expect theElement to be *failure message*."); - } + [Fact] + public void When_a_null_element_is_not_supposed_to_be_an_element_it_succeeds() + { + // Arrange + XElement theElement = null; - #endregion + // Act + Action act = () => theElement.Should().NotBe(new XElement("other")); - #region BeNull / NotBeNull + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_xml_element_is_null_and_it_is_it_should_succeed() - { - // Arrange - XElement element = null; + [Fact] + public void When_a_null_element_is_not_supposed_to_be_null_it_fails() + { + // Arrange + XElement theElement = null; - // Act - Action act = () => - element.Should().BeNull(); + // Act + Action act = () => theElement.Should().NotBe(null, "we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw() + .WithMessage("Did not expect theElement to be *failure message*."); + } } - [Fact] - public void When_asserting_an_xml_element_is_null_but_it_is_not_it_should_fail() + public class BeNull { - // Arrange - var theElement = new XElement("element"); + [Fact] + public void When_asserting_an_xml_element_is_null_and_it_is_it_should_succeed() + { + // Arrange + XElement element = null; - // Act - Action act = () => - theElement.Should().BeNull(); + // Act + Action act = () => + element.Should().BeNull(); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to be , but found ."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_xml_element_is_null_but_it_is_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = new XElement("element"); + [Fact] + public void When_asserting_an_xml_element_is_null_but_it_is_not_it_should_fail() + { + // Arrange + var theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().BeNull("because we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().BeNull(); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to be because we want to test the failure message, but found ."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to be , but found ."); + } - [Fact] - public void When_asserting_a_non_null_xml_element_is_not_null_it_should_succeed() - { - // Arrange - var element = new XElement("element"); + [Fact] + public void When_asserting_an_xml_element_is_null_but_it_is_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = new XElement("element"); - // Act - Action act = () => - element.Should().NotBeNull(); + // Act + Action act = () => + theElement.Should().BeNull("because we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to be because we want to test the failure message, but found ."); + } } - [Fact] - public void When_asserting_a_null_xml_element_is_not_null_it_should_fail() + public class NotBeNull { - // Arrange - XElement theElement = null; - - // Act - Action act = () => - theElement.Should().NotBeNull(); - - // Assert - act.Should().Throw().WithMessage("Expected theElement not to be ."); - } + [Fact] + public void When_asserting_a_non_null_xml_element_is_not_null_it_should_succeed() + { + // Arrange + var element = new XElement("element"); - [Fact] - public void When_asserting_a_null_xml_element_is_not_null_it_should_fail_with_descriptive_message() - { - // Arrange - XElement theElement = null; + // Act + Action act = () => + element.Should().NotBeNull(); - // Act - Action act = () => - theElement.Should().NotBeNull("because we want to test the failure {0}", "message"); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw().WithMessage( - "Expected theElement not to be because we want to test the failure message."); - } + [Fact] + public void When_asserting_a_null_xml_element_is_not_null_it_should_fail() + { + // Arrange + XElement theElement = null; - #endregion + // Act + Action act = () => + theElement.Should().NotBeNull(); - #region BeEquivalentTo / NotBeEquivalentTo + // Assert + act.Should().Throw().WithMessage("Expected theElement not to be ."); + } - [Fact] - public void When_asserting_a_xml_element_is_equivalent_to_the_same_xml_element_it_should_succeed() - { - // Arrange - var element = new XElement("element"); - var sameXElement = element; + [Fact] + public void When_asserting_a_null_xml_element_is_not_null_it_should_fail_with_descriptive_message() + { + // Arrange + XElement theElement = null; - // Act - Action act = () => - element.Should().BeEquivalentTo(sameXElement); + // Act + Action act = () => + theElement.Should().NotBeNull("because we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().Throw().WithMessage( + "Expected theElement not to be because we want to test the failure message."); + } } - [Fact] - public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_with_same_structure_it_should_succeed() + public class BeEquivalentTo { - // Arrange - var element = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_equivalent_to_the_same_xml_element_it_should_succeed() + { + // Arrange + var element = new XElement("element"); + var sameXElement = element; - // Act - Action act = () => - element.Should().BeEquivalentTo(otherXElement); + // Act + Action act = () => + element.Should().BeEquivalentTo(sameXElement); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_empty_xml_element_is_equivalent_to_a_different_selfclosing_xml_element_it_should_succeed() - { - // Arrange - var element = XElement.Parse(""); - var otherElement = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_with_same_structure_it_should_succeed() + { + // Arrange + var element = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - element.Should().BeEquivalentTo(otherElement); + // Act + Action act = () => + element.Should().BeEquivalentTo(otherXElement); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_selfclosing_xml_element_is_equivalent_to_a_different_empty_xml_element_it_should_succeed() - { - // Arrange - var element = XElement.Parse(""); - var otherElement = XElement.Parse(""); + [Fact] + public void When_asserting_an_empty_xml_element_is_equivalent_to_a_different_selfclosing_xml_element_it_should_succeed() + { + // Arrange + var element = XElement.Parse(""); + var otherElement = XElement.Parse(""); - // Act - Action act = () => - element.Should().BeEquivalentTo(otherElement); + // Act + Action act = () => + element.Should().BeEquivalentTo(otherElement); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_element_is_equivalent_to_a_xml_element_with_elements_missing_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_a_selfclosing_xml_element_is_equivalent_to_a_different_empty_xml_element_it_should_succeed() + { + // Arrange + var element = XElement.Parse(""); + var otherElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(otherXElement); + // Act + Action act = () => + element.Should().BeEquivalentTo(otherElement); - // Assert - act.Should().Throw().WithMessage( - "Expected EndElement \"parent\" in theElement at \"/parent\", but found Element \"child2\"."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_with_extra_elements_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_equivalent_to_a_xml_element_with_elements_missing_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(otherXElement); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(otherXElement); - // Assert - act.Should().Throw().WithMessage( - "Expected Element \"child2\" in theElement at \"/parent\", but found EndElement \"parent\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected EndElement \"parent\" in theElement at \"/parent\", but found Element \"child2\"."); + } - [Fact] - public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_elements_missing_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_with_extra_elements_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(otherXElement); - // Assert - act.Should().Throw().WithMessage( - "Expected EndElement \"parent\" in theElement at \"/parent\" because we want to test the failure message, but found Element \"child2\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected Element \"child2\" in theElement at \"/parent\", but found EndElement \"parent\"."); + } - [Fact] - public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_with_extra_elements_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_elements_missing_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected Element \"child2\" in theElement at \"/parent\" because we want to test the failure message, but found EndElement \"parent\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected EndElement \"parent\" in theElement at \"/parent\" because we want to test the failure message, but found Element \"child2\"."); + } - [Fact] - public void When_asserting_an_empty_xml_element_is_equivalent_to_a_different_xml_element_with_text_content_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse("text"); + [Fact] + public void When_asserting_a_xml_element_is_equivalent_to_a_different_xml_element_with_extra_elements_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected content \"text\" in theElement at \"/parent/child\" because we want to test the failure message, but found EndElement \"parent\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected Element \"child2\" in theElement at \"/parent\" because we want to test the failure message, but found EndElement \"parent\"."); + } - [Fact] - public void When_an_element_is_null_then_be_equivalent_to_null_succeeds() - { - XElement theElement = null; + [Fact] + public void When_asserting_an_empty_xml_element_is_equivalent_to_a_different_xml_element_with_text_content_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse("text"); - // Act - Action act = () => theElement.Should().BeEquivalentTo(null); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Expected content \"text\" in theElement at \"/parent/child\" because we want to test the failure message, but found EndElement \"parent\"."); + } - [Fact] - public void When_an_element_is_null_then_be_equivalent_to_an_element_fails() - { - XElement theElement = null; + [Fact] + public void When_an_element_is_null_then_be_equivalent_to_null_succeeds() + { + XElement theElement = null; - // Act - Action act = () => - theElement.Should().BeEquivalentTo(new XElement("element"), "we want to test the failure {0}", "message"); + // Act + Action act = () => theElement.Should().BeEquivalentTo(null); - // Assert - act.Should().Throw() - .WithMessage("Expected theElement to be equivalent to *failure message*, but found \"\"."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_an_element_is_equivalent_to_null_it_fails() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_an_element_is_null_then_be_equivalent_to_an_element_fails() + { + XElement theElement = null; - // Act - Action act = () => - theElement.Should().BeEquivalentTo(null, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(new XElement("element"), "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected theElement to be equivalent to \"\" *failure message*, but found ."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected theElement to be equivalent to *failure message*, but found \"\"."); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_elements_missing_it_should_succeed() - { - // Arrange - var element = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_an_element_is_equivalent_to_null_it_fails() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - element.Should().NotBeEquivalentTo(otherXElement); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(null, "we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw() + .WithMessage("Expected theElement to be equivalent to \"\" *failure message*, but found ."); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_extra_elements_it_should_succeed() - { - // Arrange - var element = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void + When_asserting_an_xml_element_is_equivalent_to_a_different_xml_element_with_different_namespace_prefix_it_should_succeed() + { + // Arrange + var subject = XElement.Parse(""); + var expected = XElement.Parse(""); - // Act - Action act = () => - element.Should().NotBeEquivalentTo(otherXElement); + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_structure_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_an_xml_element_is_equivalent_to_a_different_xml_element_which_differs_only_on_unused_namespace_declaration_it_should_succeed() + { + // Arrange + var subject = XElement.Parse(""); + var expected = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().NotBeEquivalentTo(otherXElement); + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theElement to be equivalent, but it is."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_contents_but_different_ns_prefixes_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(@""); - var otherXElement = XElement.Parse(@""); + [Fact] + public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_lacks_attributes_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var expected = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().NotBeEquivalentTo(otherXElement); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theElement to be equivalent, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"a\" in theElement at \"/xml/element\" because we want to test the failure message, but found none."); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_contents_but_extra_unused_xmlns_declaration_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(@""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_extra_attributes_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var expected = XElement.Parse(""); + + // Act + Action act = () => + theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Did not expect to find attribute \"a\" in theElement at \"/xml/element\" because we want to test the failure message."); + } + + [Fact] + public void + When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_different_attribute_values_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var expected = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().NotBeEquivalentTo(otherXElement); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theElement to be equivalent, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"a\" in theElement at \"/xml/element\" to have value \"c\" because we want to test the failure message, but found \"b\"."); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_the_same_xml_element_it_should_fail() - { - // Arrange - var theElement = new XElement("element"); - var sameXElement = theElement; + [Fact] + public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_attribute_with_different_namespace_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var expected = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().NotBeEquivalentTo(sameXElement); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theElement to be equivalent, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect to find attribute \"ns:a\" in theElement at \"/xml/element\" because we want to test the failure message."); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_structure_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var otherXElement = XElement.Parse(""); + [Fact] + public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_different_text_contents_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse("a"); + var expected = XElement.Parse("b"); - // Act - Action act = () => - theElement.Should().NotBeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theElement to be equivalent because we want to test the failure message, but it is."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected content to be \"b\" in theElement at \"/xml\" because we want to test the failure message, but found \"a\"."); + } - [Fact] - public void When_asserting_a_xml_element_is_not_equivalent_to_the_same_xml_element_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var sameXElement = theElement; + [Fact] + public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_with_different_comments_it_should_succeed() + { + // Arrange + var subject = XElement.Parse(""); + var expected = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().NotBeEquivalentTo(sameXElement, "because we want to test the failure {0}", "message"); + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); - // Assert - act.Should().Throw().WithMessage( - "Did not expect theElement to be equivalent because we want to test the failure message, but it is."); + // Assert + act.Should().NotThrow(); + } } - [Fact] - public void - When_asserting_an_xml_element_is_equivalent_to_a_different_xml_element_with_different_namespace_prefix_it_should_succeed() + public class NotBeEquivalentTo { - // Arrange - var subject = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_elements_missing_it_should_succeed() + { + // Arrange + var element = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); + // Act + Action act = () => + element.Should().NotBeEquivalentTo(otherXElement); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_xml_element_is_equivalent_to_a_different_xml_element_which_differs_only_on_unused_namespace_declaration_it_should_succeed() - { - // Arrange - var subject = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_extra_elements_it_should_succeed() + { + // Arrange + var element = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); + // Act + Action act = () => + element.Should().NotBeEquivalentTo(otherXElement); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_lacks_attributes_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_structure_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().NotBeEquivalentTo(otherXElement); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"a\" in theElement at \"/xml/element\" because we want to test the failure message, but found none."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theElement to be equivalent, but it is."); + } - [Fact] - public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_extra_attributes_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_contents_but_different_ns_prefixes_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(@""); + var otherXElement = XElement.Parse(@""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().NotBeEquivalentTo(otherXElement); - // Assert - act.Should().Throw().WithMessage( - "Did not expect to find attribute \"a\" in theElement at \"/xml/element\" because we want to test the failure message."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theElement to be equivalent, but it is."); + } - [Fact] - public void - When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_different_attribute_values_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_contents_but_extra_unused_xmlns_declaration_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(@""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().NotBeEquivalentTo(otherXElement); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"a\" in theElement at \"/xml/element\" to have value \"c\" because we want to test the failure message, but found \"b\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theElement to be equivalent, but it is."); + } - [Fact] - public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_attribute_with_different_namespace_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_the_same_xml_element_it_should_fail() + { + // Arrange + var theElement = new XElement("element"); + var sameXElement = theElement; - // Act - Action act = () => - theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().NotBeEquivalentTo(sameXElement); - // Assert - act.Should().Throw().WithMessage( - "Did not expect to find attribute \"ns:a\" in theElement at \"/xml/element\" because we want to test the failure message."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theElement to be equivalent, but it is."); + } - [Fact] - public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_which_has_different_text_contents_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse("a"); - var expected = XElement.Parse("b"); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_a_different_xml_element_with_same_structure_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var otherXElement = XElement.Parse(""); - // Act - Action act = () => - theElement.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().NotBeEquivalentTo(otherXElement, "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected content to be \"b\" in theElement at \"/xml\" because we want to test the failure message, but found \"a\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theElement to be equivalent because we want to test the failure message, but it is."); + } - [Fact] - public void When_asserting_an_xml_element_is_equivalent_to_different_xml_element_with_different_comments_it_should_succeed() - { - // Arrange - var subject = XElement.Parse(""); - var expected = XElement.Parse(""); + [Fact] + public void When_asserting_a_xml_element_is_not_equivalent_to_the_same_xml_element_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(""); + var sameXElement = theElement; - // Act - Action act = () => subject.Should().BeEquivalentTo(expected); + // Act + Action act = () => + theElement.Should().NotBeEquivalentTo(sameXElement, "because we want to test the failure {0}", "message"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().Throw().WithMessage( + "Did not expect theElement to be equivalent because we want to test the failure message, but it is."); + } - [Fact] - public void When_a_null_element_is_unexpected_equivalent_to_null_it_fails() - { - XElement theElement = null; + [Fact] + public void When_a_null_element_is_unexpected_equivalent_to_null_it_fails() + { + XElement theElement = null; - // Act - Action act = () => theElement.Should().NotBeEquivalentTo(null, "we want to test the failure {0}", "message"); + // Act + Action act = () => theElement.Should().NotBeEquivalentTo(null, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Did not expect theElement to be equivalent *failure message*, but it is."); - } + // Assert + act.Should().Throw() + .WithMessage("Did not expect theElement to be equivalent *failure message*, but it is."); + } - [Fact] - public void When_a_null_element_is_not_equivalent_to_an_element_it_succeeds() - { - XElement theElement = null; + [Fact] + public void When_a_null_element_is_not_equivalent_to_an_element_it_succeeds() + { + XElement theElement = null; - // Act - Action act = () => theElement.Should().NotBeEquivalentTo(new XElement("element")); + // Act + Action act = () => theElement.Should().NotBeEquivalentTo(new XElement("element")); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_an_element_is_not_equivalent_to_null_it_succeeds() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_an_element_is_not_equivalent_to_null_it_succeeds() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => theElement.Should().NotBeEquivalentTo(null); + // Act + Action act = () => theElement.Should().NotBeEquivalentTo(null); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - #endregion - - #region HaveValue - - [Fact] - public void When_asserting_element_has_a_specific_value_and_it_does_it_should_succeed() + public class HaveValue { - // Arrange - var element = XElement.Parse("grega"); + [Fact] + public void When_asserting_element_has_a_specific_value_and_it_does_it_should_succeed() + { + // Arrange + var element = XElement.Parse("grega"); - // Act - Action act = () => - element.Should().HaveValue("grega"); + // Act + Action act = () => + element.Should().HaveValue("grega"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_element_has_a_specific_value_but_it_has_a_different_value_it_should_throw() - { - // Arrange - var theElement = XElement.Parse("grega"); + [Fact] + public void When_asserting_element_has_a_specific_value_but_it_has_a_different_value_it_should_throw() + { + // Arrange + var theElement = XElement.Parse("grega"); - // Act - Action act = () => - theElement.Should().HaveValue("stamac"); + // Act + Action act = () => + theElement.Should().HaveValue("stamac"); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement 'user' to have value \"stamac\", but found \"grega\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement 'user' to have value \"stamac\", but found \"grega\"."); + } - [Fact] - public void When_asserting_element_has_a_specific_value_but_it_has_a_different_value_it_should_throw_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse("grega"); + [Fact] + public void When_asserting_element_has_a_specific_value_but_it_has_a_different_value_it_should_throw_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse("grega"); - // Act - Action act = () => - theElement.Should().HaveValue("stamac", "because we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().HaveValue("stamac", "because we want to test the failure {0}", "message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement 'user' to have value \"stamac\" because we want to test the failure message, but found \"grega\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement 'user' to have value \"stamac\" because we want to test the failure message, but found \"grega\"."); + } - [Fact] - public void When_xml_element_is_null_then_have_value_should_fail() - { - XElement theElement = null; + [Fact] + public void When_xml_element_is_null_then_have_value_should_fail() + { + XElement theElement = null; - // Act - Action act = () => - theElement.Should().HaveValue("value", "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().HaveValue("value", "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected the element to have value \"value\" *failure message*, but theElement is ."); + // Assert + act.Should().Throw() + .WithMessage("Expected the element to have value \"value\" *failure message*, but theElement is ."); + } } - #endregion - - #region HaveAttribute - - [Fact] - public void When_asserting_element_has_attribute_with_specific_value_and_it_does_it_should_succeed() + public class HaveAttribute { - // Arrange - var element = XElement.Parse(@""); - - // Act - Action act = () => - element.Should().HaveAttribute("name", "martin"); - - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_asserting_element_has_attribute_with_specific_value_and_it_does_it_should_succeed() + { + // Arrange + var element = XElement.Parse(@""); - [Fact] - public void When_asserting_element_has_attribute_with_ns_and_specific_value_and_it_does_it_should_succeed() - { - // Arrange - var element = XElement.Parse(@""); + // Act + Action act = () => + element.Should().HaveAttribute("name", "martin"); - // Act - Action act = () => - element.Should().HaveAttribute(XName.Get("name", "http://www.example.com/2012/test"), "martin"); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().NotThrow(); - } + [Fact] + public void When_asserting_element_has_attribute_with_ns_and_specific_value_and_it_does_it_should_succeed() + { + // Arrange + var element = XElement.Parse(@""); - [Fact] - public void When_asserting_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(@""); + // Act + Action act = () => + element.Should().HaveAttribute(XName.Get("name", "http://www.example.com/2012/test"), "martin"); - // Act - Action act = () => - theElement.Should().HaveAttribute("age", "36"); + // Assert + act.Should().NotThrow(); + } - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have attribute \"age\" with value \"36\", but found no such attribute in "); - } + [Fact] + public void When_asserting_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(@""); - [Fact] - public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(@""); + // Act + Action act = () => + theElement.Should().HaveAttribute("age", "36"); - // Act - Action act = () => - theElement.Should().HaveAttribute(XName.Get("age", "http://www.example.com/2012/test"), "36"); + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have attribute \"age\" with value \"36\", but found no such attribute in "); + } - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have attribute \"{http://www.example.com/2012/test}age\" with value \"36\"," - + " but found no such attribute in "); - } + [Fact] + public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(@""); - [Fact] - public void When_asserting_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(@""); + // Act + Action act = () => + theElement.Should().HaveAttribute(XName.Get("age", "http://www.example.com/2012/test"), "36"); - // Act - Action act = () => - theElement.Should().HaveAttribute("age", "36", "because we want to test the failure {0}", "message"); + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have attribute \"{http://www.example.com/2012/test}age\" with value \"36\"," + + " but found no such attribute in "); + } - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have attribute \"age\" with value \"36\" because we want to test the failure message," - + " but found no such attribute in "); - } + [Fact] + public void When_asserting_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(@""); - [Fact] - public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(@""); - - // Act - Action act = () => - theElement.Should().HaveAttribute(XName.Get("age", "http://www.example.com/2012/test"), "36", - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have attribute \"{http://www.example.com/2012/test}age\" with value \"36\"" - + " because we want to test the failure message," - + " but found no such attribute in "); - } + // Act + Action act = () => + theElement.Should().HaveAttribute("age", "36", "because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_element_has_attribute_with_specific_value_but_attribute_has_different_value_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(@""); + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have attribute \"age\" with value \"36\" because we want to test the failure message," + + " but found no such attribute in "); + } - // Act - Action act = () => - theElement.Should().HaveAttribute("name", "dennis"); + [Fact] + public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(@""); + + // Act + Action act = () => + theElement.Should().HaveAttribute(XName.Get("age", "http://www.example.com/2012/test"), "36", + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have attribute \"{http://www.example.com/2012/test}age\" with value \"36\"" + + " because we want to test the failure message," + + " but found no such attribute in "); + } + + [Fact] + public void When_asserting_element_has_attribute_with_specific_value_but_attribute_has_different_value_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(@""); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"name\" in theElement to have value \"dennis\", but found \"martin\"."); - } + // Act + Action act = () => + theElement.Should().HaveAttribute("name", "dennis"); - [Fact] - public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail() - { - // Arrange - var theElement = XElement.Parse(@""); + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"name\" in theElement to have value \"dennis\", but found \"martin\"."); + } - // Act - Action act = () => - theElement.Should().HaveAttribute(XName.Get("name", "http://www.example.com/2012/test"), "dennis"); + [Fact] + public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail() + { + // Arrange + var theElement = XElement.Parse(@""); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"{http://www.example.com/2012/test}name\" in theElement to have value \"dennis\", but found \"martin\"."); - } + // Act + Action act = () => + theElement.Should().HaveAttribute(XName.Get("name", "http://www.example.com/2012/test"), "dennis"); - [Fact] - public void When_asserting_element_has_attribute_with_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(@""); + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"{http://www.example.com/2012/test}name\" in theElement to have value \"dennis\", but found \"martin\"."); + } - // Act - Action act = () => - theElement.Should().HaveAttribute("name", "dennis", "because we want to test the failure {0}", "message"); + [Fact] + public void When_asserting_element_has_attribute_with_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(@""); - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"name\" in theElement to have value \"dennis\"" - + " because we want to test the failure message, but found \"martin\"."); - } + // Act + Action act = () => + theElement.Should().HaveAttribute("name", "dennis", "because we want to test the failure {0}", "message"); - [Fact] - public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse(@""); - - // Act - Action act = () => - theElement.Should().HaveAttribute(XName.Get("name", "http://www.example.com/2012/test"), "dennis", - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected attribute \"{http://www.example.com/2012/test}name\" in theElement to have value \"dennis\"" - + " because we want to test the failure message, but found \"martin\"."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"name\" in theElement to have value \"dennis\"" + + " because we want to test the failure message, but found \"martin\"."); + } - [Fact] - public void When_xml_element_is_null_then_have_attribute_should_fail() - { - XElement theElement = null; + [Fact] + public void When_asserting_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse(@""); + + // Act + Action act = () => + theElement.Should().HaveAttribute(XName.Get("name", "http://www.example.com/2012/test"), "dennis", + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected attribute \"{http://www.example.com/2012/test}name\" in theElement to have value \"dennis\"" + + " because we want to test the failure message, but found \"martin\"."); + } + + [Fact] + public void When_xml_element_is_null_then_have_attribute_should_fail() + { + XElement theElement = null; - // Act - Action act = () => - theElement.Should().HaveAttribute("name", "value", "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().HaveAttribute("name", "value", "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage( - "Expected attribute \"name\" in element to have value \"value\" *failure message*" + - ", but theElement is ."); - } + // Assert + act.Should().Throw() + .WithMessage( + "Expected attribute \"name\" in element to have value \"value\" *failure message*" + + ", but theElement is ."); + } - [Fact] - public void When_xml_element_is_null_then_have_attribute_with_XName_should_fail() - { - XElement theElement = null; + [Fact] + public void When_xml_element_is_null_then_have_attribute_with_XName_should_fail() + { + XElement theElement = null; - // Act - Action act = () => - theElement.Should().HaveAttribute((XName)"name", "value", "we want to test the failure {0}", "message"); + // Act + Action act = () => + theElement.Should().HaveAttribute((XName)"name", "value", "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage( - "Expected attribute \"name\" in element to have value \"value\" *failure message*" + - ", but theElement is ."); - } + // Assert + act.Should().Throw() + .WithMessage( + "Expected attribute \"name\" in element to have value \"value\" *failure message*" + + ", but theElement is ."); + } - [Fact] - public void When_asserting_element_has_an_attribute_with_a_null_name_it_should_throw() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_asserting_element_has_an_attribute_with_a_null_name_it_should_throw() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().HaveAttribute(null, "value"); + // Act + Action act = () => + theElement.Should().HaveAttribute(null, "value"); - // Assert - act.Should().ThrowExactly() - .WithParameterName("expectedName"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("expectedName"); + } - [Fact] - public void When_asserting_element_has_an_attribute_with_a_null_XName_it_should_throw() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_asserting_element_has_an_attribute_with_a_null_XName_it_should_throw() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().HaveAttribute((XName)null, "value"); + // Act + Action act = () => + theElement.Should().HaveAttribute((XName)null, "value"); - // Assert - act.Should().ThrowExactly() - .WithParameterName("expectedName"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("expectedName"); + } - [Fact] - public void When_asserting_element_has_an_attribute_with_an_empty_name_it_should_throw() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_asserting_element_has_an_attribute_with_an_empty_name_it_should_throw() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().HaveAttribute(string.Empty, "value"); + // Act + Action act = () => + theElement.Should().HaveAttribute(string.Empty, "value"); - // Assert - act.Should().ThrowExactly() - .WithParameterName("expectedName"); + // Assert + act.Should().ThrowExactly() + .WithParameterName("expectedName"); + } } - #endregion - - #region HaveElement - - [Fact] - public void When_asserting_element_has_child_element_and_it_does_it_should_succeed() + public class HaveElement { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_and_it_does_it_should_succeed() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - Action act = () => - element.Should().HaveElement("child"); + // Act + Action act = () => + element.Should().HaveElement("child"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_element_has_child_element_with_ns_and_it_does_it_should_succeed() - { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_with_ns_and_it_does_it_should_succeed() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - Action act = () => - element.Should().HaveElement(XName.Get("child", "http://www.example.com/2012/test")); + // Act + Action act = () => + element.Should().HaveElement(XName.Get("child", "http://www.example.com/2012/test")); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_element_has_child_element_but_it_does_not_it_should_fail() - { - // Arrange - var theElement = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_but_it_does_not_it_should_fail() + { + // Arrange + var theElement = XElement.Parse( + @" "); - // Act - Action act = () => - theElement.Should().HaveElement("unknown"); + // Act + Action act = () => + theElement.Should().HaveElement("unknown"); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have child element \"unknown\", but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have child element \"unknown\", but no such child element was found."); + } - [Fact] - public void When_asserting_element_has_child_element_with_ns_but_it_does_not_it_should_fail() - { - // Arrange - var theElement = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_with_ns_but_it_does_not_it_should_fail() + { + // Arrange + var theElement = XElement.Parse( + @" "); - // Act - Action act = () => - theElement.Should().HaveElement(XName.Get("unknown", "http://www.example.com/2012/test")); + // Act + Action act = () => + theElement.Should().HaveElement(XName.Get("unknown", "http://www.example.com/2012/test")); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have child element \"{{http://www.example.com/2012/test}}unknown\", but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have child element \"{{http://www.example.com/2012/test}}unknown\", but no such child element was found."); + } - [Fact] - public void When_asserting_element_has_child_element_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse( + @" "); - // Act - Action act = () => - theElement.Should().HaveElement("unknown", "because we want to test the failure message"); + // Act + Action act = () => + theElement.Should().HaveElement("unknown", "because we want to test the failure message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have child element \"unknown\" because we want to test the failure message," - + " but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have child element \"unknown\" because we want to test the failure message," + + " but no such child element was found."); + } - [Fact] - public void When_asserting_element_has_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theElement = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theElement = XElement.Parse( + @" "); - // Act - Action act = () => - theElement.Should().HaveElement(XName.Get("unknown", "http://www.example.com/2012/test"), - "because we want to test the failure message"); + // Act + Action act = () => + theElement.Should().HaveElement(XName.Get("unknown", "http://www.example.com/2012/test"), + "because we want to test the failure message"); - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have child element \"{{http://www.example.com/2012/test}}unknown\"" - + " because we want to test the failure message, but no such child element was found."); - } + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have child element \"{{http://www.example.com/2012/test}}unknown\"" + + " because we want to test the failure message, but no such child element was found."); + } - [Fact] - public void When_asserting_element_has_child_element_it_should_return_the_matched_element_in_the_which_property() - { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void When_asserting_element_has_child_element_it_should_return_the_matched_element_in_the_which_property() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - var matchedElement = element.Should().HaveElement("child").Subject; + // Act + var matchedElement = element.Should().HaveElement("child").Subject; - // Assert - matchedElement.Should().BeOfType() - .And.HaveAttribute("attr", "1"); - matchedElement.Name.Should().Be(XName.Get("child")); - } + // Assert + matchedElement.Should().BeOfType() + .And.HaveAttribute("attr", "1"); + matchedElement.Name.Should().Be(XName.Get("child")); + } - [Fact] - public void When_asserting_element_has_a_child_element_with_a_null_name_it_should_throw() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_asserting_element_has_a_child_element_with_a_null_name_it_should_throw() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().HaveElement(null); + // Act + Action act = () => + theElement.Should().HaveElement(null); - // Assert - act.Should().ThrowExactly() - .WithParameterName("expected"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("expected"); + } - [Fact] - public void When_asserting_element_has_a_child_element_with_a_null_XName_it_should_throw() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_asserting_element_has_a_child_element_with_a_null_XName_it_should_throw() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().HaveElement((XName)null); + // Act + Action act = () => + theElement.Should().HaveElement((XName)null); - // Assert - act.Should().ThrowExactly() - .WithParameterName("expected"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("expected"); + } - [Fact] - public void When_asserting_element_has_a_child_element_with_an_empty_name_it_should_throw() - { - XElement theElement = new XElement("element"); + [Fact] + public void When_asserting_element_has_a_child_element_with_an_empty_name_it_should_throw() + { + XElement theElement = new XElement("element"); - // Act - Action act = () => - theElement.Should().HaveElement(string.Empty); + // Act + Action act = () => + theElement.Should().HaveElement(string.Empty); - // Assert - act.Should().ThrowExactly() - .WithParameterName("expected"); + // Assert + act.Should().ThrowExactly() + .WithParameterName("expected"); + } } - #endregion - - #region HaveElement (with occurrence) - - [Fact] - public void Element_has_two_child_elements_and_it_expected_does_it_succeeds() + public class HaveElementWithOccurrence { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void Element_has_two_child_elements_and_it_expected_does_it_succeeds() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act / Assert - element.Should().HaveElement("child", Exactly.Twice()); - } - - [Fact] - public void Asserting_element_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() - { - // Arrange - XElement element = null; + // Act / Assert + element.Should().HaveElement("child", Exactly.Twice()); + } - // Act - Action act = () => + [Fact] + public void Asserting_element_inside_an_assertion_scope_it_checks_the_whole_assertion_scope_before_failing() { - using (new AssertionScope()) - { - element.Should().HaveElement("child", Exactly.Twice()); - element.Should().HaveElement("child", Exactly.Twice()); - } - }; - - // Assert - act.Should().NotThrow(); - } + // Arrange + XElement element = null; - [Fact] - public void Element_has_two_child_elements_and_three_expected_it_fails() - { - // Arrange - var element = XElement.Parse( - @" + // Act + Action act = () => + { + using (new AssertionScope()) + { + element.Should().HaveElement("child", Exactly.Twice()); + element.Should().HaveElement("child", Exactly.Twice()); + } + }; + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void Element_has_two_child_elements_and_three_expected_it_fails() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - Action act = () => element.Should().HaveElement("child", Exactly.Twice()); + // Act + Action act = () => element.Should().HaveElement("child", Exactly.Twice()); - // Assert - act.Should().Throw() - .WithMessage("Expected element to have an element \"child\"*exactly*2 times, but found it 3 times."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected element to have an element \"child\"*exactly*2 times, but found it 3 times."); + } - [Fact] - public void Element_is_valid_and_expected_null_with_string_overload_it_fails() - { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void Element_is_valid_and_expected_null_with_string_overload_it_fails() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - Action act = () => element.Should().HaveElement(null, Exactly.Twice()); + // Act + Action act = () => element.Should().HaveElement(null, Exactly.Twice()); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the element has an element if the expected name is .*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the element has an element if the expected name is .*"); + } - [Fact] - public void Element_is_valid_and_expected_null_with_x_name_overload_it_fails() - { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void Element_is_valid_and_expected_null_with_x_name_overload_it_fails() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - Action act = () => element.Should().HaveElement((XName)null, Exactly.Twice()); + // Act + Action act = () => element.Should().HaveElement((XName)null, Exactly.Twice()); - // Assert - act.Should().Throw().WithMessage( - "Cannot assert the element has an element count if the element name is .*"); - } + // Assert + act.Should().Throw().WithMessage( + "Cannot assert the element has an element count if the element name is .*"); + } - [Fact] - public void Chaining_after_a_successful_occurrence_check_does_continue_the_assertion() - { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void Chaining_after_a_successful_occurrence_check_does_continue_the_assertion() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act / Assert - element.Should().HaveElement("child", AtLeast.Twice()) - .Which.Should().NotBeNull(); - } + // Act / Assert + element.Should().HaveElement("child", AtLeast.Twice()) + .Which.Should().NotBeNull(); + } - [Fact] - public void Chaining_after_a_non_successful_occurrence_check_does_not_continue_the_assertion() - { - // Arrange - var element = XElement.Parse( - @" + [Fact] + public void Chaining_after_a_non_successful_occurrence_check_does_not_continue_the_assertion() + { + // Arrange + var element = XElement.Parse( + @" "); - // Act - Action act = () => element.Should().HaveElement("child", Exactly.Once()) - .Which.Should().NotBeNull(); + // Act + Action act = () => element.Should().HaveElement("child", Exactly.Once()) + .Which.Should().NotBeNull(); - // Assert - act.Should().Throw() - .WithMessage("Expected element to have an element \"child\"*exactly*1 time, but found it 3 times."); - } + // Assert + act.Should().Throw() + .WithMessage("Expected element to have an element \"child\"*exactly*1 time, but found it 3 times."); + } - [Fact] - public void Null_element_is_expected_to_have_an_element_count_it_should_fail() - { - // Arrange - XElement xElement = null; + [Fact] + public void Null_element_is_expected_to_have_an_element_count_it_should_fail() + { + // Arrange + XElement xElement = null; - // Act - Action act = () => xElement.Should().HaveElement("child", AtLeast.Once()); + // Act + Action act = () => xElement.Should().HaveElement("child", AtLeast.Once()); - // Assert - act.Should().Throw().WithMessage( - "Expected* to have an element with count of *, but the element itself is ."); + // Assert + act.Should().Throw().WithMessage( + "Expected* to have an element with count of *, but the element itself is ."); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Xml/XmlElementAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XmlElementAssertionSpecs.cs index fa37811a04..5f4ff8a6d2 100644 --- a/Tests/FluentAssertions.Specs/Xml/XmlElementAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XmlElementAssertionSpecs.cs @@ -7,455 +7,457 @@ namespace FluentAssertions.Specs.Xml { public class XmlElementAssertionSpecs { - #region BeEquivalent - - [Fact] - public void When_asserting_xml_element_is_equivalent_to_another_xml_element_with_same_contents_it_should_succeed() + public class BeEquivalent { - // This test is basically just a check that the BeEquivalent method - // is available on XmlElementAssertions, which it should be if - // XmlElementAssertions inherits XmlNodeAssertions. - - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml("grega"); - var element = xmlDoc.DocumentElement; - var expectedDoc = new XmlDocument(); - expectedDoc.LoadXml("grega"); - var expected = expectedDoc.DocumentElement; - - // Act - Action act = () => - element.Should().BeEquivalentTo(expected); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region HaveValue - - [Fact] - public void When_asserting_xml_element_has_a_specific_inner_text_and_it_does_it_should_succeed() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml("grega"); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveInnerText("grega"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_xml_element_is_equivalent_to_another_xml_element_with_same_contents_it_should_succeed() + { + // This test is basically just a check that the BeEquivalent method + // is available on XmlElementAssertions, which it should be if + // XmlElementAssertions inherits XmlNodeAssertions. + + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml("grega"); + var element = xmlDoc.DocumentElement; + var expectedDoc = new XmlDocument(); + expectedDoc.LoadXml("grega"); + var expected = expectedDoc.DocumentElement; + + // Act + Action act = () => + element.Should().BeEquivalentTo(expected); + + // Assert + act.Should().NotThrow(); + } } - [Fact] - public void When_asserting_xml_element_has_a_specific_inner_text_but_it_has_a_different_inner_text_it_should_throw() + public class HaveInnerText { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml("grega"); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveInnerText("stamac"); - - // Assert - act.Should().Throw(); + [Fact] + public void When_asserting_xml_element_has_a_specific_inner_text_and_it_does_it_should_succeed() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml("grega"); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveInnerText("grega"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_xml_element_has_a_specific_inner_text_but_it_has_a_different_inner_text_it_should_throw() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml("grega"); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveInnerText("stamac"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_xml_element_has_a_specific_inner_text_but_it_has_a_different_inner_text_it_should_throw_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml("grega"); + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveInnerText("stamac", "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have value \"stamac\" because we want to test the failure message, but found \"grega\"."); + } } - [Fact] - public void - When_asserting_xml_element_has_a_specific_inner_text_but_it_has_a_different_inner_text_it_should_throw_with_descriptive_message() + public class HaveAttribute { - // Arrange - var document = new XmlDocument(); - document.LoadXml("grega"); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveInnerText("stamac", "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have value \"stamac\" because we want to test the failure message, but found \"grega\"."); + [Fact] + public void When_asserting_xml_element_has_attribute_with_specific_value_and_it_does_it_should_succeed() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(@""); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveAttribute("name", "martin"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_xml_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(@""); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveAttribute("age", "36"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_xml_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml(@""); + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveAttribute("age", "36", "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected theElement to have attribute \"age\" with value \"36\"" + + " because we want to test the failure message" + + ", but found no such attribute in "); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveAttribute("name", "dennis"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_xml_element_has_attribute_with_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml(@""); + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveAttribute("name", "dennis", "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected attribute \"name\" in theElement to have value \"dennis\"" + + " because we want to test the failure message" + + ", but found \"martin\"."); + } } - #endregion - - #region HaveAttribute - - [Fact] - public void When_asserting_xml_element_has_attribute_with_specific_value_and_it_does_it_should_succeed() + public class HaveAttributeWithNamespace { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(@""); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveAttribute("name", "martin"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_xml_element_has_attribute_with_ns_and_specific_value_and_it_does_it_should_succeed() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(@""); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveAttributeWithNamespace("name", "http://www.example.com/2012/test", "martin"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void + When_asserting_xml_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(@""); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveAttributeWithNamespace("age", "http://www.example.com/2012/test", "36"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_xml_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml(@""); + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveAttributeWithNamespace("age", "http://www.example.com/2012/test", "36", + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected theElement to have attribute \"{http://www.example.com/2012/test}age\" with value \"36\"" + + " because we want to test the failure message" + + ", but found no such attribute in "); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveAttributeWithNamespace("name", "http://www.example.com/2012/test", "dennis"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_xml_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml(@""); + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveAttributeWithNamespace("name", "http://www.example.com/2012/test", "dennis", + "because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected attribute \"{http://www.example.com/2012/test}name\" in theElement to have value \"dennis\"" + + " because we want to test the failure message" + + ", but found \"martin\"."); + } } - [Fact] - public void When_asserting_xml_element_has_attribute_with_ns_and_specific_value_and_it_does_it_should_succeed() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(@""); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveAttributeWithNamespace("name", "http://www.example.com/2012/test", "martin"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_xml_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(@""); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveAttribute("age", "36"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_xml_element_has_attribute_with_ns_and_specific_value_but_attribute_does_not_exist_it_should_fail() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(@""); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveAttributeWithNamespace("age", "http://www.example.com/2012/test", "36"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_xml_element_has_attribute_with_specific_value_but_attribute_does_not_exist_it_should_fail_with_descriptive_message() - { - // Arrange - var document = new XmlDocument(); - document.LoadXml(@""); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveAttribute("age", "36", "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected theElement to have attribute \"age\" with value \"36\"" + - " because we want to test the failure message" + - ", but found no such attribute in "); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveAttributeWithNamespace("age", "http://www.example.com/2012/test", "36", - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected theElement to have attribute \"{http://www.example.com/2012/test}age\" with value \"36\"" + - " because we want to test the failure message" + - ", but found no such attribute in "); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveAttribute("name", "dennis"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_xml_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(@""); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveAttributeWithNamespace("name", "http://www.example.com/2012/test", "dennis"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_xml_element_has_attribute_with_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() - { - // Arrange - var document = new XmlDocument(); - document.LoadXml(@""); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveAttribute("name", "dennis", "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected attribute \"name\" in theElement to have value \"dennis\"" + - " because we want to test the failure message" + - ", but found \"martin\"."); - } - - [Fact] - public void - When_asserting_xml_element_has_attribute_with_ns_and_specific_value_but_attribute_has_different_value_it_should_fail_with_descriptive_message() - { - // Arrange - var document = new XmlDocument(); - document.LoadXml(@""); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveAttributeWithNamespace("name", "http://www.example.com/2012/test", "dennis", - "because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected attribute \"{http://www.example.com/2012/test}name\" in theElement to have value \"dennis\"" + - " because we want to test the failure message" + - ", but found \"martin\"."); - } - - #endregion - - #region HaveElement - - [Fact] - public void When_asserting_xml_element_has_child_element_and_it_does_it_should_succeed() + public class HaveElement { - // Arrange - var xml = new XmlDocument(); - xml.LoadXml( - @" + [Fact] + public void When_asserting_xml_element_has_child_element_and_it_does_it_should_succeed() + { + // Arrange + var xml = new XmlDocument(); + xml.LoadXml( + @" "); - var element = xml.DocumentElement; - - // Act - Action act = () => - element.Should().HaveElement("child"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_with_ns_and_it_does_it_should_succeed() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml( - @" - - "); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveElementWithNamespace("child", "http://www.example.com/2012/test"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_but_it_does_not_it_should_fail() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml( - @" - - "); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveElement("unknown"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_with_ns_but_it_does_not_it_should_fail() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml( - @" - - "); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveElementWithNamespace("unknown", "http://www.example.com/2012/test"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var document = new XmlDocument(); - document.LoadXml( - @" + var element = xml.DocumentElement; + + // Act + Action act = () => + element.Should().HaveElement("child"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_xml_element_has_child_element_but_it_does_not_it_should_fail() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml( + @" "); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveElement("unknown", "because we want to test the failure message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have child element \"unknown\"" - + " because we want to test the failure message" - + ", but no such child element was found."); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() - { - // Arrange - var document = new XmlDocument(); - document.LoadXml( - @" + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveElement("unknown"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_xml_element_has_child_element_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml( + @" "); - var theElement = document.DocumentElement; - - // Act - Action act = () => - theElement.Should().HaveElementWithNamespace("unknown", "http://www.example.com/2012/test", - "because we want to test the failure message"); - - // Assert - act.Should().Throw().WithMessage( - "Expected theElement to have child element \"{{http://www.example.com/2012/test}}unknown\"" - + " because we want to test the failure message" - + ", but no such child element was found."); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_it_should_return_the_matched_element_in_the_which_property() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml( - @" + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveElement("unknown", "because we want to test the failure message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have child element \"unknown\"" + + " because we want to test the failure message" + + ", but no such child element was found."); + } + + [Fact] + public void When_asserting_xml_element_has_child_element_it_should_return_the_matched_element_in_the_which_property() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml( + @" "); - var element = xmlDoc.DocumentElement; - - // Act - var matchedElement = element.Should().HaveElement("child").Subject; - - // Assert - matchedElement.Should().BeOfType() - .And.HaveAttribute("attr", "1"); - matchedElement.Name.Should().Be("child"); - } - - [Fact] - public void When_asserting_xml_element_with_ns_has_child_element_and_it_does_it_should_succeed() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml( - @" + var element = xmlDoc.DocumentElement; + + // Act + var matchedElement = element.Should().HaveElement("child").Subject; + + // Assert + matchedElement.Should().BeOfType() + .And.HaveAttribute("attr", "1"); + matchedElement.Name.Should().Be("child"); + } + + [Fact] + public void When_asserting_xml_element_with_ns_has_child_element_and_it_does_it_should_succeed() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml( + @" value "); - var element = xmlDoc.DocumentElement; - - // Act - Action act = () => - element.Should().HaveElement("child"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_xml_element_has_child_element_and_it_does_with_ns_it_should_succeed2() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml( - @" + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveElement("child"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_xml_element_has_child_element_and_it_does_with_ns_it_should_succeed2() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml( + @" value "); - var element = xmlDoc.DocumentElement; + var element = xmlDoc.DocumentElement; - // Act - Action act = () => - element.Should().HaveElement("child"); + // Act + Action act = () => + element.Should().HaveElement("child"); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - #endregion + public class HaveElementWithNamespace + { + [Fact] + public void When_asserting_xml_element_has_child_element_with_ns_and_it_does_it_should_succeed() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml( + @" + + "); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveElementWithNamespace("child", "http://www.example.com/2012/test"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_xml_element_has_child_element_with_ns_but_it_does_not_it_should_fail() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml( + @" + + "); + var element = xmlDoc.DocumentElement; + + // Act + Action act = () => + element.Should().HaveElementWithNamespace("unknown", "http://www.example.com/2012/test"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_xml_element_has_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() + { + // Arrange + var document = new XmlDocument(); + document.LoadXml( + @" + + "); + var theElement = document.DocumentElement; + + // Act + Action act = () => + theElement.Should().HaveElementWithNamespace("unknown", "http://www.example.com/2012/test", + "because we want to test the failure message"); + + // Assert + act.Should().Throw().WithMessage( + "Expected theElement to have child element \"{{http://www.example.com/2012/test}}unknown\"" + + " because we want to test the failure message" + + ", but no such child element was found."); + } + } } } diff --git a/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs index ddd58b3b6b..042ff0498b 100644 --- a/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs @@ -7,549 +7,552 @@ namespace FluentAssertions.Specs.Xml { public class XmlNodeAssertionSpecs { - #region BeSameAs / NotBeSameAs - - [Fact] - public void When_asserting_an_xml_node_is_the_same_as_the_same_xml_node_it_should_succeed() - { - // Arrange - var doc = new XmlDocument(); - - // Act - Action act = () => - doc.Should().BeSameAs(doc); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_node_is_same_as_a_different_xml_node_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var otherNode = new XmlDocument(); - otherNode.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeSameAs(otherNode, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected theDocument to refer to because we want to test the failure message, but found ."); - } - - [Fact] - public void When_asserting_an_xml_node_is_same_as_a_different_xml_node_it_should_fail_with_descriptive_message_and_truncate_xml() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml("Some very long text that should be truncated."); - var otherNode = new XmlDocument(); - otherNode.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeSameAs(otherNode, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected theDocument to refer to because we want to test the failure message, but found Some very long…."); - } - - [Fact] - public void When_asserting_the_equality_of_an_xml_node_but_is_null_it_should_throw_appropriately() - { - // Arrange - XmlDocument theDocument = null; - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => theDocument.Should().BeSameAs(expected); - - // Assert - act.Should().Throw() - .WithMessage("Expected theDocument to refer to *xml*, but found ."); - } - - #endregion - - #region BeNull / NotBeNull - - [Fact] - public void When_asserting_an_xml_node_is_null_and_it_is_it_should_succeed() - { - // Arrange - XmlNode node = null; - - // Act - Action act = () => - node.Should().BeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_node_is_null_but_it_is_not_it_should_fail() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(""); - - // Act - Action act = () => - xmlDoc.Should().BeNull(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_an_xml_node_is_null_but_it_is_not_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeNull("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected theDocument to be because we want to test the failure message," + - " but found ."); - } - - [Fact] - public void When_asserting_a_non_null_xml_node_is_not_null_it_should_succeed() - { - // Arrange - var xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(""); - - // Act - Action act = () => - xmlDoc.Should().NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_null_xml_node_is_not_null_it_should_fail() - { - // Arrange - XmlDocument xmlDoc = null; - - // Act - Action act = () => - xmlDoc.Should().NotBeNull(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_a_null_xml_node_is_not_null_it_should_fail_with_descriptive_message() - { - // Arrange - XmlDocument theDocument = null; - - // Act - Action act = () => - theDocument.Should().NotBeNull("because we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected theDocument not to be because we want to test the failure message."); - } - - #endregion - - #region BeEquivalentTo / NotBeEquivalentTo - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_the_same_xml_node_it_should_succeed() - { - // Arrange - var doc = new XmlDocument(); - - // Act - Action act = () => - doc.Should().BeEquivalentTo(doc); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_node_is_not_equivalent_to_som_other_xml_node_it_should_succeed() - { - // Arrange - var subject = new XmlDocument(); - subject.LoadXml("a"); - var unexpected = new XmlDocument(); - unexpected.LoadXml("b"); - - // Act - Action act = () => - subject.Should().NotBeEquivalentTo(unexpected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_node_is_not_equivalent_to_same_xml_node_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml("a"); - - // Act - Action act = () => - theDocument.Should().NotBeEquivalentTo(theDocument, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_with_other_contents_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected local name of element in theDocument at \"/\" to be \"expected\" because we want to test the failure message, but found \"subject\"."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_with_same_contents_it_should_succeed() - { - // Arrange - var xml = "datadata"; - - var subject = new XmlDocument(); - subject.LoadXml(xml); - var expected = new XmlDocument(); - expected.LoadXml(xml); - - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_assertion_an_xml_node_is_equivalent_to_a_different_xml_node_with_different_namespace_prefix_it_should_succeed() + public class BeSameAs { - // Arrange - var subject = new XmlDocument(); - subject.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_an_xml_node_is_the_same_as_the_same_xml_node_it_should_succeed() + { + // Arrange + var doc = new XmlDocument(); + + // Act + Action act = () => + doc.Should().BeSameAs(doc); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_same_as_a_different_xml_node_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var otherNode = new XmlDocument(); + otherNode.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeSameAs(otherNode, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected theDocument to refer to because we want to test the failure message, but found ."); + } + + [Fact] + public void When_asserting_an_xml_node_is_same_as_a_different_xml_node_it_should_fail_with_descriptive_message_and_truncate_xml() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml("Some very long text that should be truncated."); + var otherNode = new XmlDocument(); + otherNode.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeSameAs(otherNode, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected theDocument to refer to because we want to test the failure message, but found Some very long…."); + } + + [Fact] + public void When_asserting_the_equality_of_an_xml_node_but_is_null_it_should_throw_appropriately() + { + // Arrange + XmlDocument theDocument = null; + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => theDocument.Should().BeSameAs(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected theDocument to refer to *xml*, but found ."); + } } - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_which_differs_only_on_unused_namespace_declaration_it_should_succeed() + public class BeNull { - // Arrange - var subject = new XmlDocument(); - subject.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - subject.Should().BeEquivalentTo(expected); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_an_xml_node_is_null_and_it_is_it_should_succeed() + { + // Arrange + XmlNode node = null; + + // Act + Action act = () => + node.Should().BeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_null_but_it_is_not_it_should_fail() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(""); + + // Act + Action act = () => + xmlDoc.Should().BeNull(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_an_xml_node_is_null_but_it_is_not_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeNull("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected theDocument to be because we want to test the failure message," + + " but found ."); + } } - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_a_different_XmlDocument_which_differs_on_a_child_element_name_it_should_fail_with_descriptive_message() + public class NotBeNull { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected local name of element in theDocument at \"/xml/child\" to be \"expected\" because we want to test the failure message, but found \"subject\"."); + [Fact] + public void When_asserting_a_non_null_xml_node_is_not_null_it_should_succeed() + { + // Arrange + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(""); + + // Act + Action act = () => + xmlDoc.Should().NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_null_xml_node_is_not_null_it_should_fail() + { + // Arrange + XmlDocument xmlDoc = null; + + // Act + Action act = () => + xmlDoc.Should().NotBeNull(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_a_null_xml_node_is_not_null_it_should_fail_with_descriptive_message() + { + // Arrange + XmlDocument theDocument = null; + + // Act + Action act = () => + theDocument.Should().NotBeNull("because we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected theDocument not to be because we want to test the failure message."); + } } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_which_differs_on_a_child_element_namespace_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected namespace of element \"data\" in theDocument at \"/xml/child\" to be \"urn:b\" because we want to test the failure message, but found \"urn:a\"."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_contains_an_unexpected_node_type_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml("data"); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected Element \"data\" in theDocument at \"/xml\" because we want to test the failure message, but found content \"data\"."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_contains_extra_elements_it_should_fail_with_descriptive_message() + + public class BeEquivalentTo { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected end of document in theDocument because we want to test the failure message, but found \"data\"."); + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_the_same_xml_node_it_should_succeed() + { + // Arrange + var doc = new XmlDocument(); + + // Act + Action act = () => + doc.Should().BeEquivalentTo(doc); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_with_other_contents_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected local name of element in theDocument at \"/\" to be \"expected\" because we want to test the failure message, but found \"subject\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_with_same_contents_it_should_succeed() + { + // Arrange + var xml = "datadata"; + + var subject = new XmlDocument(); + subject.LoadXml(xml); + var expected = new XmlDocument(); + expected.LoadXml(xml); + + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_assertion_an_xml_node_is_equivalent_to_a_different_xml_node_with_different_namespace_prefix_it_should_succeed() + { + // Arrange + var subject = new XmlDocument(); + subject.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_which_differs_only_on_unused_namespace_declaration_it_should_succeed() + { + // Arrange + var subject = new XmlDocument(); + subject.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_a_different_XmlDocument_which_differs_on_a_child_element_name_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected local name of element in theDocument at \"/xml/child\" to be \"expected\" because we want to test the failure message, but found \"subject\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_a_different_xml_node_which_differs_on_a_child_element_namespace_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected namespace of element \"data\" in theDocument at \"/xml/child\" to be \"urn:b\" because we want to test the failure message, but found \"urn:a\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_contains_an_unexpected_node_type_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml("data"); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected Element \"data\" in theDocument at \"/xml\" because we want to test the failure message, but found content \"data\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_contains_extra_elements_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected end of document in theDocument because we want to test the failure message, but found \"data\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_lacks_elements_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected \"data\" in theDocument because we want to test the failure message, but found end of document."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_lacks_attributes_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message, but found none."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_extra_attributes_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Did not expect to find attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_different_attribute_values_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected attribute \"a\" in theDocument at \"/xml/element\" to have value \"c\" because we want to test the failure message, but found \"b\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_attribute_with_different_namespace_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Did not expect to find attribute \"ns:a\" in theDocument at \"/xml/element\" because we want to test the failure message."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_different_text_contents_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml("a"); + var expected = new XmlDocument(); + expected.LoadXml("b"); + + // Act + Action act = () => + theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected content to be \"b\" in theDocument at \"/xml\" because we want to test the failure message, but found \"a\"."); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_with_different_comments_it_should_succeed() + { + // Arrange + var subject = new XmlDocument(); + subject.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_with_different_insignificant_whitespace_it_should_succeed() + { + // Arrange + var subject = new XmlDocument() { PreserveWhitespace = true }; + subject.LoadXml(""); + var expected = new XmlDocument() { PreserveWhitespace = true }; + expected.LoadXml("\n \n \r\n"); + + // Act + Action act = () => subject.Should().BeEquivalentTo(expected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_equivalent_that_contains_an_unsupported_node_it_should_throw_a_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + + // Act + Action act = () => theDocument.Should().BeEquivalentTo(theDocument); + + // Assert + act.Should().Throw() + .WithMessage("CDATA found at /xml is not supported for equivalency comparison."); + } + + [Fact] + public void + When_asserting_an_xml_node_is_equivalent_that_isnt_it_should_include_the_right_location_in_the_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml(""); + var expected = new XmlDocument(); + expected.LoadXml(""); + + // Act + Action act = () => theDocument.Should().BeEquivalentTo(expected); + + // Assert + act.Should().Throw() + .WithMessage("Expected attribute \"c\" in theDocument at \"/xml/b\" to have value \"e\", but found \"d\"."); + } } - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_lacks_elements_it_should_fail_with_descriptive_message() + public class NotBeEquivalentTo { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected \"data\" in theDocument because we want to test the failure message, but found end of document."); + [Fact] + public void When_asserting_an_xml_node_is_not_equivalent_to_som_other_xml_node_it_should_succeed() + { + // Arrange + var subject = new XmlDocument(); + subject.LoadXml("a"); + var unexpected = new XmlDocument(); + unexpected.LoadXml("b"); + + // Act + Action act = () => + subject.Should().NotBeEquivalentTo(unexpected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_xml_node_is_not_equivalent_to_same_xml_node_it_should_fail_with_descriptive_message() + { + // Arrange + var theDocument = new XmlDocument(); + theDocument.LoadXml("a"); + + // Act + Action act = () => + theDocument.Should().NotBeEquivalentTo(theDocument, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Did not expect theDocument to be equivalent because we want to test the failure message, but it is."); + } } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_lacks_attributes_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message, but found none."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_extra_attributes_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Did not expect to find attribute \"a\" in theDocument at \"/xml/element\" because we want to test the failure message."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_different_attribute_values_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected attribute \"a\" in theDocument at \"/xml/element\" to have value \"c\" because we want to test the failure message, but found \"b\"."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_attribute_with_different_namespace_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Did not expect to find attribute \"ns:a\" in theDocument at \"/xml/element\" because we want to test the failure message."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_which_has_different_text_contents_it_should_fail_with_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml("a"); - var expected = new XmlDocument(); - expected.LoadXml("b"); - - // Act - Action act = () => - theDocument.Should().BeEquivalentTo(expected, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected content to be \"b\" in theDocument at \"/xml\" because we want to test the failure message, but found \"a\"."); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_with_different_comments_it_should_succeed() - { - // Arrange - var subject = new XmlDocument(); - subject.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => subject.Should().BeEquivalentTo(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_to_different_xml_node_with_different_insignificant_whitespace_it_should_succeed() - { - // Arrange - var subject = new XmlDocument() { PreserveWhitespace = true }; - subject.LoadXml(""); - var expected = new XmlDocument() { PreserveWhitespace = true }; - expected.LoadXml("\n \n \r\n"); - - // Act - Action act = () => subject.Should().BeEquivalentTo(expected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_xml_node_is_equivalent_that_contains_an_unsupported_node_it_should_throw_a_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - - // Act - Action act = () => theDocument.Should().BeEquivalentTo(theDocument); - - // Assert - act.Should().Throw() - .WithMessage("CDATA found at /xml is not supported for equivalency comparison."); - } - - [Fact] - public void - When_asserting_an_xml_node_is_equivalent_that_isnt_it_should_include_the_right_location_in_the_descriptive_message() - { - // Arrange - var theDocument = new XmlDocument(); - theDocument.LoadXml(""); - var expected = new XmlDocument(); - expected.LoadXml(""); - - // Act - Action act = () => theDocument.Should().BeEquivalentTo(expected); - - // Assert - act.Should().Throw() - .WithMessage("Expected attribute \"c\" in theDocument at \"/xml/b\" to have value \"e\", but found \"d\"."); - } - - #endregion } } From d96b587e469bdd79d45adefea78a2de7d6890a8d Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Sat, 23 Apr 2022 21:03:12 +0200 Subject: [PATCH 41/48] Seperate all `Types` assertions into nested classes --- .../Types/MethodBaseAssertionSpecs.cs | 1526 ++++++++-------- .../Types/MethodInfoAssertionSpecs.cs | 1190 ++++++------ .../Types/MethodInfoSelectorAssertionSpecs.cs | 790 ++++---- .../Types/PropertyInfoAssertionSpecs.cs | 1606 ++++++++--------- .../PropertyInfoSelectorAssertionSpecs.cs | 535 +++--- .../Types/TypeAssertionSpecs.Be.cs | 396 ++-- .../Types/TypeAssertionSpecs.BeAbstract.cs | 264 ++- .../TypeAssertionSpecs.BeAssignableTo.cs | 642 ++++--- .../TypeAssertionSpecs.BeDecoratedWith.cs | 376 ++-- ...AssertionSpecs.BeDecoratedWithOrInherit.cs | 378 ++-- .../Types/TypeAssertionSpecs.BeDerivedFrom.cs | 488 +++-- .../Types/TypeAssertionSpecs.BeSealed.cs | 264 ++- .../Types/TypeAssertionSpecs.BeStatic.cs | 264 ++- .../TypeAssertionSpecs.HaveAccessModifier.cs | 622 +++---- .../TypeAssertionSpecs.HaveConstructor.cs | 252 ++- ...peAssertionSpecs.HaveDefaultConstructor.cs | 324 ++-- ...ionSpecs.HaveExplicitConversionOperator.cs | 520 +++--- .../TypeAssertionSpecs.HaveExplicitMethod.cs | 1010 ++++++----- ...TypeAssertionSpecs.HaveExplicitProperty.cs | 890 +++++---- ...ionSpecs.HaveImplicitConversionOperator.cs | 556 +++--- .../Types/TypeAssertionSpecs.HaveIndexer.cs | 318 ++-- .../Types/TypeAssertionSpecs.HaveMethod.cs | 436 +++-- .../Types/TypeAssertionSpecs.HaveProperty.cs | 473 +++-- .../Types/TypeAssertionSpecs.Implement.cs | 314 ++-- .../Types/TypeSelectorAssertionSpecs.cs | 1384 +++++++------- 25 files changed, 7858 insertions(+), 7960 deletions(-) diff --git a/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs index fbdec52df0..107a2bb2d9 100644 --- a/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs @@ -8,774 +8,766 @@ namespace FluentAssertions.Specs.Types { public class MethodBaseAssertionSpecs { - #region Return - - [Fact] - public void When_asserting_an_int_method_returns_int_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().Return(typeof(int)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_int_method_returns_string_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().Return(typeof(string), "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method IntMethod to be System.String because we want to test the " + - "error message, but it is \"System.Int32\"."); - } - - [Fact] - public void When_asserting_a_void_method_returns_string_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("VoidMethod"); - - // Act - Action act = () => - methodInfo.Should().Return(typeof(string), "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method VoidMethod to be System.String because we want to test the " + - "error message, but it is \"System.Void\"."); - } - - [Fact] - public void When_subject_is_null_return_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().Return(typeof(string), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected the return type of method to be *.String *failure message*, but methodInfo is ."); - } - - [Fact] - public void When_asserting_method_return_type_is_null_it_should_throw() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().Return(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("returnType"); - } - - #endregion - - #region NotReturn - - [Fact] - public void When_asserting_an_int_method_does_not_return_string_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturn(typeof(string)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_int_method_does_not_return_int_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturn(typeof(int), "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of*IntMethod*not to be System.Int32*because we want to test the " + - "error message, but it is."); - } - - [Fact] - public void When_subject_is_null_not_return_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotReturn(typeof(string), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method not to be *.String *failure message*, but methodInfo is ."); - } - - [Fact] - public void When_asserting_method_return_type_is_not_null_it_should_throw() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturn(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("returnType"); - } - - #endregion - - #region ReturnOfT - - [Fact] - public void When_asserting_an_int_method_returnsOfT_int_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().Return(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_int_method_returnsOfT_string_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().Return("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method IntMethod to be System.String because we want to test the " + - "error message, but it is \"System.Int32\"."); - } - - [Fact] - public void When_subject_is_null_returnOfT_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().Return("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method to be *.String *failure message*, but methodInfo is ."); - } - - #endregion - - #region NotReturnOfT - - [Fact] - public void When_asserting_an_int_method_does_not_returnsOfT_string_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturn(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_int_method_does_not_returnsOfT_int_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturn("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of*IntMethod*not to be System.Int32*because we want to test the " + - "error message, but it is."); - } - - [Fact] - public void When_subject_is_null_not_returnOfT_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotReturn("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method not to be *.String *failure message*, but methodInfo is ."); - } - - #endregion - - #region ReturnVoid - - [Fact] - public void When_asserting_a_void_method_returns_void_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("VoidMethod"); - - // Act - Action act = () => - methodInfo.Should().ReturnVoid(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_int_method_returns_void_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().ReturnVoid("because we want to test the error message {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method IntMethod to be void because we want to test the error message " + - "message, but it is \"System.Int32\"."); - } - - [Fact] - public void When_subject_is_null_return_void_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().ReturnVoid("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method to be void *failure message*, but methodInfo is ."); - } - - #endregion - - #region NotReturnVoid - - [Fact] - public void When_asserting_an_int_method_does_not_return_void_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturnVoid(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_void_method_does_not_return_void_it_fails_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("VoidMethod"); - - // Act - Action act = () => - methodInfo.Should().NotReturnVoid("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of*VoidMethod*not to be void*because we want to test the error message*"); - } - - [Fact] - public void When_subject_is_null_not_return_void_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotReturnVoid("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected the return type of method not to be void *failure message*, but methodInfo is ."); - } - - #endregion - - #region HaveAccessModifier - - [Fact] - public void When_asserting_a_private_member_is_private_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Private); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_private_protected_member_is_private_protected_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateProtectedMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.PrivateProtected); - - // Assert - act.Should().NotThrow(); + public class Return + { + [Fact] + public void When_asserting_an_int_method_returns_int_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().Return(typeof(int)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_int_method_returns_string_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().Return(typeof(string), "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method IntMethod to be System.String because we want to test the " + + "error message, but it is \"System.Int32\"."); + } + + [Fact] + public void When_asserting_a_void_method_returns_string_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("VoidMethod"); + + // Act + Action act = () => + methodInfo.Should().Return(typeof(string), "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method VoidMethod to be System.String because we want to test the " + + "error message, but it is \"System.Void\"."); + } + + [Fact] + public void When_subject_is_null_return_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().Return(typeof(string), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected the return type of method to be *.String *failure message*, but methodInfo is ."); + } + + [Fact] + public void When_asserting_method_return_type_is_null_it_should_throw() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().Return(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("returnType"); + } + } + + public class NotReturn + { + [Fact] + public void When_asserting_an_int_method_does_not_return_string_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturn(typeof(string)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_int_method_does_not_return_int_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturn(typeof(int), "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of*IntMethod*not to be System.Int32*because we want to test the " + + "error message, but it is."); + } + + [Fact] + public void When_subject_is_null_not_return_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotReturn(typeof(string), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method not to be *.String *failure message*, but methodInfo is ."); + } + + [Fact] + public void When_asserting_method_return_type_is_not_null_it_should_throw() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturn(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("returnType"); + } + } + + public class ReturnOfT + { + [Fact] + public void When_asserting_an_int_method_returnsOfT_int_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().Return(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_int_method_returnsOfT_string_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().Return("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method IntMethod to be System.String because we want to test the " + + "error message, but it is \"System.Int32\"."); + } + + [Fact] + public void When_subject_is_null_returnOfT_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().Return("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method to be *.String *failure message*, but methodInfo is ."); + } + } + + public class NotReturnOfT + { + [Fact] + public void When_asserting_an_int_method_does_not_returnsOfT_string_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturn(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_int_method_does_not_returnsOfT_int_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturn("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of*IntMethod*not to be System.Int32*because we want to test the " + + "error message, but it is."); + } + + [Fact] + public void When_subject_is_null_not_returnOfT_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotReturn("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method not to be *.String *failure message*, but methodInfo is ."); + } + } + + public class ReturnVoid + { + [Fact] + public void When_asserting_a_void_method_returns_void_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("VoidMethod"); + + // Act + Action act = () => + methodInfo.Should().ReturnVoid(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_int_method_returns_void_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().ReturnVoid("because we want to test the error message {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method IntMethod to be void because we want to test the error message " + + "message, but it is \"System.Int32\"."); + } + + [Fact] + public void When_subject_is_null_return_void_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().ReturnVoid("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method to be void *failure message*, but methodInfo is ."); + } + } + + public class NotReturnVoid + { + [Fact] + public void When_asserting_an_int_method_does_not_return_void_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("IntMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturnVoid(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_void_method_does_not_return_void_it_fails_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("VoidMethod"); + + // Act + Action act = () => + methodInfo.Should().NotReturnVoid("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of*VoidMethod*not to be void*because we want to test the error message*"); + } + + [Fact] + public void When_subject_is_null_not_return_void_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotReturnVoid("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected the return type of method not to be void *failure message*, but methodInfo is ."); + } + } + + public class HaveAccessModifier + { + [Fact] + public void When_asserting_a_private_member_is_private_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Private); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_protected_member_is_private_protected_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateProtectedMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.PrivateProtected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_member_is_protected_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method PrivateMethod to be Protected because we want to test the error message, but it is " + + "Private."); + } + + [Fact] + public void When_asserting_a_protected_member_is_protected_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); + + MethodInfo setMethod = propertyInfo.SetMethod; + + // Act + Action act = () => + setMethod.Should().HaveAccessModifier(CSharpAccessModifier.Protected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_protected_member_is_public_it_throws_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); + + MethodInfo setMethod = propertyInfo.SetMethod; + + // Act + Action act = () => + setMethod + .Should() + .HaveAccessModifier(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method set_ProtectedSetProperty to be Public because we want to test the error message, but it" + + " is Protected."); + } + + [Fact] + public void When_asserting_a_public_member_is_public_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); + + MethodInfo getMethod = propertyInfo.GetMethod; + + // Act + Action act = () => + getMethod.Should().HaveAccessModifier(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_public_member_is_internal_it_throws_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); + + MethodInfo getMethod = propertyInfo.GetMethod; + + // Act + Action act = () => + getMethod + .Should() + .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method get_PublicGetProperty to be Internal because we want to test the error message, but it" + + " is Public."); + } + + [Fact] + public void When_asserting_an_internal_member_is_internal_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Internal); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_internal_member_is_protectedInternal_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" + + " error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method InternalMethod to be ProtectedInternal because we want to test the error message, but" + + " it is Internal."); + } + + [Fact] + public void When_asserting_a_protected_internal_member_is_protected_internal_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_protected_internal_member_is_private_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method ProtectedInternalMethod to be Private because we want to test the error message, but it is " + + "ProtectedInternal."); + } + + [Fact] + public void When_subject_is_null_have_access_modifier_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method to be Public *failure message*, but methodInfo is ."); + } + + [Fact] + public void When_asserting_method_has_access_modifier_with_an_invalid_enum_value_it_should_throw() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().HaveAccessModifier((CSharpAccessModifier)int.MaxValue); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("accessModifier"); + } + } + + public class NotHaveAccessModifier + { + [Fact] + public void When_asserting_a_private_member_is_not_protected_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Protected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_member_is_not_private_protected_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.PrivateProtected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_member_is_not_private_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method PrivateMethod not to be Private*because we want to test the error message*"); + } + + [Fact] + public void When_asserting_a_protected_member_is_not_internal_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); + MethodInfo setMethod = propertyInfo.SetMethod; + + // Act + Action act = () => + setMethod.Should().NotHaveAccessModifier(CSharpAccessModifier.Internal); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_protected_member_is_not_protected_it_throws_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); + MethodInfo setMethod = propertyInfo.SetMethod; + + // Act + Action act = () => + setMethod + .Should() + .NotHaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method set_ProtectedSetProperty not to be Protected*because we want to test the error message*"); + } + + [Fact] + public void When_asserting_a_public_member_is_not_private_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); + MethodInfo getMethod = propertyInfo.GetMethod; + + // Act + Action act = () => + getMethod.Should().NotHaveAccessModifier(CSharpAccessModifier.Private); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_protected_member_is_not_private_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetPrivateProtectedSet"); + MethodInfo setMethod = propertyInfo.SetMethod; + + // Act + Action act = () => + setMethod.Should().NotHaveAccessModifier(CSharpAccessModifier.Private); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_public_member_is_not_public_it_throws_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); + MethodInfo getMethod = propertyInfo.GetMethod; + + // Act + Action act = () => + getMethod + .Should() + .NotHaveAccessModifier(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method get_PublicGetProperty not to be Public*because we want to test the error message*"); + } + + [Fact] + public void When_asserting_an_internal_member_is_not_protectedInternal_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.ProtectedInternal); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_internal_member_is_not_internal_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Internal, "because we want to test the" + + " error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method InternalMethod not to be Internal*because we want to test the error message*"); + } + + [Fact] + public void When_asserting_a_protected_internal_member_is_not_public_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_protected_internal_member_is_not_protected_internal_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method ProtectedInternalMethod not to be ProtectedInternal*because we want to test the error message*"); + } + + [Fact] + public void When_subject_is_not_null_have_access_modifier_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier( + CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method not to be Public *failure message*, but methodInfo is ."); + } + + [Fact] + public void When_asserting_method_does_not_have_access_modifier_with_an_invalid_enum_value_it_should_throw() + { + // Arrange + MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); + + // Act + Action act = () => + methodInfo.Should().NotHaveAccessModifier((CSharpAccessModifier)int.MaxValue); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("accessModifier"); + } } - - [Fact] - public void When_asserting_a_private_member_is_protected_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method PrivateMethod to be Protected because we want to test the error message, but it is " + - "Private."); - } - - [Fact] - public void When_asserting_a_protected_member_is_protected_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); - - MethodInfo setMethod = propertyInfo.SetMethod; - - // Act - Action act = () => - setMethod.Should().HaveAccessModifier(CSharpAccessModifier.Protected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_protected_member_is_public_it_throws_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); - - MethodInfo setMethod = propertyInfo.SetMethod; - - // Act - Action act = () => - setMethod - .Should() - .HaveAccessModifier(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method set_ProtectedSetProperty to be Public because we want to test the error message, but it" + - " is Protected."); - } - - [Fact] - public void When_asserting_a_public_member_is_public_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); - - MethodInfo getMethod = propertyInfo.GetMethod; - - // Act - Action act = () => - getMethod.Should().HaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_public_member_is_internal_it_throws_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); - - MethodInfo getMethod = propertyInfo.GetMethod; - - // Act - Action act = () => - getMethod - .Should() - .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method get_PublicGetProperty to be Internal because we want to test the error message, but it" + - " is Public."); - } - - [Fact] - public void When_asserting_an_internal_member_is_internal_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Internal); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_internal_member_is_protectedInternal_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" + - " error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method InternalMethod to be ProtectedInternal because we want to test the error message, but" + - " it is Internal."); - } - - [Fact] - public void When_asserting_a_protected_internal_member_is_protected_internal_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_protected_internal_member_is_private_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method ProtectedInternalMethod to be Private because we want to test the error message, but it is " + - "ProtectedInternal."); - } - - [Fact] - public void When_subject_is_null_have_access_modifier_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method to be Public *failure message*, but methodInfo is ."); - } - - [Fact] - public void When_asserting_method_has_access_modifier_with_an_invalid_enum_value_it_should_throw() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().HaveAccessModifier((CSharpAccessModifier)int.MaxValue); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("accessModifier"); - } - - #endregion - - #region NotHaveAccessModifier - - [Fact] - public void When_asserting_a_private_member_is_not_protected_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Protected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_private_member_is_not_private_protected_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.PrivateProtected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_private_member_is_not_private_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method PrivateMethod not to be Private*because we want to test the error message*"); - } - - [Fact] - public void When_asserting_a_protected_member_is_not_internal_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); - MethodInfo setMethod = propertyInfo.SetMethod; - - // Act - Action act = () => - setMethod.Should().NotHaveAccessModifier(CSharpAccessModifier.Internal); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_protected_member_is_not_protected_it_throws_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("ProtectedSetProperty"); - MethodInfo setMethod = propertyInfo.SetMethod; - - // Act - Action act = () => - setMethod - .Should() - .NotHaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method set_ProtectedSetProperty not to be Protected*because we want to test the error message*"); - } - - [Fact] - public void When_asserting_a_public_member_is_not_private_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); - MethodInfo getMethod = propertyInfo.GetMethod; - - // Act - Action act = () => - getMethod.Should().NotHaveAccessModifier(CSharpAccessModifier.Private); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_private_protected_member_is_not_private_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetPrivateProtectedSet"); - MethodInfo setMethod = propertyInfo.SetMethod; - - // Act - Action act = () => - setMethod.Should().NotHaveAccessModifier(CSharpAccessModifier.Private); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_public_member_is_not_public_it_throws_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(TestClass).FindPropertyByName("PublicGetProperty"); - MethodInfo getMethod = propertyInfo.GetMethod; - - // Act - Action act = () => - getMethod - .Should() - .NotHaveAccessModifier(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method get_PublicGetProperty not to be Public*because we want to test the error message*"); - } - - [Fact] - public void When_asserting_an_internal_member_is_not_protectedInternal_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.ProtectedInternal); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_an_internal_member_is_not_internal_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("InternalMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Internal, "because we want to test the" + - " error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method InternalMethod not to be Internal*because we want to test the error message*"); - } - - [Fact] - public void When_asserting_a_protected_internal_member_is_not_public_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_protected_internal_member_is_not_protected_internal_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("ProtectedInternalMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method ProtectedInternalMethod not to be ProtectedInternal*because we want to test the error message*"); - } - - [Fact] - public void When_subject_is_not_null_have_access_modifier_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier( - CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method not to be Public *failure message*, but methodInfo is ."); - } - - [Fact] - public void When_asserting_method_does_not_have_access_modifier_with_an_invalid_enum_value_it_should_throw() - { - // Arrange - MethodInfo methodInfo = typeof(TestClass).GetParameterlessMethod("PrivateMethod"); - - // Act - Action act = () => - methodInfo.Should().NotHaveAccessModifier((CSharpAccessModifier)int.MaxValue); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("accessModifier"); - } - - #endregion } #region Internal classes used in unit tests diff --git a/Tests/FluentAssertions.Specs/Types/MethodInfoAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/MethodInfoAssertionSpecs.cs index 3c6fdd695f..cfb0145cc5 100644 --- a/Tests/FluentAssertions.Specs/Types/MethodInfoAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/MethodInfoAssertionSpecs.cs @@ -10,604 +10,598 @@ namespace FluentAssertions.Specs.Types { public class MethodInfoAssertionSpecs { - #region BeVirtual - - [Fact] - public void When_asserting_a_method_is_virtual_and_it_is_then_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsVirtual).GetParameterlessMethod("PublicVirtualDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_virtual_but_it_is_not_then_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithNonVirtualPublicMethods).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method Void FluentAssertions*ClassWithNonVirtualPublicMethods.PublicDoNothing" + - " to be virtual because we want to test the error message," + - " but it is not virtual."); - } - - [Fact] - public void When_subject_is_null_be_virtual_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().BeVirtual("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method to be virtual *failure message*, but methodInfo is ."); - } - - #endregion - - #region NotBeVirtual - - [Fact] - public void When_asserting_a_method_is_not_virtual_and_it_is_not_then_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithNonVirtualPublicMethods).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_not_virtual_but_it_is_then_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsVirtual).GetParameterlessMethod("PublicVirtualDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method *ClassWithAllMethodsVirtual.PublicVirtualDoNothing" + - " not to be virtual because we want to test the error message," + - " but it is."); - } - - [Fact] - public void When_subject_is_null_not_be_virtual_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotBeVirtual("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method not to be virtual *failure message*, but methodInfo is ."); - } - - #endregion - - #region BeDecoratedWithOfT - - [Fact] - public void When_asserting_a_method_is_decorated_with_attribute_and_it_is_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_and_it_is_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_constructor_is_decorated_with_MethodImpl_attribute_and_it_is_it_succeeds() - { - // Arrange - ConstructorInfo constructorMethodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetConstructor(Type.EmptyTypes); - - // Act - Action act = () => - constructorMethodInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_and_it_is_not_it_throws() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing to be decorated with " + - "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_with_no_options_and_it_is_it_throws() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("NoOptions"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.NoOptions to be decorated with " + - "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_with_zero_as_options_and_it_is_it_throws() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("ZeroOptions"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.ZeroOptions to be decorated with " + - "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); - } - - [Fact] - public void When_asserting_a_class_is_decorated_with_MethodImpl_attribute_and_it_is_not_it_throws() - { - // Arrange - var type = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute); - - // Act - Action act = () => - type.Should().BeDecoratedWith(); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute to be decorated with " + - "System.Runtime.CompilerServices.MethodImplAttribute, but the attribute was not found."); - } - - [Fact] - public void When_a_method_is_decorated_with_an_attribute_it_should_allow_chaining_assertions_on_it() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => methodInfo.Should().BeDecoratedWith().Which.Filter.Should().BeFalse(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_an_attribute_but_it_is_not_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PublicDoNothing to be decorated with " + - "FluentAssertions*DummyMethodAttribute because we want to test the error message," + - " but that attribute was not found."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_BeDecoratedWith_it_should_throw() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => methodInfo.Should().BeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_attribute_matching_a_predicate_and_it_is_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(d => d.Filter); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_matching_a_predicate_and_it_is_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(x => x.Value == MethodImplOptions.NoInlining); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_an_attribute_matching_a_predicate_but_it_is_not_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(d => !d.Filter, "because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() + public class BeVirtual + { + [Fact] + public void When_asserting_a_method_is_virtual_and_it_is_then_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsVirtual).GetParameterlessMethod("PublicVirtualDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_virtual_but_it_is_not_then_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithNonVirtualPublicMethods).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method Void FluentAssertions*ClassWithNonVirtualPublicMethods.PublicDoNothing" + + " to be virtual because we want to test the error message," + + " but it is not virtual."); + } + + [Fact] + public void When_subject_is_null_be_virtual_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().BeVirtual("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method to be virtual *failure message*, but methodInfo is ."); + } + } + + public class NotBeVirtual + { + [Fact] + public void When_asserting_a_method_is_not_virtual_and_it_is_not_then_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithNonVirtualPublicMethods).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_not_virtual_but_it_is_then_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsVirtual).GetParameterlessMethod("PublicVirtualDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method *ClassWithAllMethodsVirtual.PublicVirtualDoNothing" + + " not to be virtual because we want to test the error message," + + " but it is."); + } + + [Fact] + public void When_subject_is_null_not_be_virtual_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotBeVirtual("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method not to be virtual *failure message*, but methodInfo is ."); + } + } + + public class BeDecoratedWithOfT + { + [Fact] + public void When_asserting_a_method_is_decorated_with_attribute_and_it_is_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_and_it_is_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_constructor_is_decorated_with_MethodImpl_attribute_and_it_is_it_succeeds() + { + // Arrange + ConstructorInfo constructorMethodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetConstructor(Type.EmptyTypes); + + // Act + Action act = () => + constructorMethodInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_and_it_is_not_it_throws() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing to be decorated with " + + "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_with_no_options_and_it_is_it_throws() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("NoOptions"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.NoOptions to be decorated with " + + "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_with_zero_as_options_and_it_is_it_throws() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("ZeroOptions"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.ZeroOptions to be decorated with " + + "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_class_is_decorated_with_MethodImpl_attribute_and_it_is_not_it_throws() + { + // Arrange + var type = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute); + + // Act + Action act = () => + type.Should().BeDecoratedWith(); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute to be decorated with " + + "System.Runtime.CompilerServices.MethodImplAttribute, but the attribute was not found."); + } + + [Fact] + public void When_a_method_is_decorated_with_an_attribute_it_should_allow_chaining_assertions_on_it() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => methodInfo.Should().BeDecoratedWith().Which.Filter.Should().BeFalse(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_an_attribute_but_it_is_not_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PublicDoNothing to be decorated with " + + "FluentAssertions*DummyMethodAttribute because we want to test the error message," + + " but that attribute was not found."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_BeDecoratedWith_it_should_throw() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => methodInfo.Should().BeDecoratedWith(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_attribute_matching_a_predicate_and_it_is_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(d => d.Filter); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_MethodImpl_attribute_matching_a_predicate_and_it_is_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(x => x.Value == MethodImplOptions.NoInlining); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_an_attribute_matching_a_predicate_but_it_is_not_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(d => !d.Filter, "because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PublicDoNothing to be decorated with " + + "FluentAssertions*DummyMethodAttribute because we want to test the error message," + + " but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_an_MethodImpl_attribute_matching_a_predicate_but_it_is_not_it_throws() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith(x => x.Value == MethodImplOptions.AggressiveInlining); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.DoNotInlineMe to be decorated with " + + "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_method_is_decorated_with_an_attribute_and_multiple_attributes_match_continuation_using_the_matched_value_should_fail() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothingWithSameAttributeTwice"); + + // Act + Action act = + () => + methodInfo.Should() + .BeDecoratedWith() + .Which.Filter.Should() + .BeTrue(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_subject_is_null_be_decorated_withOfT_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().BeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method to be decorated with *.DummyMethodAttribute *failure message*, but methodInfo is ."); + } + } + + public class NotBeDecoratedWithOfT + { + [Fact] + public void When_asserting_a_method_is_not_decorated_with_attribute_and_it_is_not_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_not_decorated_with_MethodImpl_attribute_and_it_is_not_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_constructor_is_not_decorated_with_MethodImpl_attribute_and_it_is_not_it_succeeds() + { + // Arrange + ConstructorInfo constructorMethodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetConstructor(new[] { typeof(string) }); + + // Act + Action act = () => + constructorMethodInfo.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_not_decorated_with_an_attribute_but_it_is_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing to not be decorated with " + + "FluentAssertions*DummyMethodAttribute because we want to test the error message," + + " but that attribute was found."); + } + + [Fact] + public void When_asserting_a_method_is_not_decorated_with_MethodImpl_attribute_and_it_is_it_throws() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith(); + + // Assert + act.Should().Throw() .WithMessage( - "Expected method Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PublicDoNothing to be decorated with " + - "FluentAssertions*DummyMethodAttribute because we want to test the error message," + - " but that attribute was not found."); + "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.DoNotInlineMe to not be decorated with " + + "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was found."); + } + + [Fact] + public void When_asserting_a_method_is_not_decorated_with_attribute_matching_a_predicate_and_it_is_not_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith(d => !d.Filter); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_injecting_a_null_predicate_into_NotBeDecoratedWith_it_should_throw() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => methodInfo.Should().NotBeDecoratedWith(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_asserting_a_method_is_not_decorated_with_an_attribute_matching_a_predicate_but_it_is_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith(d => d.Filter, "because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method Void FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing to not be decorated with " + + "FluentAssertions*DummyMethodAttribute because we want to test the error message," + + " but that attribute was found."); + } + + [Fact] + public void When_subject_is_null_not_be_decorated_withOfT_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method to not be decorated with *.DummyMethodAttribute *failure message*" + + ", but methodInfo is ."); + } + } + + public class BeAsync + { + [Fact] + public void When_asserting_a_method_is_async_and_it_is_then_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsAsync).GetParameterlessMethod("PublicAsyncDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeAsync(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_async_but_it_is_not_then_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithNonAsyncMethods).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().BeAsync("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method Task FluentAssertions*ClassWithNonAsyncMethods.PublicDoNothing" + + " to be async because we want to test the error message," + + " but it is not."); + } + + [Fact] + public void When_subject_is_null_be_async_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().BeAsync("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method to be async *failure message*, but methodInfo is ."); + } + } + + public class NotBeAsync + { + [Fact] + public void When_asserting_a_method_is_not_async_and_it_is_not_then_it_succeeds() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithNonAsyncMethods).GetParameterlessMethod("PublicDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeAsync(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_method_is_not_async_but_it_is_then_it_throws_with_a_useful_message() + { + // Arrange + MethodInfo methodInfo = typeof(ClassWithAllMethodsAsync).GetParameterlessMethod("PublicAsyncDoNothing"); + + // Act + Action act = () => + methodInfo.Should().NotBeAsync("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*ClassWithAllMethodsAsync.PublicAsyncDoNothing*" + + "not to be async*because we want to test the error message*"); + } + + [Fact] + public void When_subject_is_null_not_be_async_should_fail() + { + // Arrange + MethodInfo methodInfo = null; + + // Act + Action act = () => + methodInfo.Should().NotBeAsync("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method not to be async *failure message*, but methodInfo is ."); + } } - - [Fact] - public void When_asserting_a_method_is_decorated_with_an_MethodImpl_attribute_matching_a_predicate_but_it_is_not_it_throws() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith(x => x.Value == MethodImplOptions.AggressiveInlining); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.DoNotInlineMe to be decorated with " + - "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was not found."); - } - - [Fact] - public void When_asserting_a_method_is_decorated_with_an_attribute_and_multiple_attributes_match_continuation_using_the_matched_value_should_fail() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothingWithSameAttributeTwice"); - - // Act - Action act = - () => - methodInfo.Should() - .BeDecoratedWith() - .Which.Filter.Should() - .BeTrue(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_subject_is_null_be_decorated_withOfT_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().BeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method to be decorated with *.DummyMethodAttribute *failure message*, but methodInfo is ."); - } - - #endregion - - #region NotBeDecoratedWithOfT - - [Fact] - public void When_asserting_a_method_is_not_decorated_with_attribute_and_it_is_not_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_not_decorated_with_MethodImpl_attribute_and_it_is_not_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_constructor_is_not_decorated_with_MethodImpl_attribute_and_it_is_not_it_succeeds() - { - // Arrange - ConstructorInfo constructorMethodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetConstructor(new[] { typeof(string) }); - - // Act - Action act = () => - constructorMethodInfo.Should().NotBeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_not_decorated_with_an_attribute_but_it_is_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing to not be decorated with " + - "FluentAssertions*DummyMethodAttribute because we want to test the error message," + - " but that attribute was found."); - } - - [Fact] - public void When_asserting_a_method_is_not_decorated_with_MethodImpl_attribute_and_it_is_it_throws() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithMethodWithImplementationAttribute).GetParameterlessMethod("DoNotInlineMe"); - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith(); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithMethodWithImplementationAttribute.DoNotInlineMe to not be decorated with " + - "System.Runtime.CompilerServices.MethodImplAttribute, but that attribute was found."); - } - - [Fact] - public void When_asserting_a_method_is_not_decorated_with_attribute_matching_a_predicate_and_it_is_not_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith(d => !d.Filter); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_injecting_a_null_predicate_into_NotBeDecoratedWith_it_should_throw() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => methodInfo.Should().NotBeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_asserting_a_method_is_not_decorated_with_an_attribute_matching_a_predicate_but_it_is_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsDecoratedWithDummyAttribute).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith(d => d.Filter, "because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method Void FluentAssertions*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing to not be decorated with " + - "FluentAssertions*DummyMethodAttribute because we want to test the error message," + - " but that attribute was found."); - } - - [Fact] - public void When_subject_is_null_not_be_decorated_withOfT_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method to not be decorated with *.DummyMethodAttribute *failure message*" + - ", but methodInfo is ."); - } - - #endregion - - #region BeAsync - - [Fact] - public void When_asserting_a_method_is_async_and_it_is_then_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsAsync).GetParameterlessMethod("PublicAsyncDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeAsync(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_async_but_it_is_not_then_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithNonAsyncMethods).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().BeAsync("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method Task FluentAssertions*ClassWithNonAsyncMethods.PublicDoNothing" + - " to be async because we want to test the error message," + - " but it is not."); - } - - [Fact] - public void When_subject_is_null_be_async_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().BeAsync("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method to be async *failure message*, but methodInfo is ."); - } - - #endregion - - #region NotBeAsync - - [Fact] - public void When_asserting_a_method_is_not_async_and_it_is_not_then_it_succeeds() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithNonAsyncMethods).GetParameterlessMethod("PublicDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeAsync(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_method_is_not_async_but_it_is_then_it_throws_with_a_useful_message() - { - // Arrange - MethodInfo methodInfo = typeof(ClassWithAllMethodsAsync).GetParameterlessMethod("PublicAsyncDoNothing"); - - // Act - Action act = () => - methodInfo.Should().NotBeAsync("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*ClassWithAllMethodsAsync.PublicAsyncDoNothing*" + - "not to be async*because we want to test the error message*"); - } - - [Fact] - public void When_subject_is_null_not_be_async_should_fail() - { - // Arrange - MethodInfo methodInfo = null; - - // Act - Action act = () => - methodInfo.Should().NotBeAsync("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method not to be async *failure message*, but methodInfo is ."); - } - - #endregion } #region Internal classes used in unit tests @@ -764,6 +758,6 @@ private void DoNothingWithAnotherParameter(string _) { } } - - #endregion } + +#endregion diff --git a/Tests/FluentAssertions.Specs/Types/MethodInfoSelectorAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/MethodInfoSelectorAssertionSpecs.cs index ca457d9c36..cba590149e 100644 --- a/Tests/FluentAssertions.Specs/Types/MethodInfoSelectorAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/MethodInfoSelectorAssertionSpecs.cs @@ -8,427 +8,419 @@ namespace FluentAssertions.Specs.Types { public class MethodInfoSelectorAssertionSpecs { - #region BeVirtual - - [Fact] - public void When_asserting_methods_are_virtual_and_they_are_it_should_succeed() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsVirtual)); - - // Act - Action act = () => - methodSelector.Should().BeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_methods_are_virtual_but_non_virtual_methods_are_found_it_should_throw() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonVirtualPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().BeVirtual(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_methods_are_virtual_but_non_virtual_methods_are_found_it_should_throw_with_descriptive_message() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonVirtualPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().BeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods" + - " to be virtual because we want to test the error message," + - " but the following methods are not virtual:*" + - "Void FluentAssertions*ClassWithNonVirtualPublicMethods.PublicDoNothing*" + - "Void FluentAssertions*ClassWithNonVirtualPublicMethods.InternalDoNothing*" + - "Void FluentAssertions*ClassWithNonVirtualPublicMethods.ProtectedDoNothing"); - } - - #endregion - - #region NotBeVirtual - - [Fact] - public void When_asserting_methods_are_not_virtual_and_they_are_not_it_should_succeed() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonVirtualPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().NotBeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_methods_are_not_virtual_but_virtual_methods_are_found_it_should_throw() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsVirtual)); - - // Act - Action act = () => - methodSelector.Should().NotBeVirtual(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_methods_are_not_virtual_but_virtual_methods_are_found_it_should_throw_with_descriptive_message() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsVirtual)); - - // Act - Action act = () => - methodSelector.Should().NotBeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods" + - " not to be virtual because we want to test the error message," + - " but the following methods are virtual" + - "*ClassWithAllMethodsVirtual.PublicVirtualDoNothing" + - "*ClassWithAllMethodsVirtual.InternalVirtualDoNothing" + - "*ClassWithAllMethodsVirtual.ProtectedVirtualDoNothing*"); - } - - #endregion - - #region BeDecoratedWith - - [Fact] - public void When_injecting_a_null_predicate_into_BeDecoratedWith_it_should_throw() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)); - - // Act - Action act = () => - methodSelector.Should().BeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_asserting_methods_are_decorated_with_attribute_and_they_are_it_should_succeed() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)); - - // Act - Action act = () => - methodSelector.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_methods_are_decorated_with_attribute_but_they_are_not_it_should_throw() - { - // Arrange - MethodInfoSelector methodSelector = - new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)) - .ThatArePublicOrInternal; - - // Act - Action act = () => - methodSelector.Should().BeDecoratedWith(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_methods_are_decorated_with_attribute_but_they_are_not_it_should_throw_with_descriptive_message() + public class BeVirtual { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)); - - // Act - Action act = () => - methodSelector.Should().BeDecoratedWith("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods to be decorated with" + - " FluentAssertions*DummyMethodAttribute because we want to test the error message," + - " but the following methods are not:*" + - "Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PublicDoNothing*" + - "Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.ProtectedDoNothing*" + - "Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PrivateDoNothing"); + [Fact] + public void When_asserting_methods_are_virtual_and_they_are_it_should_succeed() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsVirtual)); + + // Act + Action act = () => + methodSelector.Should().BeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_methods_are_virtual_but_non_virtual_methods_are_found_it_should_throw() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonVirtualPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().BeVirtual(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_methods_are_virtual_but_non_virtual_methods_are_found_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonVirtualPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().BeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods" + + " to be virtual because we want to test the error message," + + " but the following methods are not virtual:*" + + "Void FluentAssertions*ClassWithNonVirtualPublicMethods.PublicDoNothing*" + + "Void FluentAssertions*ClassWithNonVirtualPublicMethods.InternalDoNothing*" + + "Void FluentAssertions*ClassWithNonVirtualPublicMethods.ProtectedDoNothing"); + } } - #endregion - - #region NotBeDecoratedWith - - [Fact] - public void When_injecting_a_null_predicate_into_NotBeDecoratedWith_it_should_throw() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)); - - // Act - Action act = () => - methodSelector.Should().NotBeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_asserting_methods_are_not_decorated_with_attribute_and_they_are_not_it_should_succeed() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)); - - // Act - Action act = () => - methodSelector.Should().NotBeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_methods_are_not_decorated_with_attribute_but_they_are_it_should_throw() - { - // Arrange - MethodInfoSelector methodSelector = - new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)) - .ThatArePublicOrInternal; - - // Act - Action act = () => - methodSelector.Should().NotBeDecoratedWith(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_methods_are_not_decorated_with_attribute_but_they_are_it_should_throw_with_descriptive_message() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)); - - // Act - Action act = () => - methodSelector.Should().NotBeDecoratedWith("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods to not be decorated*DummyMethodAttribute*because we want to test the error message" + - "*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing*" + - "*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothingWithSameAttributeTwice*" + - "*ClassWithAllMethodsDecoratedWithDummyAttribute.ProtectedDoNothing*" + - "*ClassWithAllMethodsDecoratedWithDummyAttribute.PrivateDoNothing"); - } - - #endregion - - #region Be - - [Fact] - public void When_all_methods_have_specified_accessor_it_should_succeed() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().Be(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_not_all_methods_have_specified_accessor_it_should_throw() + public class NotBeVirtual { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().Be(CSharpAccessModifier.Public); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods to be Public" + - ", but the following methods are not:*" + - "Void FluentAssertions*ClassWithNonPublicMethods.PublicDoNothing*" + - "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithParameter*" + - "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithAnotherParameter"); + [Fact] + public void When_asserting_methods_are_not_virtual_and_they_are_not_it_should_succeed() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonVirtualPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().NotBeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_methods_are_not_virtual_but_virtual_methods_are_found_it_should_throw() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsVirtual)); + + // Act + Action act = () => + methodSelector.Should().NotBeVirtual(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_methods_are_not_virtual_but_virtual_methods_are_found_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsVirtual)); + + // Act + Action act = () => + methodSelector.Should().NotBeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods" + + " not to be virtual because we want to test the error message," + + " but the following methods are virtual" + + "*ClassWithAllMethodsVirtual.PublicVirtualDoNothing" + + "*ClassWithAllMethodsVirtual.InternalVirtualDoNothing" + + "*ClassWithAllMethodsVirtual.ProtectedVirtualDoNothing*"); + } } - [Fact] - public void When_not_all_methods_have_specified_accessor_it_should_throw_with_descriptive_message() + public class BeDecoratedWith { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().Be(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods to be Public" + - " because we want to test the error message" + - ", but the following methods are not:*" + - "Void FluentAssertions*ClassWithNonPublicMethods.PublicDoNothing*" + - "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithParameter*" + - "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithAnotherParameter"); + [Fact] + public void When_injecting_a_null_predicate_into_BeDecoratedWith_it_should_throw() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)); + + // Act + Action act = () => + methodSelector.Should().BeDecoratedWith(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_asserting_methods_are_decorated_with_attribute_and_they_are_it_should_succeed() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)); + + // Act + Action act = () => + methodSelector.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_methods_are_decorated_with_attribute_but_they_are_not_it_should_throw() + { + // Arrange + MethodInfoSelector methodSelector = + new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)) + .ThatArePublicOrInternal; + + // Act + Action act = () => + methodSelector.Should().BeDecoratedWith(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_methods_are_decorated_with_attribute_but_they_are_not_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)); + + // Act + Action act = () => + methodSelector.Should().BeDecoratedWith("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods to be decorated with" + + " FluentAssertions*DummyMethodAttribute because we want to test the error message," + + " but the following methods are not:*" + + "Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PublicDoNothing*" + + "Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.ProtectedDoNothing*" + + "Void FluentAssertions*ClassWithMethodsThatAreNotDecoratedWithDummyAttribute.PrivateDoNothing"); + } } - #endregion - - #region NotBe - - [Fact] - public void When_all_methods_does_not_have_specified_accessor_it_should_succeed() + public class NotBeDecoratedWith { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().NotBe(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_injecting_a_null_predicate_into_NotBeDecoratedWith_it_should_throw() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)); + + // Act + Action act = () => + methodSelector.Should().NotBeDecoratedWith(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_asserting_methods_are_not_decorated_with_attribute_and_they_are_not_it_should_succeed() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithMethodsThatAreNotDecoratedWithDummyAttribute)); + + // Act + Action act = () => + methodSelector.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_methods_are_not_decorated_with_attribute_but_they_are_it_should_throw() + { + // Arrange + MethodInfoSelector methodSelector = + new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)) + .ThatArePublicOrInternal; + + // Act + Action act = () => + methodSelector.Should().NotBeDecoratedWith(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_methods_are_not_decorated_with_attribute_but_they_are_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsDecoratedWithDummyAttribute)); + + // Act + Action act = () => + methodSelector.Should().NotBeDecoratedWith("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods to not be decorated*DummyMethodAttribute*because we want to test the error message" + + "*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothing*" + + "*ClassWithAllMethodsDecoratedWithDummyAttribute.PublicDoNothingWithSameAttributeTwice*" + + "*ClassWithAllMethodsDecoratedWithDummyAttribute.ProtectedDoNothing*" + + "*ClassWithAllMethodsDecoratedWithDummyAttribute.PrivateDoNothing"); + } } - [Fact] - public void When_any_method_have_specified_accessor_it_should_throw() + public class Be { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().NotBe(CSharpAccessModifier.Public); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods to not be Public" + - ", but the following methods are:*" + - "Void FluentAssertions*ClassWithPublicMethods.PublicDoNothing*"); + [Fact] + public void When_all_methods_have_specified_accessor_it_should_succeed() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().Be(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_not_all_methods_have_specified_accessor_it_should_throw() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().Be(CSharpAccessModifier.Public); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods to be Public" + + ", but the following methods are not:*" + + "Void FluentAssertions*ClassWithNonPublicMethods.PublicDoNothing*" + + "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithParameter*" + + "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithAnotherParameter"); + } + + [Fact] + public void When_not_all_methods_have_specified_accessor_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().Be(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods to be Public" + + " because we want to test the error message" + + ", but the following methods are not:*" + + "Void FluentAssertions*ClassWithNonPublicMethods.PublicDoNothing*" + + "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithParameter*" + + "Void FluentAssertions*ClassWithNonPublicMethods.DoNothingWithAnotherParameter"); + } } - [Fact] - public void When_any_method_have_specified_accessor_it_should_throw_with_descriptive_message() + public class NotBe { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithPublicMethods)); - - // Act - Action act = () => - methodSelector.Should().NotBe(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods to not be Public" + - " because we want to test the error message" + - ", but the following methods are:*" + - "Void FluentAssertions*ClassWithPublicMethods.PublicDoNothing*"); + [Fact] + public void When_all_methods_does_not_have_specified_accessor_it_should_succeed() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().NotBe(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_any_method_have_specified_accessor_it_should_throw() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().NotBe(CSharpAccessModifier.Public); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods to not be Public" + + ", but the following methods are:*" + + "Void FluentAssertions*ClassWithPublicMethods.PublicDoNothing*"); + } + + [Fact] + public void When_any_method_have_specified_accessor_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithPublicMethods)); + + // Act + Action act = () => + methodSelector.Should().NotBe(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods to not be Public" + + " because we want to test the error message" + + ", but the following methods are:*" + + "Void FluentAssertions*ClassWithPublicMethods.PublicDoNothing*"); + } } - #endregion - - #region BeAsync - - [Fact] - public void When_asserting_methods_are_async_and_they_are_then_it_succeeds() + public class BeAsync { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsAsync)); - - // Act - Action act = () => methodSelector.Should().BeAsync(); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_methods_are_async_and_they_are_then_it_succeeds() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsAsync)); + + // Act + Action act = () => methodSelector.Should().BeAsync(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_methods_are_async_but_non_async_methods_are_found_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonAsyncMethods)); + + // Act + Action act = () => methodSelector.Should().BeAsync("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods" + + " to be async because we want to test the error message," + + " but the following methods are not:" + Environment.NewLine + + "Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.PublicDoNothing" + Environment.NewLine + + "Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.InternalDoNothing" + Environment.NewLine + + "Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.ProtectedDoNothing"); + } } - [Fact] - public void When_asserting_methods_are_async_but_non_async_methods_are_found_it_should_throw_with_descriptive_message() + public class NotBeAsync { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonAsyncMethods)); - - // Act - Action act = () => methodSelector.Should().BeAsync("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods" + - " to be async because we want to test the error message," + - " but the following methods are not:" + Environment.NewLine + - "Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.PublicDoNothing" + Environment.NewLine + - "Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.InternalDoNothing" + Environment.NewLine + - "Task FluentAssertions.Specs.Types.ClassWithNonAsyncMethods.ProtectedDoNothing"); + [Fact] + public void When_asserting_methods_are_not_async_and_they_are_not_then_it_succeeds() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithNonAsyncMethods)); + + // Act + Action act = () => methodSelector.Should().NotBeAsync(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_methods_are_not_async_but_async_methods_are_found_it_should_throw_with_descriptive_message() + { + // Arrange + var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsAsync)); + + // Act + Action act = () => methodSelector.Should().NotBeAsync("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected methods" + + " not to be async because we want to test the error message," + + " but the following methods are:" + Environment.NewLine + + "Task FluentAssertions.Specs.Types.ClassWithAllMethodsAsync.PublicAsyncDoNothing" + Environment.NewLine + + "Task FluentAssertions.Specs.Types.ClassWithAllMethodsAsync.InternalAsyncDoNothing" + Environment.NewLine + + "Task FluentAssertions.Specs.Types.ClassWithAllMethodsAsync.ProtectedAsyncDoNothing"); + } } - - #endregion - - #region NotBeAsync - - [Fact] - public void When_asserting_methods_are_not_async_and_they_are_not_then_it_succeeds() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithNonAsyncMethods)); - - // Act - Action act = () => methodSelector.Should().NotBeAsync(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_methods_are_not_async_but_async_methods_are_found_it_should_throw_with_descriptive_message() - { - // Arrange - var methodSelector = new MethodInfoSelector(typeof(ClassWithAllMethodsAsync)); - - // Act - Action act = () => methodSelector.Should().NotBeAsync("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected methods" + - " not to be async because we want to test the error message," + - " but the following methods are:" + Environment.NewLine + - "Task FluentAssertions.Specs.Types.ClassWithAllMethodsAsync.PublicAsyncDoNothing" + Environment.NewLine + - "Task FluentAssertions.Specs.Types.ClassWithAllMethodsAsync.InternalAsyncDoNothing" + Environment.NewLine + - "Task FluentAssertions.Specs.Types.ClassWithAllMethodsAsync.ProtectedAsyncDoNothing"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/PropertyInfoAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/PropertyInfoAssertionSpecs.cs index 85b2a120fa..ca91a91de5 100644 --- a/Tests/FluentAssertions.Specs/Types/PropertyInfoAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/PropertyInfoAssertionSpecs.cs @@ -9,821 +9,807 @@ namespace FluentAssertions.Specs.Types { public class PropertyInfoAssertionSpecs { - #region BeVirtual + public class BeVirtual + { + [Fact] + public void When_asserting_that_a_property_is_virtual_and_it_is_then_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesVirtual).GetRuntimeProperty("PublicVirtualProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_that_a_property_is_virtual_and_it_is_not_then_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithNonVirtualPublicProperties).GetRuntimeProperty("PublicNonVirtualProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected property String FluentAssertions*ClassWithNonVirtualPublicProperties.PublicNonVirtualProperty" + + " to be virtual because we want to test the error message," + + " but it is not."); + } + + [Fact] + public void When_subject_is_null_be_virtual_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().BeVirtual("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to be virtual *failure message*, but propertyInfo is ."); + } + } + + public class NotBeVirtual + { + [Fact] + public void When_asserting_that_a_property_is_not_virtual_and_it_is_not_then_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithNonVirtualPublicProperties).GetRuntimeProperty("PublicNonVirtualProperty"); + + // Act + Action act = () => + propertyInfo.Should().NotBeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_that_a_property_is_not_virtual_and_it_is_then_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesVirtual).GetRuntimeProperty("PublicVirtualProperty"); + + // Act + Action act = () => + propertyInfo.Should().NotBeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected property *ClassWithAllPropertiesVirtual.PublicVirtualProperty" + + " not to be virtual because we want to test the error message," + + " but it is."); + } + + [Fact] + public void When_subject_is_null_not_be_virtual_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().NotBeVirtual("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property not to be virtual *failure message*, but propertyInfo is ."); + } + } + + public class BeDecortatedWithOfT + { + [Fact] + public void When_asserting_a_property_is_decorated_with_attribute_and_it_is_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_property_is_decorated_with_an_attribute_it_allow_chaining_assertions() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith().Which.Value.Should().Be("OtherValue"); + + // Assert + act.Should().Throw().WithMessage("Expected*OtherValue*Value*"); + } + + [Fact] + public void When_a_property_is_decorated_with_an_attribute_and_multiple_attributes_match_continuation_using_the_matched_value_fail() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicPropertyWithSameAttributeTwice"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith().Which.Value.Should().Be("OtherValue"); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_a_property_is_decorated_with_attribute_and_it_is_not_it_throw_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith("because we want to test the error message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property String " + + "FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.PublicProperty to be decorated with " + + "FluentAssertions*DummyPropertyAttribute because we want to test the error message, but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_property_is_decorated_with_an_attribute_matching_a_predicate_but_it_is_not_it_throw_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith(d => d.Value == "NotARealValue", "because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected property String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.PublicProperty to be decorated with " + + "FluentAssertions*DummyPropertyAttribute because we want to test the error message," + + " but that attribute was not found."); + } + + [Fact] + public void When_asserting_a_property_is_decorated_with_attribute_matching_a_predicate_and_it_is_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith(d => d.Value == "Value"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_subject_is_null_be_decorated_withOfT_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to be decorated with *.DummyPropertyAttribute *failure message*, but propertyInfo is ."); + } + + [Fact] + public void When_asserting_property_is_decorated_with_null_it_should_throw() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeDecoratedWith((Expression>)null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + } + + public class NotBeDecoratedWithOfT + { + [Fact] + public void When_subject_is_null_not_be_decorated_withOfT_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to not be decorated with *.DummyPropertyAttribute *failure message*, but propertyInfo is ."); + } + + [Fact] + public void When_asserting_property_is_not_decorated_with_null_it_should_throw() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action act = () => + propertyInfo.Should().NotBeDecoratedWith((Expression>)null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + } + + public class BeWritable + { + [Fact] + public void When_asserting_a_readonly_property_is_writable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().BeWritable("we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage("Expected propertyInfo ReadOnlyProperty to have a setter because we want to test the error message."); + } + + [Fact] + public void When_asserting_a_readwrite_property_is_writable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadWriteProperty"); + + // Act + Action action = () => propertyInfo.Should().BeWritable("that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_writeonly_property_is_writable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().BeWritable("that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_subject_is_null_be_writable_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().BeWritable("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to have a setter *failure message*, but propertyInfo is ."); + } + } + + public class BeReadable + { + [Fact] + public void When_asserting_a_readonly_property_is_readable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().BeReadable("that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_readwrite_property_is_readable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadWriteProperty"); + + // Act + Action action = () => propertyInfo.Should().BeReadable("that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_writeonly_property_is_readable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().BeReadable("we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage("Expected property WriteOnlyProperty to have a getter because we want to test the error message, but it does not."); + } + + [Fact] + public void When_subject_is_null_be_readable_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().BeReadable("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to have a getter *failure message*, but propertyInfo is ."); + } + } + + public class NotBeWritable + { + [Fact] + public void When_asserting_a_readonly_property_is_not_writable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().NotBeWritable("that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_readwrite_property_is_not_writable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadWriteProperty"); + + // Act + Action action = () => propertyInfo.Should().NotBeWritable("we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage("Expected propertyInfo ReadWriteProperty not to have a setter because we want to test the error message."); + } + + [Fact] + public void When_asserting_a_writeonly_property_is_not_writable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().NotBeWritable("we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage("Expected propertyInfo WriteOnlyProperty not to have a setter because we want to test the error message."); + } + + [Fact] + public void When_subject_is_null_not_be_writable_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().NotBeWritable("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property not to have a setter *failure message*, but propertyInfo is ."); + } + } + + public class NotBeReadable + { + [Fact] + public void When_asserting_a_readonly_property_is_not_readable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().NotBeReadable("we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage("Expected propertyInfo ReadOnlyProperty not to have a getter because we want to test the error message."); + } + + [Fact] + public void When_asserting_a_readwrite_property_is_not_readable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadWriteProperty"); + + // Act + Action action = () => propertyInfo.Should().NotBeReadable("we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage("Expected propertyInfo ReadWriteProperty not to have a getter because we want to test the error message."); + } + + [Fact] + public void When_asserting_a_writeonly_property_is_not_readable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); + + // Act + Action action = () => propertyInfo.Should().NotBeReadable("that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_subject_is_null_not_be_readable_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().NotBeReadable("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property not to have a getter *failure message*, but propertyInfo is ."); + } + } + + public class BeReadableAccessModifier + { + [Fact] + public void When_asserting_a_public_read_private_write_property_is_public_readable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadPrivateWriteProperty"); + + // Act + Action action = () => propertyInfo.Should().BeReadable(CSharpAccessModifier.Public, "that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_read_public_write_property_is_public_readable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WritePrivateReadProperty"); + + // Act + Action action = () => propertyInfo.Should().BeReadable(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected method get_WritePrivateReadProperty to be Public because we want to test the error message, but it is Private."); + } + + [Fact] + public void When_subject_is_null_be_readable_with_accessmodifier_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().BeReadable(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to be Public *failure message*, but propertyInfo is ."); + } + + [Fact] + public void When_asserting_is_readable_with_an_invalid_enum_value_it_should_throw() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeReadable((CSharpAccessModifier)int.MaxValue); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("accessModifier"); + } + } + + public class BeWritableAccessModifier + { + [Fact] + public void When_asserting_a_public_write_private_read_property_is_public_writable_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WritePrivateReadProperty"); + + // Act + Action action = () => propertyInfo.Should().BeWritable(CSharpAccessModifier.Public, "that's required"); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_private_write_public_read_property_is_public_writable_it_fails_with_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadPrivateWriteProperty"); + + // Act + Action action = () => propertyInfo.Should().BeWritable(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected method set_ReadPrivateWriteProperty to be Public because we want to test the error message, but it is Private."); + } + + [Fact] + public void When_subject_is_null_be_writable_with_accessmodifier_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().BeWritable(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected property to be Public *failure message*, but propertyInfo is ."); + } + + [Fact] + public void When_asserting_is_writable_with_an_invalid_enum_value_it_should_throw() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action act = () => + propertyInfo.Should().BeWritable((CSharpAccessModifier)int.MaxValue); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("accessModifier"); + } + } + + public class Return + { + [Fact] + public void When_asserting_a_String_property_returns_a_String_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().Return(typeof(string)); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_String_property_returns_an_Int32_it_throw_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().Return(typeof(int), "we want to test the error {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected Type of property StringProperty to be System.Int32 because we want to test the error " + + "message, but it is System.String."); + } + + [Fact] + public void When_subject_is_null_return_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().Return(typeof(int), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type of property to be *.Int32 *failure message*, but propertyInfo is ."); + } + + [Fact] + public void When_asserting_property_type_is_null_it_should_throw() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action act = () => + propertyInfo.Should().Return(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("propertyType"); + } + } + + public class ReturnOfT + { + [Fact] + public void When_asserting_a_String_property_returnsOfT_a_String_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().Return(); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_String_property_returnsOfT_an_Int32_it_throw_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().Return("we want to test the error {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected Type of property StringProperty to be System.Int32 because we want to test the error " + + "message, but it is System.String."); + } + } + + public class NotReturn + { + [Fact] + public void When_asserting_a_String_property_does_not_returns_an_Int32_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().NotReturn(typeof(int)); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_String_property_does_not_return_a_String_it_throw_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().NotReturn(typeof(string), "we want to test the error {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected Type of property StringProperty not to be*String*because we want to test the error " + + "message, but it is."); + } + + [Fact] + public void When_subject_is_null_not_return_should_fail() + { + // Arrange + PropertyInfo propertyInfo = null; + + // Act + Action act = () => + propertyInfo.Should().NotReturn(typeof(int), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type of property not to be *.Int32 *failure message*, but propertyInfo is ."); + } + + [Fact] + public void When_asserting_property_type_is_not_null_it_should_throw() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action act = () => + propertyInfo.Should().NotReturn(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("propertyType"); + } + } - [Fact] - public void When_asserting_that_a_property_is_virtual_and_it_is_then_it_succeeds() + public class NotReturnOfT { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesVirtual).GetRuntimeProperty("PublicVirtualProperty"); + [Fact] + public void When_asserting_a_String_property_does_not_returnOfT_an_Int32_it_succeeds() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - // Act - Action act = () => - propertyInfo.Should().BeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_that_a_property_is_virtual_and_it_is_not_then_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithNonVirtualPublicProperties).GetRuntimeProperty("PublicNonVirtualProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected property String FluentAssertions*ClassWithNonVirtualPublicProperties.PublicNonVirtualProperty" + - " to be virtual because we want to test the error message," + - " but it is not."); - } - - [Fact] - public void When_subject_is_null_be_virtual_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().BeVirtual("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to be virtual *failure message*, but propertyInfo is ."); + // Act + Action action = () => propertyInfo.Should().NotReturn(); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_String_property_does_not_returnsOfT_a_String_it_throw_with_a_useful_message() + { + // Arrange + PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); + + // Act + Action action = () => propertyInfo.Should().NotReturn("we want to test the error {0}", "message"); + + // Assert + action.Should().Throw() + .WithMessage("Expected Type of property StringProperty not to be*String*because we want to test the error " + + "message, but it is."); + } } - #endregion - - #region NotBeVirtual - - [Fact] - public void When_asserting_that_a_property_is_not_virtual_and_it_is_not_then_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithNonVirtualPublicProperties).GetRuntimeProperty("PublicNonVirtualProperty"); - - // Act - Action act = () => - propertyInfo.Should().NotBeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_that_a_property_is_not_virtual_and_it_is_then_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesVirtual).GetRuntimeProperty("PublicVirtualProperty"); - - // Act - Action act = () => - propertyInfo.Should().NotBeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected property *ClassWithAllPropertiesVirtual.PublicVirtualProperty" + - " not to be virtual because we want to test the error message," + - " but it is."); - } - - [Fact] - public void When_subject_is_null_not_be_virtual_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().NotBeVirtual("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property not to be virtual *failure message*, but propertyInfo is ."); - } - - #endregion - - #region BeDecortatedWithOfT - - [Fact] - public void When_asserting_a_property_is_decorated_with_attribute_and_it_is_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_a_property_is_decorated_with_an_attribute_it_allow_chaining_assertions() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith().Which.Value.Should().Be("OtherValue"); - - // Assert - act.Should().Throw().WithMessage("Expected*OtherValue*Value*"); - } - - [Fact] - public void When_a_property_is_decorated_with_an_attribute_and_multiple_attributes_match_continuation_using_the_matched_value_fail() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicPropertyWithSameAttributeTwice"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith().Which.Value.Should().Be("OtherValue"); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_a_property_is_decorated_with_attribute_and_it_is_not_it_throw_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith("because we want to test the error message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property String " + - "FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.PublicProperty to be decorated with " + - "FluentAssertions*DummyPropertyAttribute because we want to test the error message, but that attribute was not found."); - } - - [Fact] - public void When_asserting_a_property_is_decorated_with_an_attribute_matching_a_predicate_but_it_is_not_it_throw_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith(d => d.Value == "NotARealValue", "because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected property String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.PublicProperty to be decorated with " + - "FluentAssertions*DummyPropertyAttribute because we want to test the error message," + - " but that attribute was not found."); - } - - [Fact] - public void When_asserting_a_property_is_decorated_with_attribute_matching_a_predicate_and_it_is_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith(d => d.Value == "Value"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_subject_is_null_be_decorated_withOfT_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to be decorated with *.DummyPropertyAttribute *failure message*, but propertyInfo is ."); - } - - [Fact] - public void When_asserting_property_is_decorated_with_null_it_should_throw() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute).GetRuntimeProperty("PublicProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeDecoratedWith((Expression>)null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - #endregion - - #region NotBeDecoratedWithOfT - - [Fact] - public void When_subject_is_null_not_be_decorated_withOfT_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to not be decorated with *.DummyPropertyAttribute *failure message*, but propertyInfo is ."); - } - - [Fact] - public void When_asserting_property_is_not_decorated_with_null_it_should_throw() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action act = () => - propertyInfo.Should().NotBeDecoratedWith((Expression>)null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - #endregion - - #region BeWritable - - [Fact] - public void When_asserting_a_readonly_property_is_writable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().BeWritable("we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage("Expected propertyInfo ReadOnlyProperty to have a setter because we want to test the error message."); - } - - [Fact] - public void When_asserting_a_readwrite_property_is_writable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadWriteProperty"); - - // Act - Action action = () => propertyInfo.Should().BeWritable("that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_writeonly_property_is_writable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().BeWritable("that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_subject_is_null_be_writable_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().BeWritable("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to have a setter *failure message*, but propertyInfo is ."); - } - - #endregion - - #region BeReadable - - [Fact] - public void When_asserting_a_readonly_property_is_readable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().BeReadable("that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_readwrite_property_is_readable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadWriteProperty"); - - // Act - Action action = () => propertyInfo.Should().BeReadable("that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_writeonly_property_is_readable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().BeReadable("we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage("Expected property WriteOnlyProperty to have a getter because we want to test the error message, but it does not."); - } - - [Fact] - public void When_subject_is_null_be_readable_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().BeReadable("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to have a getter *failure message*, but propertyInfo is ."); - } - - #endregion - - #region NotBeWritable - - [Fact] - public void When_asserting_a_readonly_property_is_not_writable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().NotBeWritable("that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_readwrite_property_is_not_writable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadWriteProperty"); - - // Act - Action action = () => propertyInfo.Should().NotBeWritable("we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage("Expected propertyInfo ReadWriteProperty not to have a setter because we want to test the error message."); - } - - [Fact] - public void When_asserting_a_writeonly_property_is_not_writable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().NotBeWritable("we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage("Expected propertyInfo WriteOnlyProperty not to have a setter because we want to test the error message."); - } - - [Fact] - public void When_subject_is_null_not_be_writable_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().NotBeWritable("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property not to have a setter *failure message*, but propertyInfo is ."); - } - - #endregion - - #region NotBeReadable - - [Fact] - public void When_asserting_a_readonly_property_is_not_readable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().NotBeReadable("we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage("Expected propertyInfo ReadOnlyProperty not to have a getter because we want to test the error message."); - } - - [Fact] - public void When_asserting_a_readwrite_property_is_not_readable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithReadOnlyProperties).GetRuntimeProperty("ReadWriteProperty"); - - // Act - Action action = () => propertyInfo.Should().NotBeReadable("we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage("Expected propertyInfo ReadWriteProperty not to have a getter because we want to test the error message."); - } - - [Fact] - public void When_asserting_a_writeonly_property_is_not_readable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WriteOnlyProperty"); - - // Act - Action action = () => propertyInfo.Should().NotBeReadable("that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_subject_is_null_not_be_readable_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().NotBeReadable("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property not to have a getter *failure message*, but propertyInfo is ."); - } - - #endregion - - #region BeReadableAccessModifier - - [Fact] - public void When_asserting_a_public_read_private_write_property_is_public_readable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadPrivateWriteProperty"); - - // Act - Action action = () => propertyInfo.Should().BeReadable(CSharpAccessModifier.Public, "that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_private_read_public_write_property_is_public_readable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WritePrivateReadProperty"); - - // Act - Action action = () => propertyInfo.Should().BeReadable(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected method get_WritePrivateReadProperty to be Public because we want to test the error message, but it is Private."); - } - - [Fact] - public void When_subject_is_null_be_readable_with_accessmodifier_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().BeReadable(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to be Public *failure message*, but propertyInfo is ."); - } - - [Fact] - public void When_asserting_is_readable_with_an_invalid_enum_value_it_should_throw() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeReadable((CSharpAccessModifier)int.MaxValue); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("accessModifier"); - } - - #endregion - - #region BeWritableAccessModifier - - [Fact] - public void When_asserting_a_public_write_private_read_property_is_public_writable_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("WritePrivateReadProperty"); - - // Act - Action action = () => propertyInfo.Should().BeWritable(CSharpAccessModifier.Public, "that's required"); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_private_write_public_read_property_is_public_writable_it_fails_with_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("ReadPrivateWriteProperty"); - - // Act - Action action = () => propertyInfo.Should().BeWritable(CSharpAccessModifier.Public, "we want to test the error {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected method set_ReadPrivateWriteProperty to be Public because we want to test the error message, but it is Private."); - } - - [Fact] - public void When_subject_is_null_be_writable_with_accessmodifier_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().BeWritable(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected property to be Public *failure message*, but propertyInfo is ."); - } - - [Fact] - public void When_asserting_is_writable_with_an_invalid_enum_value_it_should_throw() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action act = () => - propertyInfo.Should().BeWritable((CSharpAccessModifier)int.MaxValue); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("accessModifier"); - } - - #endregion - - #region Return - - [Fact] - public void When_asserting_a_String_property_returns_a_String_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().Return(typeof(string)); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_String_property_returns_an_Int32_it_throw_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().Return(typeof(int), "we want to test the error {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected Type of property StringProperty to be System.Int32 because we want to test the error " + - "message, but it is System.String."); - } - - [Fact] - public void When_subject_is_null_return_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().Return(typeof(int), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type of property to be *.Int32 *failure message*, but propertyInfo is ."); - } - - [Fact] - public void When_asserting_property_type_is_null_it_should_throw() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action act = () => - propertyInfo.Should().Return(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("propertyType"); - } - - #endregion - - #region ReturnOfT - - [Fact] - public void When_asserting_a_String_property_returnsOfT_a_String_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().Return(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_String_property_returnsOfT_an_Int32_it_throw_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().Return("we want to test the error {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected Type of property StringProperty to be System.Int32 because we want to test the error " + - "message, but it is System.String."); - } - - #endregion - - #region NotReturn - - [Fact] - public void When_asserting_a_String_property_does_not_returns_an_Int32_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().NotReturn(typeof(int)); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_String_property_does_not_return_a_String_it_throw_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().NotReturn(typeof(string), "we want to test the error {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected Type of property StringProperty not to be*String*because we want to test the error " + - "message, but it is."); - } - - [Fact] - public void When_subject_is_null_not_return_should_fail() - { - // Arrange - PropertyInfo propertyInfo = null; - - // Act - Action act = () => - propertyInfo.Should().NotReturn(typeof(int), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type of property not to be *.Int32 *failure message*, but propertyInfo is ."); - } - - [Fact] - public void When_asserting_property_type_is_not_null_it_should_throw() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action act = () => - propertyInfo.Should().NotReturn(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("propertyType"); - } - - #endregion - - #region NotReturnOfT - - [Fact] - public void When_asserting_a_String_property_does_not_returnOfT_an_Int32_it_succeeds() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().NotReturn(); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_String_property_does_not_returnsOfT_a_String_it_throw_with_a_useful_message() - { - // Arrange - PropertyInfo propertyInfo = typeof(ClassWithProperties).GetRuntimeProperty("StringProperty"); - - // Act - Action action = () => propertyInfo.Should().NotReturn("we want to test the error {0}", "message"); - - // Assert - action.Should().Throw() - .WithMessage("Expected Type of property StringProperty not to be*String*because we want to test the error " + - "message, but it is."); - } - - #endregion - #region Internal classes used in unit tests private class ClassWithProperties diff --git a/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs index baef7fa9d3..5328a9f8e8 100644 --- a/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/PropertyInfoSelectorAssertionSpecs.cs @@ -7,293 +7,287 @@ namespace FluentAssertions.Specs.Types { public class PropertyInfoSelectorAssertionSpecs { - #region BeVirtual - - [Fact] - public void When_asserting_properties_are_virtual_and_they_are_it_should_succeed() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesVirtual)); - - // Act - Action act = () => - propertyInfoSelector.Should().BeVirtual(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_properties_are_virtual_but_non_virtual_properties_are_found_it_should_throw() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithNonVirtualPublicProperties)); - - // Act - Action act = () => - propertyInfoSelector.Should().BeVirtual(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_properties_are_virtual_but_non_virtual_properties_are_found_it_should_throw_with_descriptive_message() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithNonVirtualPublicProperties)); - - // Act - Action act = () => - propertyInfoSelector.Should().BeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected properties" + - " to be virtual because we want to test the error message," + - " but the following properties are not virtual:*" + - "String FluentAssertions*ClassWithNonVirtualPublicProperties.PublicNonVirtualProperty*" + - "String FluentAssertions*ClassWithNonVirtualPublicProperties.InternalNonVirtualProperty*" + - "String FluentAssertions*ClassWithNonVirtualPublicProperties.ProtectedNonVirtualProperty"); - } - - #endregion - - #region NotBeVirtual - - [Fact] - public void When_asserting_properties_are_not_virtual_and_they_are_not_it_should_succeed() + public class BeVirtual { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithNonVirtualPublicProperties)); - - // Act - Action act = () => - propertyInfoSelector.Should().NotBeVirtual(); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_properties_are_virtual_and_they_are_it_should_succeed() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesVirtual)); + + // Act + Action act = () => + propertyInfoSelector.Should().BeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_properties_are_virtual_but_non_virtual_properties_are_found_it_should_throw() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithNonVirtualPublicProperties)); + + // Act + Action act = () => + propertyInfoSelector.Should().BeVirtual(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_properties_are_virtual_but_non_virtual_properties_are_found_it_should_throw_with_descriptive_message() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithNonVirtualPublicProperties)); + + // Act + Action act = () => + propertyInfoSelector.Should().BeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected properties" + + " to be virtual because we want to test the error message," + + " but the following properties are not virtual:*" + + "String FluentAssertions*ClassWithNonVirtualPublicProperties.PublicNonVirtualProperty*" + + "String FluentAssertions*ClassWithNonVirtualPublicProperties.InternalNonVirtualProperty*" + + "String FluentAssertions*ClassWithNonVirtualPublicProperties.ProtectedNonVirtualProperty"); + } } - [Fact] - public void When_asserting_properties_are_not_virtual_but_virtual_properties_are_found_it_should_throw() + public class NotBeVirtual { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesVirtual)); - - // Act - Action act = () => - propertyInfoSelector.Should().NotBeVirtual(); - - // Assert - act.Should().Throw(); + [Fact] + public void When_asserting_properties_are_not_virtual_and_they_are_not_it_should_succeed() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithNonVirtualPublicProperties)); + + // Act + Action act = () => + propertyInfoSelector.Should().NotBeVirtual(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_properties_are_not_virtual_but_virtual_properties_are_found_it_should_throw() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesVirtual)); + + // Act + Action act = () => + propertyInfoSelector.Should().NotBeVirtual(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_properties_are_not_virtual_but_virtual_properties_are_found_it_should_throw_with_descriptive_message() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesVirtual)); + + // Act + Action act = () => + propertyInfoSelector.Should().NotBeVirtual("we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected properties" + + " not to be virtual because we want to test the error message," + + " but the following properties are virtual*" + + "*ClassWithAllPropertiesVirtual.PublicVirtualProperty" + + "*ClassWithAllPropertiesVirtual.InternalVirtualProperty" + + "*ClassWithAllPropertiesVirtual.ProtectedVirtualProperty"); + } } - [Fact] - public void - When_asserting_properties_are_not_virtual_but_virtual_properties_are_found_it_should_throw_with_descriptive_message() + public class BeDecoratedWith { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesVirtual)); - - // Act - Action act = () => - propertyInfoSelector.Should().NotBeVirtual("we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected properties" + - " not to be virtual because we want to test the error message," + - " but the following properties are virtual*" + - "*ClassWithAllPropertiesVirtual.PublicVirtualProperty" + - "*ClassWithAllPropertiesVirtual.InternalVirtualProperty" + - "*ClassWithAllPropertiesVirtual.ProtectedVirtualProperty"); + [Fact] + public void When_asserting_properties_are_decorated_with_attribute_and_they_are_it_should_succeed() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute)); + + // Act + Action act = () => + propertyInfoSelector.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_properties_are_decorated_with_attribute_and_they_are_not_it_should_throw() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute)) + .ThatArePublicOrInternal; + + // Act + Action act = () => + propertyInfoSelector.Should().BeDecoratedWith(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_properties_are_decorated_with_attribute_and_they_are_not_it_should_throw_with_descriptive_message() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute)); + + // Act + Action act = () => + propertyInfoSelector.Should() + .BeDecoratedWith("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected properties to be decorated with" + + " FluentAssertions*DummyPropertyAttribute because we want to test the error message," + + " but the following properties are not:*" + + "String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.PublicProperty*" + + "String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.InternalProperty*" + + "String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.ProtectedProperty"); + } } - #endregion - - #region BeDecoratedWith - - [Fact] - public void When_asserting_properties_are_decorated_with_attribute_and_they_are_it_should_succeed() + public class NotBeDecoratedWith { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute)); - - // Act - Action act = () => - propertyInfoSelector.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_properties_are_not_decorated_with_attribute_and_they_are_not_it_should_succeed() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute)); + + // Act + Action act = () => + propertyInfoSelector.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_properties_are_not_decorated_with_attribute_and_they_are_it_should_throw() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute)) + .ThatArePublicOrInternal; + + // Act + Action act = () => + propertyInfoSelector.Should().NotBeDecoratedWith(); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void + When_asserting_properties_are_not_decorated_with_attribute_and_they_are_it_should_throw_with_descriptive_message() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute)); + + // Act + Action act = () => + propertyInfoSelector.Should() + .NotBeDecoratedWith("because we want to test the error {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected all selected properties not to be decorated*" + + "DummyPropertyAttribute*" + + "because we want to test the error message*" + + "ClassWithAllPropertiesDecoratedWithDummyAttribute.PublicProperty*" + + "ClassWithAllPropertiesDecoratedWithDummyAttribute.InternalProperty*" + + "ClassWithAllPropertiesDecoratedWithDummyAttribute.ProtectedProperty*"); + } } - [Fact] - public void When_asserting_properties_are_decorated_with_attribute_and_they_are_not_it_should_throw() + public class BeWritable { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute)) - .ThatArePublicOrInternal; - - // Act - Action act = () => - propertyInfoSelector.Should().BeDecoratedWith(); - - // Assert - act.Should().Throw(); + [Fact] + public void When_a_read_only_property_is_expected_to_be_writable_it_should_throw_with_descriptive_message() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithReadOnlyProperties)); + + // Act + Action action = () => propertyInfoSelector.Should().BeWritable("because we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage( + "Expected all selected properties to have a setter because we want to test the error message, " + + "but the following properties do not:*" + + "String FluentAssertions*ClassWithReadOnlyProperties.ReadOnlyProperty*" + + "String FluentAssertions*ClassWithReadOnlyProperties.ReadOnlyProperty2"); + } + + [Fact] + public void When_writable_properties_are_expected_to_be_writable_it_should_not_throw() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithOnlyWritableProperties)); + + // Act + Action action = () => propertyInfoSelector.Should().BeWritable(); + + // Assert + action.Should().NotThrow(); + } } - [Fact] - public void - When_asserting_properties_are_decorated_with_attribute_and_they_are_not_it_should_throw_with_descriptive_message() + public class NotBeWritable { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute)); - - // Act - Action act = () => - propertyInfoSelector.Should() - .BeDecoratedWith("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected properties to be decorated with" + - " FluentAssertions*DummyPropertyAttribute because we want to test the error message," + - " but the following properties are not:*" + - "String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.PublicProperty*" + - "String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.InternalProperty*" + - "String FluentAssertions*ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute.ProtectedProperty"); + [Fact] + public void When_a_writable_property_is_expected_to_be_read_only_it_should_throw_with_descriptive_message() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithWritableProperties)); + + // Act + Action action = () => propertyInfoSelector.Should().NotBeWritable("because we want to test the error {0}", "message"); + + // Assert + action + .Should().Throw() + .WithMessage( + "Expected selected properties to not have a setter because we want to test the error message, " + + "but the following properties do:*" + + "String FluentAssertions*ClassWithWritableProperties.ReadWriteProperty*" + + "String FluentAssertions*ClassWithWritableProperties.ReadWriteProperty2"); + } + + [Fact] + public void When_read_only_properties_are_expected_to_not_be_writable_it_should_not_throw() + { + // Arrange + var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithOnlyReadOnlyProperties)); + + // Act + Action action = () => propertyInfoSelector.Should().NotBeWritable(); + + // Assert + action.Should().NotThrow(); + } } - - #endregion - - #region NotBeDecoratedWith - - [Fact] - public void When_asserting_properties_are_not_decorated_with_attribute_and_they_are_not_it_should_succeed() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute)); - - // Act - Action act = () => - propertyInfoSelector.Should().NotBeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_properties_are_not_decorated_with_attribute_and_they_are_it_should_throw() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute)) - .ThatArePublicOrInternal; - - // Act - Action act = () => - propertyInfoSelector.Should().NotBeDecoratedWith(); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void - When_asserting_properties_are_not_decorated_with_attribute_and_they_are_it_should_throw_with_descriptive_message() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithAllPropertiesDecoratedWithDummyAttribute)); - - // Act - Action act = () => - propertyInfoSelector.Should() - .NotBeDecoratedWith("because we want to test the error {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected all selected properties not to be decorated*" + - "DummyPropertyAttribute*" + - "because we want to test the error message*" + - "ClassWithAllPropertiesDecoratedWithDummyAttribute.PublicProperty*" + - "ClassWithAllPropertiesDecoratedWithDummyAttribute.InternalProperty*" + - "ClassWithAllPropertiesDecoratedWithDummyAttribute.ProtectedProperty*"); - } - - #endregion - - #region BeWritable - - [Fact] - public void When_a_read_only_property_is_expected_to_be_writable_it_should_throw_with_descriptive_message() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithReadOnlyProperties)); - - // Act - Action action = () => propertyInfoSelector.Should().BeWritable("because we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage( - "Expected all selected properties to have a setter because we want to test the error message, " + - "but the following properties do not:*" + - "String FluentAssertions*ClassWithReadOnlyProperties.ReadOnlyProperty*" + - "String FluentAssertions*ClassWithReadOnlyProperties.ReadOnlyProperty2"); - } - - [Fact] - public void When_writable_properties_are_expected_to_be_writable_it_should_not_throw() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithOnlyWritableProperties)); - - // Act - Action action = () => propertyInfoSelector.Should().BeWritable(); - - // Assert - action.Should().NotThrow(); - } - - #endregion - - #region NotBeWritable - - [Fact] - public void When_a_writable_property_is_expected_to_be_read_only_it_should_throw_with_descriptive_message() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithWritableProperties)); - - // Act - Action action = () => propertyInfoSelector.Should().NotBeWritable("because we want to test the error {0}", "message"); - - // Assert - action - .Should().Throw() - .WithMessage( - "Expected selected properties to not have a setter because we want to test the error message, " + - "but the following properties do:*" + - "String FluentAssertions*ClassWithWritableProperties.ReadWriteProperty*" + - "String FluentAssertions*ClassWithWritableProperties.ReadWriteProperty2"); - } - - [Fact] - public void When_read_only_properties_are_expected_to_not_be_writable_it_should_not_throw() - { - // Arrange - var propertyInfoSelector = new PropertyInfoSelector(typeof(ClassWithOnlyReadOnlyProperties)); - - // Act - Action action = () => propertyInfoSelector.Should().NotBeWritable(); - - // Assert - action.Should().NotThrow(); - } - - #endregion } #region Internal classes used in unit tests @@ -375,6 +369,5 @@ internal class ClassWithPropertiesThatAreNotDecoratedWithDummyAttribute protected string ProtectedProperty { get; set; } } - #endregion } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Be.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Be.cs index 29108f08ca..cc783493d7 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Be.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Be.cs @@ -11,215 +11,213 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region Be - - [Fact] - public void When_type_is_equal_to_the_same_type_it_succeeds() - { - // Arrange - Type type = typeof(ClassWithAttribute); - Type sameType = typeof(ClassWithAttribute); - - // Act - Action act = () => - type.Should().Be(sameType); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_equal_to_another_type_it_fails() - { - // Arrange - Type type = typeof(ClassWithAttribute); - Type differentType = typeof(ClassWithoutAttribute); - - // Act - Action act = () => - type.Should().Be(differentType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be *.ClassWithoutAttribute *failure message*, but found *.ClassWithAttribute."); - } - - [Fact] - public void When_asserting_equality_of_two_null_types_it_succeeds() - { - // Arrange - Type nullType = null; - Type someType = null; - - // Act - Action act = () => nullType.Should().Be(someType); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_equality_of_a_type_but_the_type_is_null_it_fails() + public class Be { - // Arrange - Type nullType = null; - Type someType = typeof(ClassWithAttribute); - - // Act - Action act = () => - nullType.Should().Be(someType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be *.ClassWithAttribute *failure message*, but found ."); - } - - [Fact] - public void When_asserting_equality_of_a_type_with_null_it_fails() - { - // Arrange - Type someType = typeof(ClassWithAttribute); - Type nullType = null; - - // Act - Action act = () => - someType.Should().Be(nullType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be *failure message*, but found *.ClassWithAttribute."); - } - - [Fact] - public void When_type_is_equal_to_same_type_from_different_assembly_it_fails_with_assembly_qualified_name() - { - // Arrange + [Fact] + public void When_type_is_equal_to_the_same_type_it_succeeds() + { + // Arrange + Type type = typeof(ClassWithAttribute); + Type sameType = typeof(ClassWithAttribute); + + // Act + Action act = () => + type.Should().Be(sameType); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_equal_to_another_type_it_fails() + { + // Arrange + Type type = typeof(ClassWithAttribute); + Type differentType = typeof(ClassWithoutAttribute); + + // Act + Action act = () => + type.Should().Be(differentType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be *.ClassWithoutAttribute *failure message*, but found *.ClassWithAttribute."); + } + + [Fact] + public void When_asserting_equality_of_two_null_types_it_succeeds() + { + // Arrange + Type nullType = null; + Type someType = null; + + // Act + Action act = () => nullType.Should().Be(someType); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_equality_of_a_type_but_the_type_is_null_it_fails() + { + // Arrange + Type nullType = null; + Type someType = typeof(ClassWithAttribute); + + // Act + Action act = () => + nullType.Should().Be(someType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be *.ClassWithAttribute *failure message*, but found ."); + } + + [Fact] + public void When_asserting_equality_of_a_type_with_null_it_fails() + { + // Arrange + Type someType = typeof(ClassWithAttribute); + Type nullType = null; + + // Act + Action act = () => + someType.Should().Be(nullType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be *failure message*, but found *.ClassWithAttribute."); + } + + [Fact] + public void When_type_is_equal_to_same_type_from_different_assembly_it_fails_with_assembly_qualified_name() + { + // Arrange #pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec - Type typeFromThisAssembly = typeof(AssemblyB.ClassC); + Type typeFromThisAssembly = typeof(AssemblyB.ClassC); - Type typeFromOtherAssembly = - new AssemblyA.ClassA().ReturnClassC().GetType(); + Type typeFromOtherAssembly = + new AssemblyA.ClassA().ReturnClassC().GetType(); #pragma warning restore 436 - // Act - Action act = () => - typeFromThisAssembly.Should().Be(typeFromOtherAssembly, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be [AssemblyB.ClassC, AssemblyB*] *failure message*, but found [AssemblyB.ClassC, FluentAssertions.Specs*]."); - } - - [Fact] - public void When_type_is_equal_to_the_same_type_using_generics_it_succeeds() - { - // Arrange - Type type = typeof(ClassWithAttribute); - - // Act - Action act = () => - type.Should().Be(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_equal_to_another_type_using_generics_it_fails() - { - // Arrange - Type type = typeof(ClassWithAttribute); - - // Act - Action act = () => - type.Should().Be("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be *.ClassWithoutAttribute *failure message*, but found *.ClassWithAttribute."); - } - - #endregion - - #region NotBe - - [Fact] - public void When_type_is_not_equal_to_the_another_type_it_succeeds() - { - // Arrange - Type type = typeof(ClassWithAttribute); - Type otherType = typeof(ClassWithoutAttribute); - - // Act - Action act = () => - type.Should().NotBe(otherType); - - // Assert - act.Should().NotThrow(); + // Act + Action act = () => + typeFromThisAssembly.Should().Be(typeFromOtherAssembly, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be [AssemblyB.ClassC, AssemblyB*] *failure message*, but found [AssemblyB.ClassC, FluentAssertions.Specs*]."); + } + + [Fact] + public void When_type_is_equal_to_the_same_type_using_generics_it_succeeds() + { + // Arrange + Type type = typeof(ClassWithAttribute); + + // Act + Action act = () => + type.Should().Be(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_equal_to_another_type_using_generics_it_fails() + { + // Arrange + Type type = typeof(ClassWithAttribute); + + // Act + Action act = () => + type.Should().Be("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be *.ClassWithoutAttribute *failure message*, but found *.ClassWithAttribute."); + } } - [Fact] - public void When_type_is_not_equal_to_the_same_type_it_fails() + public class NotBe { - // Arrange - Type type = typeof(ClassWithAttribute); - Type sameType = typeof(ClassWithAttribute); - - // Act - Action act = () => - type.Should().NotBe(sameType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type not to be [*.ClassWithAttribute*] *failure message*, but it is."); + [Fact] + public void When_type_is_not_equal_to_the_another_type_it_succeeds() + { + // Arrange + Type type = typeof(ClassWithAttribute); + Type otherType = typeof(ClassWithoutAttribute); + + // Act + Action act = () => + type.Should().NotBe(otherType); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_not_equal_to_the_same_type_it_fails() + { + // Arrange + Type type = typeof(ClassWithAttribute); + Type sameType = typeof(ClassWithAttribute); + + // Act + Action act = () => + type.Should().NotBe(sameType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type not to be [*.ClassWithAttribute*] *failure message*, but it is."); + } + + [Fact] + public void When_type_is_not_equal_to_the_same_null_type_it_fails() + { + // Arrange + Type type = null; + Type sameType = null; + + // Act + Action act = () => + type.Should().NotBe(sameType); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_type_is_not_equal_to_another_type_using_generics_it_succeeds() + { + // Arrange + Type type = typeof(ClassWithAttribute); + + // Act + Action act = () => + type.Should().NotBe(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails() + { + // Arrange + Type type = typeof(ClassWithAttribute); + + // Act + Action act = () => + type.Should().NotBe("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type not to be [*.ClassWithAttribute*] *failure message*, but it is."); + } } - - [Fact] - public void When_type_is_not_equal_to_the_same_null_type_it_fails() - { - // Arrange - Type type = null; - Type sameType = null; - - // Act - Action act = () => - type.Should().NotBe(sameType); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_type_is_not_equal_to_another_type_using_generics_it_succeeds() - { - // Arrange - Type type = typeof(ClassWithAttribute); - - // Act - Action act = () => - type.Should().NotBe(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails() - { - // Arrange - Type type = typeof(ClassWithAttribute); - - // Act - Action act = () => - type.Should().NotBe("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type not to be [*.ClassWithAttribute*] *failure message*, but it is."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAbstract.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAbstract.cs index d6f7721738..a8abc4e428 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAbstract.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAbstract.cs @@ -9,143 +9,141 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeAbstract - - [Fact] - public void When_type_is_abstract_it_succeeds() - { - // Arrange / Act / Assert - typeof(Abstract).Should().BeAbstract(); - } - - [Theory] - [InlineData(typeof(ClassWithoutMembers), "Expected type *.ClassWithoutMembers to be abstract.")] - [InlineData(typeof(Sealed), "Expected type *.Sealed to be abstract.")] - [InlineData(typeof(Static), "Expected type *.Static to be abstract.")] - public void When_type_is_not_abstract_it_fails(Type type, string exceptionMessage) + public class BeAbstract { - // Act - Action act = () => type.Should().BeAbstract(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); + [Fact] + public void When_type_is_abstract_it_succeeds() + { + // Arrange / Act / Assert + typeof(Abstract).Should().BeAbstract(); + } + + [Theory] + [InlineData(typeof(ClassWithoutMembers), "Expected type *.ClassWithoutMembers to be abstract.")] + [InlineData(typeof(Sealed), "Expected type *.Sealed to be abstract.")] + [InlineData(typeof(Static), "Expected type *.Static to be abstract.")] + public void When_type_is_not_abstract_it_fails(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().BeAbstract(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_type_is_not_abstract_it_fails_with_a_meaningful_message() + { + // Arrange + var type = typeof(ClassWithoutMembers); + + // Act + Action act = () => type.Should().BeAbstract("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.ClassWithoutMembers to be abstract *failure message*."); + } + + [Theory] + [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] + [InlineData(typeof(Struct), "*.Struct must be a class.")] + [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] + public void When_type_is_not_valid_for_BeAbstract_it_throws_exception(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().BeAbstract(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_subject_is_null_be_abstract_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().BeAbstract("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be abstract *failure message*, but type is ."); + } } - [Fact] - public void When_type_is_not_abstract_it_fails_with_a_meaningful_message() - { - // Arrange - var type = typeof(ClassWithoutMembers); - - // Act - Action act = () => type.Should().BeAbstract("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.ClassWithoutMembers to be abstract *failure message*."); - } - - [Theory] - [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] - [InlineData(typeof(Struct), "*.Struct must be a class.")] - [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] - public void When_type_is_not_valid_for_BeAbstract_it_throws_exception(Type type, string exceptionMessage) - { - // Act - Action act = () => type.Should().BeAbstract(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); - } - - [Fact] - public void When_subject_is_null_be_abstract_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().BeAbstract("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be abstract *failure message*, but type is ."); - } - - #endregion - - #region NotBeAbstract - - [Theory] - [InlineData(typeof(ClassWithoutMembers))] - [InlineData(typeof(Sealed))] - [InlineData(typeof(Static))] - public void When_type_is_not_abstract_it_succeeds(Type type) + public class NotBeAbstract { - // Arrange / Act / Assert - type.Should().NotBeAbstract(); + [Theory] + [InlineData(typeof(ClassWithoutMembers))] + [InlineData(typeof(Sealed))] + [InlineData(typeof(Static))] + public void When_type_is_not_abstract_it_succeeds(Type type) + { + // Arrange / Act / Assert + type.Should().NotBeAbstract(); + } + + [Fact] + public void When_type_is_abstract_it_fails() + { + // Arrange + var type = typeof(Abstract); + + // Act + Action act = () => type.Should().NotBeAbstract(); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.Abstract not to be abstract."); + } + + [Fact] + public void When_type_is_abstract_it_fails_with_a_meaningful_message() + { + // Arrange + var type = typeof(Abstract); + + // Act + Action act = () => type.Should().NotBeAbstract("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.Abstract not to be abstract *failure message*."); + } + + [Theory] + [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] + [InlineData(typeof(Struct), "*.Struct must be a class.")] + [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] + public void When_type_is_not_valid_for_NotBeAbstract_it_throws_exception(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().NotBeAbstract(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_subject_is_null_not_be_abstract_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotBeAbstract("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type not to be abstract *failure message*, but type is ."); + } } - - [Fact] - public void When_type_is_abstract_it_fails() - { - // Arrange - var type = typeof(Abstract); - - // Act - Action act = () => type.Should().NotBeAbstract(); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.Abstract not to be abstract."); - } - - [Fact] - public void When_type_is_abstract_it_fails_with_a_meaningful_message() - { - // Arrange - var type = typeof(Abstract); - - // Act - Action act = () => type.Should().NotBeAbstract("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.Abstract not to be abstract *failure message*."); - } - - [Theory] - [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] - [InlineData(typeof(Struct), "*.Struct must be a class.")] - [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] - public void When_type_is_not_valid_for_NotBeAbstract_it_throws_exception(Type type, string exceptionMessage) - { - // Act - Action act = () => type.Should().NotBeAbstract(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); - } - - [Fact] - public void When_subject_is_null_not_be_abstract_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotBeAbstract("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type not to be abstract *failure message*, but type is ."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAssignableTo.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAssignableTo.cs index 4910686e22..8226eda165 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAssignableTo.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAssignableTo.cs @@ -10,332 +10,330 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeAssignableTo - - [Fact] - public void When_its_own_type_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().BeAssignableTo(); - } - - [Fact] - public void When_its_base_type_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().BeAssignableTo(); - } - - [Fact] - public void When_implemented_interface_type_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().BeAssignableTo(); - } - - [Fact] - public void When_an_unrelated_type_it_fails() - { - // Arrange - Type someType = typeof(DummyImplementingClass); - Action act = () => someType.Should().BeAssignableTo("we want to test the failure {0}", "message"); - - // Act / Assert - act.Should().Throw() - .WithMessage( - "Expected someType *.DummyImplementingClass to be assignable to *.DateTime *failure message*" + - ", but it is not."); - } - - [Fact] - public void When_its_own_type_instance_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyImplementingClass)); - } - - [Fact] - public void When_its_base_type_instance_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyBaseClass)); - } - - [Fact] - public void When_an_implemented_interface_type_instance_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(IDisposable)); - } - - [Fact] - public void When_an_unrelated_type_instance_it_fails() - { - // Arrange - Type someType = typeof(DummyImplementingClass); - - // Act - Action act = () => - someType.Should().BeAssignableTo(typeof(DateTime), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("*.DummyImplementingClass to be assignable to *.DateTime *failure message*"); - } - - [Fact] - public void When_constructed_of_open_generic_it_succeeds() - { - // Arrange / Act / Assert - typeof(IDummyInterface).Should().BeAssignableTo(typeof(IDummyInterface<>)); - } - - [Fact] - public void When_implementation_of_open_generic_interface_it_succeeds() - { - // Arrange / Act / Assert - typeof(ClassWithGenericBaseType).Should().BeAssignableTo(typeof(IDummyInterface<>)); - } - - [Fact] - public void When_derived_of_open_generic_class_it_succeeds() - { - // Arrange / Act / Assert - typeof(ClassWithGenericBaseType).Should().BeAssignableTo(typeof(DummyBaseType<>)); - } - - [Fact] - public void When_unrelated_to_open_generic_interface_it_fails() - { - // Arrange - Type someType = typeof(IDummyInterface); - - // Act - Action act = () => - someType.Should().BeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected someType *.IDummyInterface to be assignable to *.IDummyInterface`1[T] *failure message*" + - ", but it is not."); - } - - [Fact] - public void When_unrelated_to_open_generic_type_it_fails() - { - // Arrange - Type someType = typeof(ClassWithAttribute); - Action act = () => - someType.Should().BeAssignableTo(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); - - // Act / Assert - act.Should().Throw() - .WithMessage("*.ClassWithAttribute to be assignable to *.DummyBaseType* *failure message*"); - } - - [Fact] - public void When_asserting_an_open_generic_class_is_assignable_to_itself_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyBaseType<>).Should().BeAssignableTo(typeof(DummyBaseType<>)); - } - - [Fact] - public void When_asserting_a_type_to_be_assignable_to_null_it_should_throw() - { - // Arrange - var type = typeof(DummyBaseType<>); - - // Act - Action act = () => - type.Should().BeAssignableTo(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("type"); - } - - #endregion - - #region NotBeAssignableTo - - [Fact] - public void When_its_own_type_and_asserting_not_assignable_it_fails() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeAssignableTo("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass to not be assignable to *.DummyImplementingClass *failure message*"); - } - - [Fact] - public void When_its_base_type_and_asserting_not_assignable_it_fails() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeAssignableTo("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass to not be assignable to *.DummyBaseClass *failure message*" + - ", but it is."); - } - - [Fact] - public void When_implemented_interface_type_and_asserting_not_assignable_it_fails() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeAssignableTo("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass to not be assignable to *.IDisposable *failure message*, but it is."); - } - - [Fact] - public void When_an_unrelated_type_and_asserting_not_assignable_it_succeeds() + public class BeAssignableTo { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().NotBeAssignableTo(); + [Fact] + public void When_its_own_type_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().BeAssignableTo(); + } + + [Fact] + public void When_its_base_type_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().BeAssignableTo(); + } + + [Fact] + public void When_implemented_interface_type_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().BeAssignableTo(); + } + + [Fact] + public void When_an_unrelated_type_it_fails() + { + // Arrange + Type someType = typeof(DummyImplementingClass); + Action act = () => someType.Should().BeAssignableTo("we want to test the failure {0}", "message"); + + // Act / Assert + act.Should().Throw() + .WithMessage( + "Expected someType *.DummyImplementingClass to be assignable to *.DateTime *failure message*" + + ", but it is not."); + } + + [Fact] + public void When_its_own_type_instance_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyImplementingClass)); + } + + [Fact] + public void When_its_base_type_instance_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyBaseClass)); + } + + [Fact] + public void When_an_implemented_interface_type_instance_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(IDisposable)); + } + + [Fact] + public void When_an_unrelated_type_instance_it_fails() + { + // Arrange + Type someType = typeof(DummyImplementingClass); + + // Act + Action act = () => + someType.Should().BeAssignableTo(typeof(DateTime), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("*.DummyImplementingClass to be assignable to *.DateTime *failure message*"); + } + + [Fact] + public void When_constructed_of_open_generic_it_succeeds() + { + // Arrange / Act / Assert + typeof(IDummyInterface).Should().BeAssignableTo(typeof(IDummyInterface<>)); + } + + [Fact] + public void When_implementation_of_open_generic_interface_it_succeeds() + { + // Arrange / Act / Assert + typeof(ClassWithGenericBaseType).Should().BeAssignableTo(typeof(IDummyInterface<>)); + } + + [Fact] + public void When_derived_of_open_generic_class_it_succeeds() + { + // Arrange / Act / Assert + typeof(ClassWithGenericBaseType).Should().BeAssignableTo(typeof(DummyBaseType<>)); + } + + [Fact] + public void When_unrelated_to_open_generic_interface_it_fails() + { + // Arrange + Type someType = typeof(IDummyInterface); + + // Act + Action act = () => + someType.Should().BeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected someType *.IDummyInterface to be assignable to *.IDummyInterface`1[T] *failure message*" + + ", but it is not."); + } + + [Fact] + public void When_unrelated_to_open_generic_type_it_fails() + { + // Arrange + Type someType = typeof(ClassWithAttribute); + Action act = () => + someType.Should().BeAssignableTo(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); + + // Act / Assert + act.Should().Throw() + .WithMessage("*.ClassWithAttribute to be assignable to *.DummyBaseType* *failure message*"); + } + + [Fact] + public void When_asserting_an_open_generic_class_is_assignable_to_itself_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyBaseType<>).Should().BeAssignableTo(typeof(DummyBaseType<>)); + } + + [Fact] + public void When_asserting_a_type_to_be_assignable_to_null_it_should_throw() + { + // Arrange + var type = typeof(DummyBaseType<>); + + // Act + Action act = () => + type.Should().BeAssignableTo(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("type"); + } } - [Fact] - public void When_its_own_type_instance_and_asserting_not_assignable_it_fails() + public class NotBeAssignableTo { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeAssignableTo(typeof(DummyImplementingClass), "we want to test the failure {0}", "message"); - - // Act / Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass to not be assignable to *.DummyImplementingClass *failure message*" + - ", but it is."); + [Fact] + public void When_its_own_type_and_asserting_not_assignable_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeAssignableTo("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass to not be assignable to *.DummyImplementingClass *failure message*"); + } + + [Fact] + public void When_its_base_type_and_asserting_not_assignable_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeAssignableTo("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass to not be assignable to *.DummyBaseClass *failure message*" + + ", but it is."); + } + + [Fact] + public void When_implemented_interface_type_and_asserting_not_assignable_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeAssignableTo("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass to not be assignable to *.IDisposable *failure message*, but it is."); + } + + [Fact] + public void When_an_unrelated_type_and_asserting_not_assignable_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().NotBeAssignableTo(); + } + + [Fact] + public void When_its_own_type_instance_and_asserting_not_assignable_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeAssignableTo(typeof(DummyImplementingClass), "we want to test the failure {0}", "message"); + + // Act / Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass to not be assignable to *.DummyImplementingClass *failure message*" + + ", but it is."); + } + + [Fact] + public void When_its_base_type_instance_and_asserting_not_assignable_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeAssignableTo(typeof(DummyBaseClass), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass to not be assignable to *.DummyBaseClass *failure message*" + + ", but it is."); + } + + [Fact] + public void When_an_implemented_interface_type_instance_and_asserting_not_assignable_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeAssignableTo(typeof(IDisposable), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass to not be assignable to *.IDisposable *failure message*, but it is."); + } + + [Fact] + public void When_an_unrelated_type_instance_and_asserting_not_assignable_it_succeeds() + { + // Arrange / Act / Assert + typeof(DummyImplementingClass).Should().NotBeAssignableTo(typeof(DateTime)); + } + + [Fact] + public void When_unrelated_to_open_generic_interface_and_asserting_not_assignable_it_succeeds() + { + // Arrange / Act / Assert + typeof(ClassWithAttribute).Should().NotBeAssignableTo(typeof(IDummyInterface<>)); + } + + [Fact] + public void When_unrelated_to_open_generic_class_and_asserting_not_assignable_it_succeeds() + { + // Arrange / Act / Assert + typeof(ClassWithAttribute).Should().NotBeAssignableTo(typeof(DummyBaseType<>)); + } + + [Fact] + public void When_implementation_of_open_generic_interface_and_asserting_not_assignable_it_fails() + { + // Arrange + Type type = typeof(ClassWithGenericBaseType); + + // Act + Action act = () => + type.Should().NotBeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithGenericBaseType to not be assignable to *.IDummyInterface`1[T] *failure message*" + + ", but it is."); + } + + [Fact] + public void When_derived_from_open_generic_class_and_asserting_not_assignable_it_fails() + { + // Arrange + Type type = typeof(ClassWithGenericBaseType); + + // Act + Action act = () => + type.Should().NotBeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithGenericBaseType to not be assignable to *.IDummyInterface`1[T] *failure message*" + + ", but it is."); + } + + [Fact] + public void When_asserting_a_type_not_to_be_assignable_to_null_it_should_throw() + { + // Arrange + var type = typeof(DummyBaseType<>); + + // Act + Action act = + () => type.Should().NotBeAssignableTo(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("type"); + } } - - [Fact] - public void When_its_base_type_instance_and_asserting_not_assignable_it_fails() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeAssignableTo(typeof(DummyBaseClass), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass to not be assignable to *.DummyBaseClass *failure message*" + - ", but it is."); - } - - [Fact] - public void When_an_implemented_interface_type_instance_and_asserting_not_assignable_it_fails() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeAssignableTo(typeof(IDisposable), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass to not be assignable to *.IDisposable *failure message*, but it is."); - } - - [Fact] - public void When_an_unrelated_type_instance_and_asserting_not_assignable_it_succeeds() - { - // Arrange / Act / Assert - typeof(DummyImplementingClass).Should().NotBeAssignableTo(typeof(DateTime)); - } - - [Fact] - public void When_unrelated_to_open_generic_interface_and_asserting_not_assignable_it_succeeds() - { - // Arrange / Act / Assert - typeof(ClassWithAttribute).Should().NotBeAssignableTo(typeof(IDummyInterface<>)); - } - - [Fact] - public void When_unrelated_to_open_generic_class_and_asserting_not_assignable_it_succeeds() - { - // Arrange / Act / Assert - typeof(ClassWithAttribute).Should().NotBeAssignableTo(typeof(DummyBaseType<>)); - } - - [Fact] - public void When_implementation_of_open_generic_interface_and_asserting_not_assignable_it_fails() - { - // Arrange - Type type = typeof(ClassWithGenericBaseType); - - // Act - Action act = () => - type.Should().NotBeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithGenericBaseType to not be assignable to *.IDummyInterface`1[T] *failure message*" + - ", but it is."); - } - - [Fact] - public void When_derived_from_open_generic_class_and_asserting_not_assignable_it_fails() - { - // Arrange - Type type = typeof(ClassWithGenericBaseType); - - // Act - Action act = () => - type.Should().NotBeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithGenericBaseType to not be assignable to *.IDummyInterface`1[T] *failure message*" + - ", but it is."); - } - - [Fact] - public void When_asserting_a_type_not_to_be_assignable_to_null_it_should_throw() - { - // Arrange - var type = typeof(DummyBaseType<>); - - // Act - Action act = - () => type.Should().NotBeAssignableTo(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("type"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWith.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWith.cs index 72a8bba418..43198f50f9 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWith.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWith.cs @@ -9,201 +9,199 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeDecoratedWith - - [Fact] - public void When_type_is_decorated_with_expected_attribute_it_succeeds() + public class BeDecoratedWith { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_decorated_with_expected_attribute_it_should_allow_chaining() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should().BeDecoratedWith() - .Which.IsEnabled.Should().BeTrue(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_not_decorated_with_expected_attribute_it_fails() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithoutAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should().BeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithoutAttribute to be decorated with *.DummyClassAttribute *failure message*" + - ", but the attribute was not found."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_BeDecoratedWith_it_should_throw() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should().BeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_succeeds() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .BeDecoratedWith(a => (a.Name == "Expected") && a.IsEnabled); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_should_allow_chaining() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .BeDecoratedWith(a => a.Name == "Expected") + [Fact] + public void When_type_is_decorated_with_expected_attribute_it_succeeds() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_decorated_with_expected_attribute_it_should_allow_chaining() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should().BeDecoratedWith() .Which.IsEnabled.Should().BeTrue(); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_not_decorated_with_expected_attribute_it_fails() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithoutAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should().BeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithoutAttribute to be decorated with *.DummyClassAttribute *failure message*" + + ", but the attribute was not found."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_BeDecoratedWith_it_should_throw() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should().BeDecoratedWith(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_succeeds() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .BeDecoratedWith(a => (a.Name == "Expected") && a.IsEnabled); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_should_allow_chaining() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .BeDecoratedWith(a => a.Name == "Expected") + .Which.IsEnabled.Should().BeTrue(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .BeDecoratedWith(a => (a.Name == "Unexpected") && a.IsEnabled); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithAttribute to be decorated with *.DummyClassAttribute that matches " + + "(a.Name == \"Unexpected\")*a.IsEnabled, but no matching attribute was found."); + } } - [Fact] - public void When_type_is_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails() + public class NotBeDecoratedWith { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .BeDecoratedWith(a => (a.Name == "Unexpected") && a.IsEnabled); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithAttribute to be decorated with *.DummyClassAttribute that matches " + - "(a.Name == \"Unexpected\")*a.IsEnabled, but no matching attribute was found."); + [Fact] + public void When_type_is_not_decorated_with_unexpected_attribute_it_succeeds() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithoutAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_decorated_with_unexpected_attribute_it_fails() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithAttribute.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithAttribute to not be decorated with *.DummyClassAttribute* *failure message*" + + ", but the attribute was found."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_NotBeDecoratedWith_it_should_throw() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => typeWithoutAttribute.Should() + .NotBeDecoratedWith(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_type_is_not_decorated_with_unexpected_attribute_with_the_expected_properties_it_succeeds() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should() + .NotBeDecoratedWith(a => (a.Name == "Unexpected") && a.IsEnabled); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_is_not_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should() + .NotBeDecoratedWith(a => (a.Name == "Expected") && a.IsEnabled); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithAttribute to not be decorated with *.DummyClassAttribute that matches " + + "(a.Name == \"Expected\") * a.IsEnabled, but a matching attribute was found."); + } } - - #endregion - - #region NotBeDecoratedWith - - [Fact] - public void When_type_is_not_decorated_with_unexpected_attribute_it_succeeds() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithoutAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should().NotBeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_decorated_with_unexpected_attribute_it_fails() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithAttribute.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithAttribute to not be decorated with *.DummyClassAttribute* *failure message*" + - ", but the attribute was found."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_NotBeDecoratedWith_it_should_throw() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => typeWithoutAttribute.Should() - .NotBeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_type_is_not_decorated_with_unexpected_attribute_with_the_expected_properties_it_succeeds() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should() - .NotBeDecoratedWith(a => (a.Name == "Unexpected") && a.IsEnabled); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_is_not_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should() - .NotBeDecoratedWith(a => (a.Name == "Expected") && a.IsEnabled); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithAttribute to not be decorated with *.DummyClassAttribute that matches " + - "(a.Name == \"Expected\") * a.IsEnabled, but a matching attribute was found."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWithOrInherit.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWithOrInherit.cs index 7aabde5638..8567ae0ce2 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWithOrInherit.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDecoratedWithOrInherit.cs @@ -9,202 +9,200 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeDecoratedWithOrInherit - - [Fact] - public void When_type_inherits_expected_attribute_it_succeeds() + public class BeDecoratedWithOrInherit { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithAttribute.Should().BeDecoratedWithOrInherit(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_inherits_expected_attribute_it_should_allow_chaining() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithAttribute.Should().BeDecoratedWithOrInherit() - .Which.IsEnabled.Should().BeTrue(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_does_not_inherit_expected_attribute_it_fails() - { - // Arrange - Type type = typeof(ClassWithoutAttribute); - - // Act - Action act = () => - type.Should().BeDecoratedWithOrInherit("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithoutAttribute to be decorated with or inherit *.DummyClassAttribute " + - "*failure message*, but the attribute was not found."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_BeDecoratedWithOrInherit_it_should_throw() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => typeWithAttribute.Should() - .BeDecoratedWithOrInherit(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_type_inherits_expected_attribute_with_the_expected_properties_it_succeeds() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .BeDecoratedWithOrInherit(a => (a.Name == "Expected") && a.IsEnabled); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_inherits_expected_attribute_with_the_expected_properties_it_should_allow_chaining() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .BeDecoratedWithOrInherit(a => a.Name == "Expected") + [Fact] + public void When_type_inherits_expected_attribute_it_succeeds() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithAttribute.Should().BeDecoratedWithOrInherit(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_inherits_expected_attribute_it_should_allow_chaining() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithAttribute.Should().BeDecoratedWithOrInherit() .Which.IsEnabled.Should().BeTrue(); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_does_not_inherit_expected_attribute_it_fails() + { + // Arrange + Type type = typeof(ClassWithoutAttribute); + + // Act + Action act = () => + type.Should().BeDecoratedWithOrInherit("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithoutAttribute to be decorated with or inherit *.DummyClassAttribute " + + "*failure message*, but the attribute was not found."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_BeDecoratedWithOrInherit_it_should_throw() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => typeWithAttribute.Should() + .BeDecoratedWithOrInherit(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_type_inherits_expected_attribute_with_the_expected_properties_it_succeeds() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .BeDecoratedWithOrInherit(a => (a.Name == "Expected") && a.IsEnabled); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_inherits_expected_attribute_with_the_expected_properties_it_should_allow_chaining() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .BeDecoratedWithOrInherit(a => a.Name == "Expected") + .Which.IsEnabled.Should().BeTrue(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_inherits_expected_attribute_that_has_an_unexpected_property_it_fails() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .BeDecoratedWithOrInherit(a => (a.Name == "Unexpected") && a.IsEnabled); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithInheritedAttribute to be decorated with or inherit *.DummyClassAttribute " + + "that matches (a.Name == \"Unexpected\")*a.IsEnabled, but no matching attribute was found."); + } } - [Fact] - public void When_type_inherits_expected_attribute_that_has_an_unexpected_property_it_fails() + public class NotBeDecoratedWithOrInherit { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .BeDecoratedWithOrInherit(a => (a.Name == "Unexpected") && a.IsEnabled); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithInheritedAttribute to be decorated with or inherit *.DummyClassAttribute " + - "that matches (a.Name == \"Unexpected\")*a.IsEnabled, but no matching attribute was found."); + [Fact] + public void When_type_does_not_inherit_unexpected_attribute_it_succeeds() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithoutAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should().NotBeDecoratedWithOrInherit(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_inherits_unexpected_attribute_it_fails() + { + // Arrange + Type typeWithAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithAttribute.Should() + .NotBeDecoratedWithOrInherit("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithInheritedAttribute to not be decorated with or inherit *.DummyClassAttribute " + + "*failure message* attribute was found."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_NotBeDecoratedWithOrInherit_it_should_throw() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => typeWithoutAttribute.Should() + .NotBeDecoratedWithOrInherit(isMatchingAttributePredicate: null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } + + [Fact] + public void When_type_does_not_inherit_unexpected_attribute_with_the_expected_properties_it_succeeds() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should() + .NotBeDecoratedWithOrInherit(a => (a.Name == "Unexpected") && a.IsEnabled); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_type_does_not_inherit_expected_attribute_that_has_an_unexpected_property_it_fails() + { + // Arrange + Type typeWithoutAttribute = typeof(ClassWithInheritedAttribute); + + // Act + Action act = () => + typeWithoutAttribute.Should() + .NotBeDecoratedWithOrInherit(a => (a.Name == "Expected") && a.IsEnabled); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithInheritedAttribute to not be decorated with or inherit *.DummyClassAttribute " + + "that matches (a.Name == \"Expected\") * a.IsEnabled, but a matching attribute was found."); + } } - - #endregion - - #region NotBeDecoratedWithOrInherit - - [Fact] - public void When_type_does_not_inherit_unexpected_attribute_it_succeeds() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithoutAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should().NotBeDecoratedWithOrInherit(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_inherits_unexpected_attribute_it_fails() - { - // Arrange - Type typeWithAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithAttribute.Should() - .NotBeDecoratedWithOrInherit("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithInheritedAttribute to not be decorated with or inherit *.DummyClassAttribute " + - "*failure message* attribute was found."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_NotBeDecoratedWithOrInherit_it_should_throw() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => typeWithoutAttribute.Should() - .NotBeDecoratedWithOrInherit(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_type_does_not_inherit_unexpected_attribute_with_the_expected_properties_it_succeeds() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should() - .NotBeDecoratedWithOrInherit(a => (a.Name == "Unexpected") && a.IsEnabled); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_type_does_not_inherit_expected_attribute_that_has_an_unexpected_property_it_fails() - { - // Arrange - Type typeWithoutAttribute = typeof(ClassWithInheritedAttribute); - - // Act - Action act = () => - typeWithoutAttribute.Should() - .NotBeDecoratedWithOrInherit(a => (a.Name == "Expected") && a.IsEnabled); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithInheritedAttribute to not be decorated with or inherit *.DummyClassAttribute " + - "that matches (a.Name == \"Expected\") * a.IsEnabled, but a matching attribute was found."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDerivedFrom.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDerivedFrom.cs index bbd3154e86..ab5866c623 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDerivedFrom.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeDerivedFrom.cs @@ -10,262 +10,258 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeDerivedFrom - - [Fact] - public void When_asserting_a_type_is_derived_from_its_base_class_it_succeeds() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().BeDerivedFrom(typeof(DummyBaseClass)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_is_derived_from_an_unrelated_class_it_fails() - { - // Arrange - var type = typeof(DummyBaseClass); - - // Act - Action act = () => - type.Should().BeDerivedFrom(typeof(ClassWithMembers), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyBaseClass to be derived from *.ClassWithMembers *failure message*, but it is not."); - } - - [Fact] - public void When_asserting_a_type_is_derived_from_an_interface_it_fails() - { - // Arrange - var type = typeof(ClassThatImplementsInterface); - - // Act - Action act = () => - type.Should().BeDerivedFrom(typeof(IDummyInterface), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassThatImplementsInterface to be derived from *.IDummyInterface *failure message*" + - ", but *.IDummyInterface is an interface."); - } - - [Fact] - public void When_asserting_a_type_is_derived_from_an_open_generic_it_succeeds() - { - // Arrange - var type = typeof(DummyBaseType); - - // Act - Action act = () => - type.Should().BeDerivedFrom(typeof(DummyBaseType<>)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_is_derived_from_an_open_generic_base_class_it_succeeds() - { - // Arrange - var type = typeof(ClassWithGenericBaseType); - - // Act - Action act = () => - type.Should().BeDerivedFrom(typeof(DummyBaseType<>)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_is_derived_from_an_unrelated_open_generic_class_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().BeDerivedFrom(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassWithMembers to be derived from *.DummyBaseType`* *failure message*, but it is not."); - } - - [Fact] - public void When_asserting_a_type_to_be_derived_from_null_it_should_throw() - { - // Arrange - var type = typeof(DummyBaseType<>); - - // Act - Action act = - () => type.Should().BeDerivedFrom(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("baseType"); - } - - #endregion - - #region BeDerivedFromOfT - - [Fact] - public void When_asserting_a_type_is_DerivedFromOfT_its_base_class_it_succeeds() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().BeDerivedFrom(); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region NotBeDerivedFrom - - [Fact] - public void When_asserting_a_type_is_not_derived_from_an_unrelated_class_it_succeeds() - { - // Arrange - var type = typeof(DummyBaseClass); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(typeof(ClassWithMembers)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_is_not_derived_from_its_base_class_it_fails() - { - // Arrange - var type = typeof(DummyImplementingClass); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(typeof(DummyBaseClass), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyImplementingClass not to be derived from *.DummyBaseClass *failure message*" + - ", but it is."); - } - - [Fact] - public void When_asserting_a_type_is_not_derived_from_an_interface_it_fails() + public class BeDerivedFrom { - // Arrange - var type = typeof(ClassThatImplementsInterface); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(typeof(IDummyInterface), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassThatImplementsInterface not to be derived from *.IDummyInterface *failure message*" + - ", but *.IDummyInterface is an interface."); + [Fact] + public void When_asserting_a_type_is_derived_from_its_base_class_it_succeeds() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().BeDerivedFrom(typeof(DummyBaseClass)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_is_derived_from_an_unrelated_class_it_fails() + { + // Arrange + var type = typeof(DummyBaseClass); + + // Act + Action act = () => + type.Should().BeDerivedFrom(typeof(ClassWithMembers), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyBaseClass to be derived from *.ClassWithMembers *failure message*, but it is not."); + } + + [Fact] + public void When_asserting_a_type_is_derived_from_an_interface_it_fails() + { + // Arrange + var type = typeof(ClassThatImplementsInterface); + + // Act + Action act = () => + type.Should().BeDerivedFrom(typeof(IDummyInterface), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassThatImplementsInterface to be derived from *.IDummyInterface *failure message*" + + ", but *.IDummyInterface is an interface."); + } + + [Fact] + public void When_asserting_a_type_is_derived_from_an_open_generic_it_succeeds() + { + // Arrange + var type = typeof(DummyBaseType); + + // Act + Action act = () => + type.Should().BeDerivedFrom(typeof(DummyBaseType<>)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_is_derived_from_an_open_generic_base_class_it_succeeds() + { + // Arrange + var type = typeof(ClassWithGenericBaseType); + + // Act + Action act = () => + type.Should().BeDerivedFrom(typeof(DummyBaseType<>)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_is_derived_from_an_unrelated_open_generic_class_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().BeDerivedFrom(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassWithMembers to be derived from *.DummyBaseType`* *failure message*, but it is not."); + } + + [Fact] + public void When_asserting_a_type_to_be_derived_from_null_it_should_throw() + { + // Arrange + var type = typeof(DummyBaseType<>); + + // Act + Action act = + () => type.Should().BeDerivedFrom(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("baseType"); + } } - [Fact] - public void When_asserting_a_type_is_not_derived_from_an_unrelated_open_generic_it_succeeds() + public class BeDerivedFromOfT { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(typeof(DummyBaseType<>)); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_is_DerivedFromOfT_its_base_class_it_succeeds() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().BeDerivedFrom(); + + // Assert + act.Should().NotThrow(); + } } - [Fact] - public void When_asserting_an_open_generic_type_is_not_derived_from_itself_it_succeeds() + public class NotBeDerivedFrom { - // Arrange - var type = typeof(DummyBaseType<>); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(typeof(DummyBaseType<>)); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_is_not_derived_from_an_unrelated_class_it_succeeds() + { + // Arrange + var type = typeof(DummyBaseClass); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(typeof(ClassWithMembers)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_is_not_derived_from_its_base_class_it_fails() + { + // Arrange + var type = typeof(DummyImplementingClass); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(typeof(DummyBaseClass), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyImplementingClass not to be derived from *.DummyBaseClass *failure message*" + + ", but it is."); + } + + [Fact] + public void When_asserting_a_type_is_not_derived_from_an_interface_it_fails() + { + // Arrange + var type = typeof(ClassThatImplementsInterface); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(typeof(IDummyInterface), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassThatImplementsInterface not to be derived from *.IDummyInterface *failure message*" + + ", but *.IDummyInterface is an interface."); + } + + [Fact] + public void When_asserting_a_type_is_not_derived_from_an_unrelated_open_generic_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(typeof(DummyBaseType<>)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_an_open_generic_type_is_not_derived_from_itself_it_succeeds() + { + // Arrange + var type = typeof(DummyBaseType<>); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(typeof(DummyBaseType<>)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_is_not_derived_from_its_open_generic_it_fails() + { + // Arrange + var type = typeof(DummyBaseType); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.DummyBaseType`1[*.ClassWithGenericBaseType] not to be derived from *.DummyBaseType`1[T] " + + "*failure message*, but it is."); + } + + [Fact] + public void When_asserting_a_type_not_to_be_derived_from_null_it_should_throw() + { + // Arrange + var type = typeof(DummyBaseType<>); + + // Act + Action act = + () => type.Should().NotBeDerivedFrom(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("baseType"); + } } - [Fact] - public void When_asserting_a_type_is_not_derived_from_its_open_generic_it_fails() + public class NotBeDerivedFromOfT { - // Arrange - var type = typeof(DummyBaseType); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.DummyBaseType`1[*.ClassWithGenericBaseType] not to be derived from *.DummyBaseType`1[T] " + - "*failure message*, but it is."); - } - - [Fact] - public void When_asserting_a_type_not_to_be_derived_from_null_it_should_throw() - { - // Arrange - var type = typeof(DummyBaseType<>); - - // Act - Action act = - () => type.Should().NotBeDerivedFrom(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("baseType"); + [Fact] + public void When_asserting_a_type_is_not_DerivedFromOfT_an_unrelated_class_it_succeeds() + { + // Arrange + var type = typeof(DummyBaseClass); + + // Act + Action act = () => + type.Should().NotBeDerivedFrom(); + + // Assert + act.Should().NotThrow(); + } } - - #endregion - - #region NotBeDerivedFromOfT - - [Fact] - public void When_asserting_a_type_is_not_DerivedFromOfT_an_unrelated_class_it_succeeds() - { - // Arrange - var type = typeof(DummyBaseClass); - - // Act - Action act = () => - type.Should().NotBeDerivedFrom(); - - // Assert - act.Should().NotThrow(); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeSealed.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeSealed.cs index d98592295f..6886e3bdd4 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeSealed.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeSealed.cs @@ -9,143 +9,141 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeSealed - - [Fact] - public void When_type_is_sealed_it_succeeds() - { - // Arrange / Act / Assert - typeof(Sealed).Should().BeSealed(); - } - - [Theory] - [InlineData(typeof(ClassWithoutMembers), "Expected type *.ClassWithoutMembers to be sealed.")] - [InlineData(typeof(Abstract), "Expected type *.Abstract to be sealed.")] - [InlineData(typeof(Static), "Expected type *.Static to be sealed.")] - public void When_type_is_not_sealed_it_fails(Type type, string exceptionMessage) + public class BeSealed { - // Act - Action act = () => type.Should().BeSealed(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); + [Fact] + public void When_type_is_sealed_it_succeeds() + { + // Arrange / Act / Assert + typeof(Sealed).Should().BeSealed(); + } + + [Theory] + [InlineData(typeof(ClassWithoutMembers), "Expected type *.ClassWithoutMembers to be sealed.")] + [InlineData(typeof(Abstract), "Expected type *.Abstract to be sealed.")] + [InlineData(typeof(Static), "Expected type *.Static to be sealed.")] + public void When_type_is_not_sealed_it_fails(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().BeSealed(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_type_is_not_sealed_it_fails_with_a_meaningful_message() + { + // Arrange + var type = typeof(ClassWithoutMembers); + + // Act + Action act = () => type.Should().BeSealed("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.ClassWithoutMembers to be sealed *failure message*."); + } + + [Theory] + [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] + [InlineData(typeof(Struct), "*.Struct must be a class.")] + [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] + public void When_type_is_not_valid_for_BeSealed_it_throws_exception(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().BeSealed(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_subject_is_null_be_sealed_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().BeSealed("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be sealed *failure message*, but type is ."); + } } - [Fact] - public void When_type_is_not_sealed_it_fails_with_a_meaningful_message() - { - // Arrange - var type = typeof(ClassWithoutMembers); - - // Act - Action act = () => type.Should().BeSealed("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.ClassWithoutMembers to be sealed *failure message*."); - } - - [Theory] - [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] - [InlineData(typeof(Struct), "*.Struct must be a class.")] - [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] - public void When_type_is_not_valid_for_BeSealed_it_throws_exception(Type type, string exceptionMessage) - { - // Act - Action act = () => type.Should().BeSealed(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); - } - - [Fact] - public void When_subject_is_null_be_sealed_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().BeSealed("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be sealed *failure message*, but type is ."); - } - - #endregion - - #region NotBeSealed - - [Theory] - [InlineData(typeof(ClassWithoutMembers))] - [InlineData(typeof(Abstract))] - [InlineData(typeof(Static))] - public void When_type_is_not_sealed_it_succeeds(Type type) + public class NotBeSealed { - // Arrange / Act / Assert - type.Should().NotBeSealed(); + [Theory] + [InlineData(typeof(ClassWithoutMembers))] + [InlineData(typeof(Abstract))] + [InlineData(typeof(Static))] + public void When_type_is_not_sealed_it_succeeds(Type type) + { + // Arrange / Act / Assert + type.Should().NotBeSealed(); + } + + [Fact] + public void When_type_is_sealed_it_fails() + { + // Arrange + var type = typeof(Sealed); + + // Act + Action act = () => type.Should().NotBeSealed(); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.Sealed not to be sealed."); + } + + [Fact] + public void When_type_is_sealed_it_fails_with_a_meaningful_message() + { + // Arrange + var type = typeof(Sealed); + + // Act + Action act = () => type.Should().NotBeSealed("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.Sealed not to be sealed *failure message*."); + } + + [Theory] + [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] + [InlineData(typeof(Struct), "*.Struct must be a class.")] + [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] + public void When_type_is_not_valid_for_NotBeSealed_it_throws_exception(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().NotBeSealed(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_subject_is_null_not_be_sealed_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotBeSealed("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type not to be sealed *failure message*, but type is ."); + } } - - [Fact] - public void When_type_is_sealed_it_fails() - { - // Arrange - var type = typeof(Sealed); - - // Act - Action act = () => type.Should().NotBeSealed(); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.Sealed not to be sealed."); - } - - [Fact] - public void When_type_is_sealed_it_fails_with_a_meaningful_message() - { - // Arrange - var type = typeof(Sealed); - - // Act - Action act = () => type.Should().NotBeSealed("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.Sealed not to be sealed *failure message*."); - } - - [Theory] - [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] - [InlineData(typeof(Struct), "*.Struct must be a class.")] - [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] - public void When_type_is_not_valid_for_NotBeSealed_it_throws_exception(Type type, string exceptionMessage) - { - // Act - Action act = () => type.Should().NotBeSealed(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); - } - - [Fact] - public void When_subject_is_null_not_be_sealed_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotBeSealed("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type not to be sealed *failure message*, but type is ."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeStatic.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeStatic.cs index f3f0a6ca7a..273618f1a5 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeStatic.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeStatic.cs @@ -9,143 +9,141 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region BeStatic - - [Fact] - public void When_type_is_static_it_succeeds() - { - // Arrange / Act / Assert - typeof(Static).Should().BeStatic(); - } - - [Theory] - [InlineData(typeof(ClassWithoutMembers), "Expected type *.ClassWithoutMembers to be static.")] - [InlineData(typeof(Sealed), "Expected type *.Sealed to be static.")] - [InlineData(typeof(Abstract), "Expected type *.Abstract to be static.")] - public void When_type_is_not_static_it_fails(Type type, string exceptionMessage) + public class BeStatic { - // Act - Action act = () => type.Should().BeStatic(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); + [Fact] + public void When_type_is_static_it_succeeds() + { + // Arrange / Act / Assert + typeof(Static).Should().BeStatic(); + } + + [Theory] + [InlineData(typeof(ClassWithoutMembers), "Expected type *.ClassWithoutMembers to be static.")] + [InlineData(typeof(Sealed), "Expected type *.Sealed to be static.")] + [InlineData(typeof(Abstract), "Expected type *.Abstract to be static.")] + public void When_type_is_not_static_it_fails(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().BeStatic(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_type_is_not_static_it_fails_with_a_meaningful_message() + { + // Arrange + var type = typeof(ClassWithoutMembers); + + // Act + Action act = () => type.Should().BeStatic("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.ClassWithoutMembers to be static *failure message*."); + } + + [Theory] + [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] + [InlineData(typeof(Struct), "*.Struct must be a class.")] + [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] + public void When_type_is_not_valid_for_BeStatic_it_throws_exception(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().BeStatic(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_subject_is_null_be_static_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().BeStatic("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be static *failure message*, but type is ."); + } } - [Fact] - public void When_type_is_not_static_it_fails_with_a_meaningful_message() - { - // Arrange - var type = typeof(ClassWithoutMembers); - - // Act - Action act = () => type.Should().BeStatic("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.ClassWithoutMembers to be static *failure message*."); - } - - [Theory] - [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] - [InlineData(typeof(Struct), "*.Struct must be a class.")] - [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] - public void When_type_is_not_valid_for_BeStatic_it_throws_exception(Type type, string exceptionMessage) - { - // Act - Action act = () => type.Should().BeStatic(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); - } - - [Fact] - public void When_subject_is_null_be_static_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().BeStatic("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be static *failure message*, but type is ."); - } - - #endregion - - #region NotBeStatic - - [Theory] - [InlineData(typeof(ClassWithoutMembers))] - [InlineData(typeof(Sealed))] - [InlineData(typeof(Abstract))] - public void When_type_is_not_static_it_succeeds(Type type) + public class NotBeStatic { - // Arrange / Act / Assert - type.Should().NotBeStatic(); + [Theory] + [InlineData(typeof(ClassWithoutMembers))] + [InlineData(typeof(Sealed))] + [InlineData(typeof(Abstract))] + public void When_type_is_not_static_it_succeeds(Type type) + { + // Arrange / Act / Assert + type.Should().NotBeStatic(); + } + + [Fact] + public void When_type_is_static_it_fails() + { + // Arrange + var type = typeof(Static); + + // Act + Action act = () => type.Should().NotBeStatic(); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.Static not to be static."); + } + + [Fact] + public void When_type_is_static_it_fails_with_a_meaningful_message() + { + // Arrange + var type = typeof(Static); + + // Act + Action act = () => type.Should().NotBeStatic("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type *.Static not to be static *failure message*."); + } + + [Theory] + [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] + [InlineData(typeof(Struct), "*.Struct must be a class.")] + [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] + public void When_type_is_not_valid_for_NotBeStatic_it_throws_exception(Type type, string exceptionMessage) + { + // Act + Action act = () => type.Should().NotBeStatic(); + + // Assert + act.Should().Throw() + .WithMessage(exceptionMessage); + } + + [Fact] + public void When_subject_is_null_not_be_static_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotBeStatic("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type not to be static *failure message*, but type is ."); + } } - - [Fact] - public void When_type_is_static_it_fails() - { - // Arrange - var type = typeof(Static); - - // Act - Action act = () => type.Should().NotBeStatic(); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.Static not to be static."); - } - - [Fact] - public void When_type_is_static_it_fails_with_a_meaningful_message() - { - // Arrange - var type = typeof(Static); - - // Act - Action act = () => type.Should().NotBeStatic("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type *.Static not to be static *failure message*."); - } - - [Theory] - [InlineData(typeof(IDummyInterface), "*.IDummyInterface must be a class.")] - [InlineData(typeof(Struct), "*.Struct must be a class.")] - [InlineData(typeof(ExampleDelegate), "*.ExampleDelegate must be a class.")] - public void When_type_is_not_valid_for_NotBeStatic_it_throws_exception(Type type, string exceptionMessage) - { - // Act - Action act = () => type.Should().NotBeStatic(); - - // Assert - act.Should().Throw() - .WithMessage(exceptionMessage); - } - - [Fact] - public void When_subject_is_null_not_be_static_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotBeStatic("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type not to be static *failure message*, but type is ."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveAccessModifier.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveAccessModifier.cs index 8c351a6e76..126f8edf91 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveAccessModifier.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveAccessModifier.cs @@ -11,327 +11,327 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - public class NotHaveAccessModifier + public class HaveAccessModifier { - public class HaveAccessModifier - { - [Fact] - public void When_asserting_a_public_type_is_public_it_succeeds() - { - // Arrange - Type type = typeof(IPublicInterface); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_public_member_is_internal_it_throws() - { - // Arrange - Type type = typeof(IPublicInterface); - - // Act - Action act = () => - type - .Should() - .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type IPublicInterface to be Internal *failure message*, but it is Public."); - } - - [Fact] - public void An_internal_class_has_an_internal_access_modifier() - { - // Arrange - Type type = typeof(InternalClass); - - // Act / Assert - type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); - } + [Fact] + public void When_asserting_a_public_type_is_public_it_succeeds() + { + // Arrange + Type type = typeof(IPublicInterface); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Public); - [Fact] - public void An_internal_interface_has_an_internal_access_modifier() - { - // Arrange - Type type = typeof(IInternalInterface); + // Assert + act.Should().NotThrow(); + } - // Act / Assert - type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); - } + [Fact] + public void When_asserting_a_public_member_is_internal_it_throws() + { + // Arrange + Type type = typeof(IPublicInterface); - [Fact] - public void An_internal_struct_has_an_internal_access_modifier() - { - // Arrange - Type type = typeof(InternalStruct); + // Act + Action act = () => + type + .Should() + .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the failure {0}", "message"); - // Act / Assert - type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); - } + // Assert + act.Should().Throw() + .WithMessage("Expected type IPublicInterface to be Internal *failure message*, but it is Public."); + } + + [Fact] + public void An_internal_class_has_an_internal_access_modifier() + { + // Arrange + Type type = typeof(InternalClass); + + // Act / Assert + type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); + } + + [Fact] + public void An_internal_interface_has_an_internal_access_modifier() + { + // Arrange + Type type = typeof(IInternalInterface); + + // Act / Assert + type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); + } + + [Fact] + public void An_internal_struct_has_an_internal_access_modifier() + { + // Arrange + Type type = typeof(InternalStruct); + + // Act / Assert + type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); + } + + [Fact] + public void An_internal_enum_has_an_internal_access_modifier() + { + // Arrange + Type type = typeof(InternalEnum); + + // Act / Assert + type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); + } + + [Fact] + public void An_internal_class_does_not_have_a_protected_internal_modifier() + { + // Arrange + Type type = typeof(InternalClass); + + // Act + Action act = () => + type.Should().HaveAccessModifier( + CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type InternalClass to be ProtectedInternal *failure message*, but it is Internal."); + } + + [Fact] + public void An_internal_interface_does_not_have_a_protected_internal_modifier() + { + // Arrange + Type type = typeof(IInternalInterface); + + // Act + Action act = () => + type.Should().HaveAccessModifier( + CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type IInternalInterface to be ProtectedInternal *failure message*, but it is Internal."); + } + + [Fact] + public void An_internal_struct_does_not_have_a_protected_internal_modifier() + { + // Arrange + Type type = typeof(InternalStruct); + + // Act + Action act = () => + type.Should().HaveAccessModifier( + CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type InternalStruct to be ProtectedInternal *failure message*, but it is Internal."); + } + + [Fact] + public void An_internal_enum_does_not_have_a_protected_internal_modifier() + { + // Arrange + Type type = typeof(InternalEnum); + + // Act + Action act = () => + type.Should().HaveAccessModifier( + CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type InternalEnum to be ProtectedInternal *failure message*, but it is Internal."); + } + + [Fact] + public void When_asserting_a_nested_private_type_is_private_it_succeeds() + { + // Arrange + Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Private); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_nested_private_type_is_protected_it_throws() + { + // Arrange + Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the failure {0}", + "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type PrivateClass to be Protected *failure message*, but it is Private."); + } - [Fact] - public void An_internal_enum_has_an_internal_access_modifier() - { - // Arrange - Type type = typeof(InternalEnum); + [Fact] + public void When_asserting_a_nested_protected_type_is_protected_it_succeeds() + { + // Arrange + Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Protected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_nested_protected_type_is_public_it_throws() + { + // Arrange + Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance); - // Act / Assert + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Public); + + // Assert + act.Should().Throw() + .WithMessage("Expected type ProtectedEnum to be Public, but it is Protected."); + } + + [Fact] + public void When_asserting_a_nested_public_type_is_public_it_succeeds() + { + // Arrange + Type type = typeof(Nested.IPublicInterface); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_nested_public_member_is_internal_it_throws() + { + // Arrange + Type type = typeof(Nested.IPublicInterface); + + // Act + Action act = () => + type + .Should() + .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type IPublicInterface to be Internal *failure message*, but it is Public."); + } + + [Fact] + public void When_asserting_a_nested_internal_type_is_internal_it_succeeds() + { + // Arrange + Type type = typeof(Nested.InternalClass); + + // Act + Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); - } - - [Fact] - public void An_internal_class_does_not_have_a_protected_internal_modifier() - { - // Arrange - Type type = typeof(InternalClass); - - // Act - Action act = () => - type.Should().HaveAccessModifier( - CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type InternalClass to be ProtectedInternal *failure message*, but it is Internal."); - } - - [Fact] - public void An_internal_interface_does_not_have_a_protected_internal_modifier() - { - // Arrange - Type type = typeof(IInternalInterface); - - // Act - Action act = () => - type.Should().HaveAccessModifier( - CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type IInternalInterface to be ProtectedInternal *failure message*, but it is Internal."); - } - - [Fact] - public void An_internal_struct_does_not_have_a_protected_internal_modifier() - { - // Arrange - Type type = typeof(InternalStruct); - - // Act - Action act = () => - type.Should().HaveAccessModifier( - CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type InternalStruct to be ProtectedInternal *failure message*, but it is Internal."); - } - - [Fact] - public void An_internal_enum_does_not_have_a_protected_internal_modifier() - { - // Arrange - Type type = typeof(InternalEnum); - - // Act - Action act = () => - type.Should().HaveAccessModifier( - CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type InternalEnum to be ProtectedInternal *failure message*, but it is Internal."); - } - - [Fact] - public void When_asserting_a_nested_private_type_is_private_it_succeeds() - { - // Arrange - Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Private); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_nested_private_type_is_protected_it_throws() - { - // Arrange - Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the failure {0}", - "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type PrivateClass to be Protected *failure message*, but it is Private."); - } - - [Fact] - public void When_asserting_a_nested_protected_type_is_protected_it_succeeds() - { - // Arrange - Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Protected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_nested_protected_type_is_public_it_throws() - { - // Arrange - Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().Throw() - .WithMessage("Expected type ProtectedEnum to be Public, but it is Protected."); - } - - [Fact] - public void When_asserting_a_nested_public_type_is_public_it_succeeds() - { - // Arrange - Type type = typeof(Nested.IPublicInterface); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_nested_public_member_is_internal_it_throws() - { - // Arrange - Type type = typeof(Nested.IPublicInterface); - - // Act - Action act = () => - type - .Should() - .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type IPublicInterface to be Internal *failure message*, but it is Public."); - } - - [Fact] - public void When_asserting_a_nested_internal_type_is_internal_it_succeeds() - { - // Arrange - Type type = typeof(Nested.InternalClass); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_nested_internal_type_is_protected_internal_it_throws() - { - // Arrange - Type type = typeof(Nested.InternalClass); - - // Act - Action act = () => - type.Should().HaveAccessModifier( - CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type InternalClass to be ProtectedInternal *failure message*, but it is Internal."); - } - - [Fact] - public void When_asserting_a_nested_protected_internal_member_is_protected_internal_it_succeeds() - { - // Arrange - Type type = typeof(Nested.IProtectedInternalInterface); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_nested_protected_internal_member_is_private_it_throws() - { - // Arrange - Type type = typeof(Nested.IProtectedInternalInterface); - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type IProtectedInternalInterface to be Private *failure message*, but it is ProtectedInternal."); - } - - [Fact] - public void When_subject_is_null_have_access_modifier_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveAccessModifier(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type to be Public *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_access_modifier_with_an_invalid_enum_value_it_should_throw() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveAccessModifier((CSharpAccessModifier)int.MaxValue); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("accessModifier"); - } + + // Assert + act.Should().NotThrow(); } + [Fact] + public void When_asserting_a_nested_internal_type_is_protected_internal_it_throws() + { + // Arrange + Type type = typeof(Nested.InternalClass); + + // Act + Action act = () => + type.Should().HaveAccessModifier( + CSharpAccessModifier.ProtectedInternal, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type InternalClass to be ProtectedInternal *failure message*, but it is Internal."); + } + + [Fact] + public void When_asserting_a_nested_protected_internal_member_is_protected_internal_it_succeeds() + { + // Arrange + Type type = typeof(Nested.IProtectedInternalInterface); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_nested_protected_internal_member_is_private_it_throws() + { + // Arrange + Type type = typeof(Nested.IProtectedInternalInterface); + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type IProtectedInternalInterface to be Private *failure message*, but it is ProtectedInternal."); + } + + [Fact] + public void When_subject_is_null_have_access_modifier_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveAccessModifier(CSharpAccessModifier.Public, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type to be Public *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_access_modifier_with_an_invalid_enum_value_it_should_throw() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveAccessModifier((CSharpAccessModifier)int.MaxValue); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("accessModifier"); + } + } + + public class NotHaveAccessModifier + { [Fact] public void When_asserting_a_public_type_is_not_private_it_succeeds() { diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveConstructor.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveConstructor.cs index 2c422ebf31..a9f865e790 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveConstructor.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveConstructor.cs @@ -10,137 +10,135 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveConstructor - - [Fact] - public void When_asserting_a_type_has_a_constructor_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .HaveConstructor(new Type[] { typeof(string) }) - .Which.Should() - .HaveAccessModifier(CSharpAccessModifier.Private); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_a_constructor_which_it_does_not_it_fails() - { - // Arrange - var type = typeof(ClassWithNoMembers); - - // Act - Action act = () => - type.Should().HaveConstructor(new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected constructor *ClassWithNoMembers(System.Int32, System.Type) to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_constructor_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveConstructor(new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected constructor type(System.String) to exist *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_a_constructor_of_null_it_should_throw() - { - // Arrange - Type type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveConstructor(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - #endregion - - #region NotHaveConstructor - - [Fact] - public void When_asserting_a_type_does_not_have_a_constructor_which_it_does_not_it_succeeds() + public class HaveConstructor { - // Arrange - var type = typeof(ClassWithNoMembers); - - // Act - Action act = () => - type.Should() - .NotHaveConstructor(new Type[] { typeof(string) }); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_has_a_constructor_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveConstructor(new Type[] { typeof(string) }) + .Which.Should() + .HaveAccessModifier(CSharpAccessModifier.Private); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_constructor_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(ClassWithNoMembers); + + // Act + Action act = () => + type.Should().HaveConstructor(new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected constructor *ClassWithNoMembers(System.Int32, System.Type) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_constructor_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveConstructor(new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected constructor type(System.String) to exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_a_constructor_of_null_it_should_throw() + { + // Arrange + Type type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveConstructor(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } } - [Fact] - public void When_asserting_a_type_does_not_have_a_constructor_which_it_does_it_fails() + public class NotHaveConstructor { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveConstructor(new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected constructor *.ClassWithMembers(System.String) not to exist *failure message*, but it does."); + [Fact] + public void When_asserting_a_type_does_not_have_a_constructor_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(ClassWithNoMembers); + + // Act + Action act = () => + type.Should() + .NotHaveConstructor(new Type[] { typeof(string) }); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_constructor_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveConstructor(new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected constructor *.ClassWithMembers(System.String) not to exist *failure message*, but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_constructor_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveConstructor(new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected constructor type(System.String) not to exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_constructor_of_null_it_should_throw() + { + // Arrange + Type type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveConstructor(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } } - - [Fact] - public void When_subject_is_null_not_have_constructor_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveConstructor(new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected constructor type(System.String) not to exist *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_constructor_of_null_it_should_throw() - { - // Arrange - Type type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveConstructor(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveDefaultConstructor.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveDefaultConstructor.cs index 7f4bd5b371..4b59e38483 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveDefaultConstructor.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveDefaultConstructor.cs @@ -10,176 +10,174 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveDefaultConstructor - - [Fact] - public void When_asserting_a_type_has_a_default_constructor_which_it_does_it_succeeds() + public class HaveDefaultConstructor { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => + [Fact] + public void When_asserting_a_type_has_a_default_constructor_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveDefaultConstructor() + .Which.Should() + .HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(ClassWithNoMembers); + + // Act + Action act = () => + type.Should() + .HaveDefaultConstructor() + .Which.Should() + .HaveAccessModifier(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_and_a_cctor_it_succeeds() + { + // Arrange + var type = typeof(ClassWithCctor); + + // Act type.Should() - .HaveDefaultConstructor() - .Which.Should() - .HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); - - // Assert - act.Should().NotThrow(); + .HaveDefaultConstructor() + .Which.Should() + .HaveAccessModifier(CSharpAccessModifier.Public); + Action act = () => + type.Should() + .HaveDefaultConstructor() + .Which.Should() + .HaveAccessModifier(CSharpAccessModifier.Public); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_and_a_cctor_it_fails() + { + // Arrange + var type = typeof(ClassWithCctorAndNonDefaultConstructor); + + // Act + Action act = () => + type.Should().HaveDefaultConstructor("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected constructor *ClassWithCctorAndNonDefaultConstructor() to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_default_constructor_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveDefaultConstructor("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected constructor type() to exist *failure message*, but type is ."); + } } - [Fact] - public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_it_succeeds() + public class NotHaveDefaultConstructor { - // Arrange - var type = typeof(ClassWithNoMembers); - - // Act - Action act = () => - type.Should() - .HaveDefaultConstructor() - .Which.Should() - .HaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(ClassWithCctorAndNonDefaultConstructor); + + // Act + Action act = () => + type.Should() + .NotHaveDefaultConstructor(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .NotHaveDefaultConstructor("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected constructor *.ClassWithMembers() not to exist *failure message*, but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_and_a_cctor_it_fails() + { + // Arrange + var type = typeof(ClassWithCctor); + + // Act + Action act = () => + type.Should().NotHaveDefaultConstructor("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected constructor *ClassWithCctor*() not to exist *failure message*, but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_not_and_a_cctor_it_succeeds() + { + // Arrange + var type = typeof(ClassWithCctorAndNonDefaultConstructor); + + // Act + Action act = () => + type.Should().NotHaveDefaultConstructor(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_subject_is_null_not_have_default_constructor_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveDefaultConstructor("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected constructor type() not to exist *failure message*, but type is ."); + } } - [Fact] - public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_and_a_cctor_it_succeeds() - { - // Arrange - var type = typeof(ClassWithCctor); - - // Act - type.Should() - .HaveDefaultConstructor() - .Which.Should() - .HaveAccessModifier(CSharpAccessModifier.Public); - Action act = () => - type.Should() - .HaveDefaultConstructor() - .Which.Should() - .HaveAccessModifier(CSharpAccessModifier.Public); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_and_a_cctor_it_fails() - { - // Arrange - var type = typeof(ClassWithCctorAndNonDefaultConstructor); - - // Act - Action act = () => - type.Should().HaveDefaultConstructor("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected constructor *ClassWithCctorAndNonDefaultConstructor() to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_default_constructor_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveDefaultConstructor("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected constructor type() to exist *failure message*, but type is ."); - } - - #endregion - - #region NotHaveDefaultConstructor - - [Fact] - public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(ClassWithCctorAndNonDefaultConstructor); - - // Act - Action act = () => - type.Should() - .NotHaveDefaultConstructor(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .NotHaveDefaultConstructor("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected constructor *.ClassWithMembers() not to exist *failure message*, but it does."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_and_a_cctor_it_fails() - { - // Arrange - var type = typeof(ClassWithCctor); - - // Act - Action act = () => - type.Should().NotHaveDefaultConstructor("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected constructor *ClassWithCctor*() not to exist *failure message*, but it does."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_default_constructor_which_it_does_not_and_a_cctor_it_succeeds() - { - // Arrange - var type = typeof(ClassWithCctorAndNonDefaultConstructor); - - // Act - Action act = () => - type.Should().NotHaveDefaultConstructor(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_subject_is_null_not_have_default_constructor_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveDefaultConstructor("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected constructor type() not to exist *failure message*, but type is ."); - } - - #endregion - internal class ClassWithNoMembers { } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitConversionOperator.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitConversionOperator.cs index 827a5c1801..84ed2ef5d1 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitConversionOperator.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitConversionOperator.cs @@ -9,278 +9,274 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveExplicitConversionOperator - - [Fact] - public void When_asserting_a_type_has_an_explicit_conversion_operator_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(byte); - - // Act - Action act = () => - type.Should() - .HaveExplicitConversionOperator(sourceType, targetType) - .Which.Should() - .NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_conversion_operator_which_it_does_not_it_fails_with_a_useful_message() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(string); - - // Act - Action act = () => - type.Should().HaveExplicitConversionOperator( - sourceType, targetType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_explicit_conversion_operator_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveExplicitConversionOperator( - typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_conversion_operator_from_null_it_should_throw() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().HaveExplicitConversionOperator(null, typeof(string)); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("sourceType"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_conversion_operator_to_null_it_should_throw() + public class HaveExplicitConversionOperator { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().HaveExplicitConversionOperator(typeof(TypeWithConversionOperators), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("targetType"); + [Fact] + public void When_asserting_a_type_has_an_explicit_conversion_operator_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(byte); + + // Act + Action act = () => + type.Should() + .HaveExplicitConversionOperator(sourceType, targetType) + .Which.Should() + .NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_conversion_operator_which_it_does_not_it_fails_with_a_useful_message() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(string); + + // Act + Action act = () => + type.Should().HaveExplicitConversionOperator( + sourceType, targetType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_explicit_conversion_operator_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveExplicitConversionOperator( + typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_conversion_operator_from_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().HaveExplicitConversionOperator(null, typeof(string)); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("sourceType"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_conversion_operator_to_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().HaveExplicitConversionOperator(typeof(TypeWithConversionOperators), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("targetType"); + } } - #endregion - - #region HaveExplicitConversionOperatorOfT - - [Fact] - public void When_asserting_a_type_has_an_explicit_conversion_operatorOfT_which_it_does_it_succeeds() + public class HaveExplicitConversionOperatorOfT { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should() - .HaveExplicitConversionOperator() - .Which.Should() - .NotBeNull(); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_has_an_explicit_conversion_operatorOfT_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should() + .HaveExplicitConversionOperator() + .Which.Should() + .NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_conversion_operatorOfT_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().HaveExplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_explicit_conversion_operatorOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveExplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but type is ."); + } } - [Fact] - public void When_asserting_a_type_has_an_explicit_conversion_operatorOfT_which_it_does_not_it_fails() + public class NotHaveExplicitConversionOperator { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().HaveExplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but it does not."); + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(string); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitConversionOperator(sourceType, targetType); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_which_it_does_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(byte); + + // Act + Action act = () => + type.Should().NotHaveExplicitConversionOperator( + sourceType, targetType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit *.Byte(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_explicit_conversion_operator_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveExplicitConversionOperator( + typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit *.String(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_from_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().NotHaveExplicitConversionOperator(null, typeof(string)); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("sourceType"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_to_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().NotHaveExplicitConversionOperator(typeof(TypeWithConversionOperators), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("targetType"); + } } - [Fact] - public void When_subject_is_null_have_explicit_conversion_operatorOfT_should_fail() + public class NotHaveExplicitConversionOperatorOfT { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveExplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit System.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but type is ."); + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_conversion_operatorOfT_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitConversionOperator(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_conversion_operatorOfT_which_it_does_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().NotHaveExplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static explicit *.Byte(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but it does."); + } } - - #endregion - - #region NotHaveExplicitConversionOperator - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(string); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitConversionOperator(sourceType, targetType); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_which_it_does_it_fails() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(byte); - - // Act - Action act = () => - type.Should().NotHaveExplicitConversionOperator( - sourceType, targetType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit *.Byte(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but it does."); - } - - [Fact] - public void When_subject_is_null_not_have_explicit_conversion_operator_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveExplicitConversionOperator( - typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit *.String(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_from_null_it_should_throw() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().NotHaveExplicitConversionOperator(null, typeof(string)); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("sourceType"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_conversion_operator_to_null_it_should_throw() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().NotHaveExplicitConversionOperator(typeof(TypeWithConversionOperators), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("targetType"); - } - - #endregion - - #region NotHaveExplicitConversionOperatorOfT - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_conversion_operatorOfT_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitConversionOperator(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_conversion_operatorOfT_which_it_does_it_fails() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().NotHaveExplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static explicit *.Byte(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but it does."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitMethod.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitMethod.cs index 0c54efb6dc..7f3c955ee2 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitMethod.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitMethod.cs @@ -9,523 +9,519 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveExplicitMethod - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitMethod(interfaceType, "ExplicitMethod", new Type[0]); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_and_explicitly_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", new Type[0]); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitMethod(interfaceType, "ImplicitMethod", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + - "*.IExplicitInterface.ImplicitMethod(), but it does not."); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_not_implement_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitMethod(interfaceType, "NonExistentMethod", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + - "*.IExplicitInterface.NonExistentMethod(), but it does not."); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_method_from_an_unimplemented_interface_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IDummyInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitMethod(interfaceType, "NonExistentProperty", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassExplicitlyImplementingInterface to implement interface " + - "*.IDummyInterface, but it does not."); - } - - [Fact] - public void When_subject_is_null_have_explicit_method_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveExplicitMethod( - typeof(IExplicitInterface), "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_method_with_a_null_interface_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod(null, "ExplicitMethod", new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("interfaceType"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_method_with_a_null_parameter_type_list_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod(typeof(IExplicitInterface), "ExplicitMethod", null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_method_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod(typeof(IExplicitInterface), null, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_method_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod(typeof(IExplicitInterface), string.Empty, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion - - #region HaveExplicitMethodOfT - - [Fact] - public void When_asserting_a_type_explicitly_implementsOfT_a_method_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitMethod("ExplicitMethod", new Type[0]); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_subject_is_null_have_explicit_methodOfT_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveExplicitMethod( - "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_methodOfT_with_a_null_parameter_type_list_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod("ExplicitMethod", null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_methodOfT_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod(null, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_methodOfT_with_an_empty_name_it_should_throw() + public class HaveExplicitMethod { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitMethod(string.Empty, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); + [Fact] + public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitMethod(interfaceType, "ExplicitMethod", new Type[0]); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_and_explicitly_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", new Type[0]); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitMethod(interfaceType, "ImplicitMethod", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + + "*.IExplicitInterface.ImplicitMethod(), but it does not."); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_not_implement_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitMethod(interfaceType, "NonExistentMethod", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + + "*.IExplicitInterface.NonExistentMethod(), but it does not."); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_method_from_an_unimplemented_interface_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IDummyInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitMethod(interfaceType, "NonExistentProperty", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassExplicitlyImplementingInterface to implement interface " + + "*.IDummyInterface, but it does not."); + } + + [Fact] + public void When_subject_is_null_have_explicit_method_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveExplicitMethod( + typeof(IExplicitInterface), "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_method_with_a_null_interface_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod(null, "ExplicitMethod", new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("interfaceType"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_method_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod(typeof(IExplicitInterface), "ExplicitMethod", null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_method_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod(typeof(IExplicitInterface), null, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_method_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod(typeof(IExplicitInterface), string.Empty, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - #endregion - - #region NotHaveExplicitMethod - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_it_fails() + public class HaveExplicitMethodOfT { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitMethod(interfaceType, "ExplicitMethod", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + - "*.IExplicitInterface.ExplicitMethod(), but it does."); + [Fact] + public void When_asserting_a_type_explicitly_implementsOfT_a_method_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitMethod("ExplicitMethod", new Type[0]); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_subject_is_null_have_explicit_methodOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveExplicitMethod( + "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_methodOfT_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod("ExplicitMethod", null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_methodOfT_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod(null, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_methodOfT_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitMethod(string.Empty, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_and_explicitly_it_fails() + public class NotHaveExplicitMethod { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + - "*.IExplicitInterface.ExplicitImplicitMethod(), but it does."); + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitMethod(interfaceType, "ExplicitMethod", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + + "*.IExplicitInterface.ExplicitMethod(), but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_and_explicitly_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + + "*.IExplicitInterface.ExplicitImplicitMethod(), but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitMethod(interfaceType, "ImplicitMethod", new Type[0]); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_not_implement_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitMethod(interfaceType, "NonExistentMethod", new Type[0]); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_method_from_an_unimplemented_interface_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IDummyInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitMethod(interfaceType, "NonExistentMethod", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassExplicitlyImplementingInterface to implement interface *.IDummyInterface" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_not_have_explicit_method_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod( + typeof(IExplicitInterface), "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to not explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_method_inherited_from_null_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod(null, "ExplicitMethod", new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("interfaceType"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_method_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod(typeof(IExplicitInterface), "ExplicitMethod", null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_method_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod(typeof(IExplicitInterface), null, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_method_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod(typeof(IExplicitInterface), string.Empty, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_it_succeeds() + public class NotHaveExplicitMethodOfT { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitMethod(interfaceType, "ImplicitMethod", new Type[0]); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_does_not_explicitly_implementOfT_a_method_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitMethod("ExplicitMethod", new Type[0]); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + + "*.IExplicitInterface.ExplicitMethod(), but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_explicit_methodOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod( + "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to not explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_methodOfT_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod("ExplicitMethod", null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_methodOfT_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod(null, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_methodOfT_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitMethod(string.Empty, new Type[0]); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_not_implement_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitMethod(interfaceType, "NonExistentMethod", new Type[0]); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_method_from_an_unimplemented_interface_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IDummyInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitMethod(interfaceType, "NonExistentMethod", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassExplicitlyImplementingInterface to implement interface *.IDummyInterface" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_not_have_explicit_method_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod( - typeof(IExplicitInterface), "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to not explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_method_inherited_from_null_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod(null, "ExplicitMethod", new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("interfaceType"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_method_with_a_null_parameter_type_list_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod(typeof(IExplicitInterface), "ExplicitMethod", null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_method_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod(typeof(IExplicitInterface), null, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_method_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod(typeof(IExplicitInterface), string.Empty, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion - - #region NotHaveExplicitMethodOfT - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implementOfT_a_method_which_it_does_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitMethod("ExplicitMethod", new Type[0]); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + - "*.IExplicitInterface.ExplicitMethod(), but it does."); - } - - [Fact] - public void When_subject_is_null_not_have_explicit_methodOfT_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod( - "ExplicitMethod", new Type[0], "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to not explicitly implement *.IExplicitInterface.ExplicitMethod() *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_methodOfT_with_a_null_parameter_type_list_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod("ExplicitMethod", null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_methodOfT_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod(null, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_methodOfT_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitMethod(string.Empty, new Type[0]); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitProperty.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitProperty.cs index 8c128e066c..3b4103af98 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitProperty.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveExplicitProperty.cs @@ -9,463 +9,459 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveExplicitProperty - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitProperty(interfaceType, "ExplicitStringProperty"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_and_explicitly_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitProperty(interfaceType, "ImplicitStringProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + - "*.IExplicitInterface.ImplicitStringProperty, but it does not."); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_not_implement_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitProperty(interfaceType, "NonExistentProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + - "*.IExplicitInterface.NonExistentProperty, but it does not."); - } - - [Fact] - public void When_asserting_a_type_explicitly_implements_a_property_from_an_unimplemented_interface_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IDummyInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitProperty(interfaceType, "NonExistentProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassExplicitlyImplementingInterface to implement interface *.IDummyInterface" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_explicit_property_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveExplicitProperty( - typeof(IExplicitInterface), "ExplicitStringProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to explicitly implement *.IExplicitInterface.ExplicitStringProperty *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_property_inherited_by_null_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitProperty(null, "ExplicitStringProperty"); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("interfaceType"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_property_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitProperty(typeof(IExplicitInterface), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicit_property_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitProperty(typeof(IExplicitInterface), string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion - - #region HaveExplicitPropertyOfT - - [Fact] - public void When_asserting_a_type_explicitlyOfT_implements_a_property_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should() - .HaveExplicitProperty("ExplicitStringProperty"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_an_explicitlyOfT_property_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitProperty(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_an_explicitlyOfT_property_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().HaveExplicitProperty(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_subject_is_null_have_explicit_propertyOfT_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveExplicitProperty( - "ExplicitStringProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to explicitly implement *.IExplicitInterface.ExplicitStringProperty *failure message*" + - ", but type is ."); - } - - #endregion - - #region NotHaveExplicitProperty - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitProperty(interfaceType, "ExplicitStringProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + - "*.IExplicitInterface.ExplicitStringProperty, but it does."); - } - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_and_explicitly_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + - "*.IExplicitInterface.ExplicitImplicitStringProperty, but it does."); - } - - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_it_succeeds() + public class HaveExplicitProperty { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitProperty(interfaceType, "ImplicitStringProperty"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitProperty(interfaceType, "ExplicitStringProperty"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_and_explicitly_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitProperty(interfaceType, "ImplicitStringProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + + "*.IExplicitInterface.ImplicitStringProperty, but it does not."); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_not_implement_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitProperty(interfaceType, "NonExistentProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to explicitly implement " + + "*.IExplicitInterface.NonExistentProperty, but it does not."); + } + + [Fact] + public void When_asserting_a_type_explicitly_implements_a_property_from_an_unimplemented_interface_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IDummyInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitProperty(interfaceType, "NonExistentProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassExplicitlyImplementingInterface to implement interface *.IDummyInterface" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_explicit_property_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveExplicitProperty( + typeof(IExplicitInterface), "ExplicitStringProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to explicitly implement *.IExplicitInterface.ExplicitStringProperty *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_property_inherited_by_null_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitProperty(null, "ExplicitStringProperty"); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("interfaceType"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_property_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitProperty(typeof(IExplicitInterface), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicit_property_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitProperty(typeof(IExplicitInterface), string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_not_implement_it_succeeds() + public class HaveExplicitPropertyOfT { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IExplicitInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitProperty(interfaceType, "NonExistentProperty"); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_explicitlyOfT_implements_a_property_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should() + .HaveExplicitProperty("ExplicitStringProperty"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_an_explicitlyOfT_property_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitProperty(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_an_explicitlyOfT_property_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().HaveExplicitProperty(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_subject_is_null_have_explicit_propertyOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveExplicitProperty( + "ExplicitStringProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to explicitly implement *.IExplicitInterface.ExplicitStringProperty *failure message*" + + ", but type is ."); + } } - [Fact] - public void When_asserting_a_type_does_not_explicitly_implement_a_property_from_an_unimplemented_interface_it_succeeds() + public class NotHaveExplicitProperty { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - var interfaceType = typeof(IDummyInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitProperty(interfaceType, "NonExistentProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassExplicitlyImplementingInterface to implement interface *.IDummyInterface" + - ", but it does not."); + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitProperty(interfaceType, "ExplicitStringProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + + "*.IExplicitInterface.ExplicitStringProperty, but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_and_explicitly_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + + "*.IExplicitInterface.ExplicitImplicitStringProperty, but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitProperty(interfaceType, "ImplicitStringProperty"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_not_implement_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IExplicitInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitProperty(interfaceType, "NonExistentProperty"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_explicitly_implement_a_property_from_an_unimplemented_interface_it_succeeds() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + var interfaceType = typeof(IDummyInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitProperty(interfaceType, "NonExistentProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassExplicitlyImplementingInterface to implement interface *.IDummyInterface" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_not_have_explicit_property_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty( + typeof(IExplicitInterface), "ExplicitStringProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to not explicitly implement *IExplicitInterface.ExplicitStringProperty *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_property_inherited_from_null_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty(null, "ExplicitStringProperty"); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("interfaceType"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_property_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty(typeof(IExplicitInterface), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicit_property_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty(typeof(IExplicitInterface), string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - [Fact] - public void When_subject_is_null_not_have_explicit_property_should_fail() + public class NotHaveExplicitPropertyOfT { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty( - typeof(IExplicitInterface), "ExplicitStringProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to not explicitly implement *IExplicitInterface.ExplicitStringProperty *failure message*" + - ", but type is ."); + [Fact] + public void When_asserting_a_type_does_not_explicitlyOfT_implement_a_property_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should() + .NotHaveExplicitProperty("ExplicitStringProperty"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + + "*.IExplicitInterface.ExplicitStringProperty, but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_explicit_propertyOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty( + "ExplicitStringProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type to not explicitly implement *.IExplicitInterface.ExplicitStringProperty *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicitlyOfT_property_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_explicitlyOfT_property_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassExplicitlyImplementingInterface); + + // Act + Action act = () => + type.Should().NotHaveExplicitProperty(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_property_inherited_from_null_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty(null, "ExplicitStringProperty"); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("interfaceType"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_property_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty(typeof(IExplicitInterface), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicit_property_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty(typeof(IExplicitInterface), string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion - - #region NotHaveExplicitPropertyOfT - - [Fact] - public void When_asserting_a_type_does_not_explicitlyOfT_implement_a_property_which_it_does_it_fails() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should() - .NotHaveExplicitProperty("ExplicitStringProperty"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected *.ClassExplicitlyImplementingInterface to not explicitly implement " + - "*.IExplicitInterface.ExplicitStringProperty, but it does."); - } - - [Fact] - public void When_subject_is_null_not_have_explicit_propertyOfT_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty( - "ExplicitStringProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type to not explicitly implement *.IExplicitInterface.ExplicitStringProperty *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicitlyOfT_property_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_explicitlyOfT_property_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassExplicitlyImplementingInterface); - - // Act - Action act = () => - type.Should().NotHaveExplicitProperty(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveImplicitConversionOperator.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveImplicitConversionOperator.cs index 6695dfadb2..391629aa03 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveImplicitConversionOperator.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveImplicitConversionOperator.cs @@ -9,296 +9,292 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveImplicitConversionOperator - - [Fact] - public void When_asserting_a_type_has_an_implicit_conversion_operator_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(int); - - // Act - Action act = () => - type.Should() - .HaveImplicitConversionOperator(sourceType, targetType) - .Which.Should() - .NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_an_implicit_conversion_operator_which_it_does_not_it_fails() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(string); - - // Act - Action act = () => - type.Should().HaveImplicitConversionOperator( - sourceType, targetType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_implicit_conversion_operator_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveImplicitConversionOperator( - typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_implicit_conversion_operator_from_null_it_should_throw() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().HaveImplicitConversionOperator(null, typeof(string)); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("sourceType"); - } - - [Fact] - public void When_asserting_a_type_has_an_implicit_conversion_operator_to_null_it_should_throw() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().HaveImplicitConversionOperator(typeof(TypeWithConversionOperators), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("targetType"); - } - - #endregion - - #region HaveImplicitConversionOperatorOfT - - [Fact] - public void When_asserting_a_type_has_an_implicit_conversion_operatorOfT_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should() - .HaveImplicitConversionOperator() - .Which.Should() - .NotBeNull(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_an_implicit_conversion_operatorOfT_which_it_does_not_it_fails() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().HaveImplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_implicit_conversion_operatorOfT_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveImplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + - ", but type is ."); - } - - #endregion - - #region NotHaveImplicitConversionOperator - - [Fact] - public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(string); - - // Act - Action act = () => - type.Should() - .NotHaveImplicitConversionOperator(sourceType, targetType); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_which_it_does_it_fails() + public class HaveImplicitConversionOperator { - // Arrange - var type = typeof(TypeWithConversionOperators); - var sourceType = typeof(TypeWithConversionOperators); - var targetType = typeof(int); - - // Act - Action act = () => - type.Should().NotHaveImplicitConversionOperator( - sourceType, targetType, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.Int32(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but it does."); + [Fact] + public void When_asserting_a_type_has_an_implicit_conversion_operator_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(int); + + // Act + Action act = () => + type.Should() + .HaveImplicitConversionOperator(sourceType, targetType) + .Which.Should() + .NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_an_implicit_conversion_operator_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(string); + + // Act + Action act = () => + type.Should().HaveImplicitConversionOperator( + sourceType, targetType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_implicit_conversion_operator_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveImplicitConversionOperator( + typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_implicit_conversion_operator_from_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().HaveImplicitConversionOperator(null, typeof(string)); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("sourceType"); + } + + [Fact] + public void When_asserting_a_type_has_an_implicit_conversion_operator_to_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().HaveImplicitConversionOperator(typeof(TypeWithConversionOperators), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("targetType"); + } } - [Fact] - public void When_subject_is_null_not_have_implicit_conversion_operator_should_fail() + public class HaveImplicitConversionOperatorOfT { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveImplicitConversionOperator( - typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.String(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but type is ."); + [Fact] + public void When_asserting_a_type_has_an_implicit_conversion_operatorOfT_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should() + .HaveImplicitConversionOperator() + .Which.Should() + .NotBeNull(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_an_implicit_conversion_operatorOfT_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().HaveImplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_implicit_conversion_operatorOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveImplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.String(*.TypeWithConversionOperators) to exist *failure message*" + + ", but type is ."); + } } - [Fact] - public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_from_null_it_should_throw() + public class NotHaveImplicitConversionOperator { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().NotHaveImplicitConversionOperator(null, typeof(string)); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("sourceType"); + [Fact] + public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(string); + + // Act + Action act = () => + type.Should() + .NotHaveImplicitConversionOperator(sourceType, targetType); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_which_it_does_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + var sourceType = typeof(TypeWithConversionOperators); + var targetType = typeof(int); + + // Act + Action act = () => + type.Should().NotHaveImplicitConversionOperator( + sourceType, targetType, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.Int32(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_implicit_conversion_operator_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveImplicitConversionOperator( + typeof(TypeWithConversionOperators), typeof(string), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.String(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_from_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().NotHaveImplicitConversionOperator(null, typeof(string)); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("sourceType"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_to_null_it_should_throw() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().NotHaveImplicitConversionOperator(typeof(TypeWithConversionOperators), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("targetType"); + } } - [Fact] - public void When_asserting_a_type_does_not_have_an_implicit_conversion_operator_to_null_it_should_throw() + public class NotHaveImplicitConversionOperatorOfT { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().NotHaveImplicitConversionOperator(typeof(TypeWithConversionOperators), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("targetType"); + [Fact] + public void When_asserting_a_type_does_not_have_an_implicit_conversion_operatorOfT_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should() + .NotHaveImplicitConversionOperator(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_implicit_conversion_operatorOfT_which_it_does_it_fails() + { + // Arrange + var type = typeof(TypeWithConversionOperators); + + // Act + Action act = () => + type.Should().NotHaveImplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.Int32(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_implicit_conversion_operatorOfT_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveImplicitConversionOperator( + "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected public static implicit *.String(*.TypeWithConversionOperators) to not exist *failure message*" + + ", but type is ."); + } } - - #endregion - - #region NotHaveImplicitConversionOperatorOfT - - [Fact] - public void When_asserting_a_type_does_not_have_an_implicit_conversion_operatorOfT_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should() - .NotHaveImplicitConversionOperator(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_implicit_conversion_operatorOfT_which_it_does_it_fails() - { - // Arrange - var type = typeof(TypeWithConversionOperators); - - // Act - Action act = () => - type.Should().NotHaveImplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.Int32(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but it does."); - } - - [Fact] - public void When_subject_is_null_not_have_implicit_conversion_operatorOfT_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveImplicitConversionOperator( - "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected public static implicit *.String(*.TypeWithConversionOperators) to not exist *failure message*" + - ", but type is ."); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs index 3b1fc79a81..398bc5eeae 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs @@ -10,169 +10,167 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveIndexer - - [Fact] - public void When_asserting_a_type_has_an_indexer_which_it_does_then_it_succeeds() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .HaveIndexer(typeof(string), new[] { typeof(string) }) - .Which.Should() - .BeWritable(CSharpAccessModifier.Internal) - .And.BeReadable(CSharpAccessModifier.Private); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_an_indexer_which_it_does_not_it_fails() - { - // Arrange - var type = typeof(ClassWithNoMembers); - - // Act - Action act = () => - type.Should().HaveIndexer( - typeof(string), new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected String *ClassWithNoMembers[System.Int32, System.Type] to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_asserting_a_type_has_an_indexer_with_different_parameters_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveIndexer( - typeof(string), new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected String *.ClassWithMembers[System.Int32, System.Type] to exist *failure message*, but it does not."); - } - - [Fact] - public void When_subject_is_null_have_indexer_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveIndexer(typeof(string), new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected String type[System.String] to exist *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_an_indexer_for_null_it_should_throw() + public class HaveIndexer { - // Arrange - Type type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveIndexer(null, new[] { typeof(string) }); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("indexerType"); + [Fact] + public void When_asserting_a_type_has_an_indexer_which_it_does_then_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveIndexer(typeof(string), new[] { typeof(string) }) + .Which.Should() + .BeWritable(CSharpAccessModifier.Internal) + .And.BeReadable(CSharpAccessModifier.Private); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_an_indexer_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(ClassWithNoMembers); + + // Act + Action act = () => + type.Should().HaveIndexer( + typeof(string), new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected String *ClassWithNoMembers[System.Int32, System.Type] to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_asserting_a_type_has_an_indexer_with_different_parameters_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveIndexer( + typeof(string), new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected String *.ClassWithMembers[System.Int32, System.Type] to exist *failure message*, but it does not."); + } + + [Fact] + public void When_subject_is_null_have_indexer_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveIndexer(typeof(string), new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected String type[System.String] to exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_an_indexer_for_null_it_should_throw() + { + // Arrange + Type type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveIndexer(null, new[] { typeof(string) }); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("indexerType"); + } + + [Fact] + public void When_asserting_a_type_has_an_indexer_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + Type type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveIndexer(typeof(string), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } } - - [Fact] - public void When_asserting_a_type_has_an_indexer_with_a_null_parameter_type_list_it_should_throw() + + public class NotHaveIndexer { - // Arrange - Type type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveIndexer(typeof(string), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); + [Fact] + public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(ClassWithoutMembers); + + // Act + Action act = () => + type.Should().NotHaveIndexer(new[] { typeof(string) }); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveIndexer(new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected indexer *.ClassWithMembers[System.String] to not exist *failure message*, but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_indexer_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveIndexer(new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected indexer type[System.String] to not exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_an_indexer_for_null_it_should_throw() + { + // Arrange + Type type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveIndexer(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } } - - #endregion - - #region NotHaveIndexer - - [Fact] - public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(ClassWithoutMembers); - - // Act - Action act = () => - type.Should().NotHaveIndexer(new[] { typeof(string) }); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveIndexer(new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected indexer *.ClassWithMembers[System.String] to not exist *failure message*, but it does."); - } - - [Fact] - public void When_subject_is_null_not_have_indexer_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveIndexer(new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected indexer type[System.String] to not exist *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_does_not_have_an_indexer_for_null_it_should_throw() - { - // Arrange - Type type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveIndexer(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveMethod.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveMethod.cs index b92c96c8c6..f1ae220a47 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveMethod.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveMethod.cs @@ -10,229 +10,227 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveMethod - - [Fact] - public void When_asserting_a_type_has_a_method_which_it_does_it_succeeds() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .HaveMethod("VoidMethod", new Type[] { }) - .Which.Should() - .HaveAccessModifier(CSharpAccessModifier.Private) - .And.ReturnVoid(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_a_method_which_it_does_not_it_fails() - { - // Arrange - var type = typeof(ClassWithNoMembers); - - // Act - Action act = () => - type.Should().HaveMethod( - "NonExistentMethod", new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method *ClassWithNoMembers.NonExistentMethod(*.Int32, *.Type) to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_asserting_a_type_has_a_method_with_different_parameter_types_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveMethod( - "VoidMethod", new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected method *.ClassWithMembers.VoidMethod(*.Int32, *.Type) to exist *failure message*" + - ", but it does not."); - } - - [Fact] - public void When_subject_is_null_have_method_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveMethod("Name", new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method type.Name(System.String) to exist *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_a_method_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveMethod(null, new[] { typeof(string) }); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_a_method_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveMethod(string.Empty, new[] { typeof(string) }); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_a_method_with_a_null_parameter_type_list_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveMethod("Name", null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - #endregion - - #region NotHaveMethod - - [Fact] - public void When_asserting_a_type_does_not_have_a_method_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(ClassWithoutMembers); - - // Act - Action act = () => - type.Should().NotHaveMethod("NonExistentMethod", new Type[] { }); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_method_which_it_has_with_different_parameter_types_it_succeeds() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveMethod("VoidMethod", new[] { typeof(int) }); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_that_method_which_it_does_it_fails() + public class HaveMethod { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveMethod("VoidMethod", new Type[] { }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method Void *.ClassWithMembers.VoidMethod() to not exist *failure message*, but it does."); + [Fact] + public void When_asserting_a_type_has_a_method_which_it_does_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveMethod("VoidMethod", new Type[] { }) + .Which.Should() + .HaveAccessModifier(CSharpAccessModifier.Private) + .And.ReturnVoid(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_method_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(ClassWithNoMembers); + + // Act + Action act = () => + type.Should().HaveMethod( + "NonExistentMethod", new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method *ClassWithNoMembers.NonExistentMethod(*.Int32, *.Type) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_asserting_a_type_has_a_method_with_different_parameter_types_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveMethod( + "VoidMethod", new[] { typeof(int), typeof(Type) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected method *.ClassWithMembers.VoidMethod(*.Int32, *.Type) to exist *failure message*" + + ", but it does not."); + } + + [Fact] + public void When_subject_is_null_have_method_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveMethod("Name", new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method type.Name(System.String) to exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_a_method_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveMethod(null, new[] { typeof(string) }); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_a_method_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveMethod(string.Empty, new[] { typeof(string) }); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_a_method_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveMethod("Name", null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } } - [Fact] - public void When_subject_is_null_not_have_method_should_fail() + public class NotHaveMethod { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveMethod("Name", new[] { typeof(string) }, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected method type.Name(System.String) to not exist *failure message*, but type is ."); + [Fact] + public void When_asserting_a_type_does_not_have_a_method_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(ClassWithoutMembers); + + // Act + Action act = () => + type.Should().NotHaveMethod("NonExistentMethod", new Type[] { }); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_method_which_it_has_with_different_parameter_types_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveMethod("VoidMethod", new[] { typeof(int) }); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_that_method_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveMethod("VoidMethod", new Type[] { }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method Void *.ClassWithMembers.VoidMethod() to not exist *failure message*, but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_method_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveMethod("Name", new[] { typeof(string) }, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected method type.Name(System.String) to not exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_method_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveMethod(null, new[] { typeof(string) }); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_method_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveMethod(string.Empty, new[] { typeof(string) }); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_method_with_a_null_parameter_type_list_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveMethod("Name", null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("parameterTypes"); + } } - - [Fact] - public void When_asserting_a_type_does_not_have_a_method_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveMethod(null, new[] { typeof(string) }); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_method_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveMethod(string.Empty, new[] { typeof(string) }); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_method_with_a_null_parameter_type_list_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveMethod("Name", null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("parameterTypes"); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveProperty.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveProperty.cs index 44888e9cbd..f13b02c56b 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveProperty.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveProperty.cs @@ -10,251 +10,248 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region HaveProperty - - [Fact] - public void When_asserting_a_type_has_a_property_which_it_does_then_it_succeeds() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .HaveProperty(typeof(string), "PrivateWriteProtectedReadProperty") - .Which.Should() - .BeWritable(CSharpAccessModifier.Private) - .And.BeReadable(CSharpAccessModifier.Protected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_a_property_which_it_does_not_it_fails() - { - // Arrange - var type = typeof(ClassWithNoMembers); - - // Act - Action act = () => - type.Should().HaveProperty(typeof(string), "PublicProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected String *ClassWithNoMembers.PublicProperty to exist *failure message*, but it does not."); - } - - [Fact] - public void When_asserting_a_type_has_a_property_which_it_has_with_a_different_type_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .HaveProperty(typeof(int), "PrivateWriteProtectedReadProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected String *.ClassWithMembers.PrivateWriteProtectedReadProperty to be of type System.Int32 " + - "*failure message*, but it is not."); - } - - [Fact] - public void When_subject_is_null_have_property_should_fail() - { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().HaveProperty(typeof(string), "PublicProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected String type.PublicProperty to exist *failure message*, but type is ."); - } - - [Fact] - public void When_asserting_a_type_has_a_property_of_null_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveProperty(null, "PublicProperty"); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("propertyType"); - } - - [Fact] - public void When_asserting_a_type_has_a_property_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveProperty(typeof(string), null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_a_property_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveProperty(typeof(string), string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion - - #region HavePropertyOfT - - [Fact] - public void When_asserting_a_type_has_a_propertyOfT_which_it_does_then_it_succeeds() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should() - .HaveProperty("PrivateWriteProtectedReadProperty") - .Which.Should() - .BeWritable(CSharpAccessModifier.Private) - .And.BeReadable(CSharpAccessModifier.Protected); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_has_a_propertyOfT_with_a_null_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveProperty(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - [Fact] - public void When_asserting_a_type_has_a_propertyOfT_with_an_empty_name_it_should_throw() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().HaveProperty(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); - } - - #endregion - - #region NotHaveProperty - - [Fact] - public void When_asserting_a_type_does_not_have_a_property_which_it_does_not_it_succeeds() - { - // Arrange - var type = typeof(ClassWithoutMembers); - - // Act - Action act = () => - type.Should().NotHaveProperty("Property"); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_have_a_property_which_it_does_it_fails() - { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveProperty("PrivateWriteProtectedReadProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected String *.ClassWithMembers.PrivateWriteProtectedReadProperty to not exist *failure message*" + - ", but it does."); - } - - [Fact] - public void When_subject_is_null_not_have_property_should_fail() + public class HaveProperty { - // Arrange - Type type = null; - - // Act - Action act = () => - type.Should().NotHaveProperty("PublicProperty", "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage("Expected type.PublicProperty to not exist *failure message*, but type is ."); + [Fact] + public void When_asserting_a_type_has_a_property_which_it_does_then_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveProperty(typeof(string), "PrivateWriteProtectedReadProperty") + .Which.Should() + .BeWritable(CSharpAccessModifier.Private) + .And.BeReadable(CSharpAccessModifier.Protected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_property_which_it_does_not_it_fails() + { + // Arrange + var type = typeof(ClassWithNoMembers); + + // Act + Action act = () => + type.Should().HaveProperty(typeof(string), "PublicProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected String *ClassWithNoMembers.PublicProperty to exist *failure message*, but it does not."); + } + + [Fact] + public void When_asserting_a_type_has_a_property_which_it_has_with_a_different_type_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveProperty(typeof(int), "PrivateWriteProtectedReadProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected String *.ClassWithMembers.PrivateWriteProtectedReadProperty to be of type System.Int32 " + + "*failure message*, but it is not."); + } + + [Fact] + public void When_subject_is_null_have_property_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().HaveProperty(typeof(string), "PublicProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected String type.PublicProperty to exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_has_a_property_of_null_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveProperty(null, "PublicProperty"); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("propertyType"); + } + + [Fact] + public void When_asserting_a_type_has_a_property_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveProperty(typeof(string), null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_a_property_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveProperty(typeof(string), string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - [Fact] - public void When_asserting_a_type_does_not_have_a_property_with_a_null_name_it_should_throw() + public class HavePropertyOfT { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveProperty(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); + [Fact] + public void When_asserting_a_type_has_a_propertyOfT_which_it_does_then_it_succeeds() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should() + .HaveProperty("PrivateWriteProtectedReadProperty") + .Which.Should() + .BeWritable(CSharpAccessModifier.Private) + .And.BeReadable(CSharpAccessModifier.Protected); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_has_a_propertyOfT_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveProperty(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_has_a_propertyOfT_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().HaveProperty(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - [Fact] - public void When_asserting_a_type_does_not_have_a_property_with_an_empty_name_it_should_throw() + public class NotHaveProperty { - // Arrange - var type = typeof(ClassWithMembers); - - // Act - Action act = () => - type.Should().NotHaveProperty(string.Empty); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("name"); + [Fact] + public void When_asserting_a_type_does_not_have_a_property_which_it_does_not_it_succeeds() + { + // Arrange + var type = typeof(ClassWithoutMembers); + + // Act + Action act = () => + type.Should().NotHaveProperty("Property"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_property_which_it_does_it_fails() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveProperty("PrivateWriteProtectedReadProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected String *.ClassWithMembers.PrivateWriteProtectedReadProperty to not exist *failure message*" + + ", but it does."); + } + + [Fact] + public void When_subject_is_null_not_have_property_should_fail() + { + // Arrange + Type type = null; + + // Act + Action act = () => + type.Should().NotHaveProperty("PublicProperty", "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage("Expected type.PublicProperty to not exist *failure message*, but type is ."); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_property_with_a_null_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveProperty(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } + + [Fact] + public void When_asserting_a_type_does_not_have_a_property_with_an_empty_name_it_should_throw() + { + // Arrange + var type = typeof(ClassWithMembers); + + // Act + Action act = () => + type.Should().NotHaveProperty(string.Empty); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("name"); + } } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs index 6614396893..c1b06bf1bc 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs @@ -9,174 +9,170 @@ namespace FluentAssertions.Specs.Types /// public partial class TypeAssertionSpecs { - #region Implement - - [Fact] - public void When_asserting_a_type_implements_an_interface_which_it_does_then_it_succeeds() - { - // Arrange - var type = typeof(ClassThatImplementsInterface); - - // Act - Action act = () => - type.Should().Implement(typeof(IDummyInterface)); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_then_it_fails() + public class Implement { - // Arrange - var type = typeof(ClassThatDoesNotImplementInterface); - - // Act - Action act = () => - type.Should().Implement(typeof(IDummyInterface), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassThatDoesNotImplementInterface to implement interface *.IDummyInterface " + - "*failure message*, but it does not."); + [Fact] + public void When_asserting_a_type_implements_an_interface_which_it_does_then_it_succeeds() + { + // Arrange + var type = typeof(ClassThatImplementsInterface); + + // Act + Action act = () => + type.Should().Implement(typeof(IDummyInterface)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_then_it_fails() + { + // Arrange + var type = typeof(ClassThatDoesNotImplementInterface); + + // Act + Action act = () => + type.Should().Implement(typeof(IDummyInterface), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassThatDoesNotImplementInterface to implement interface *.IDummyInterface " + + "*failure message*, but it does not."); + } + + [Fact] + public void When_asserting_a_type_implements_a_NonInterface_type_it_fails() + { + // Arrange + var type = typeof(ClassThatDoesNotImplementInterface); + + // Act + Action act = () => + type.Should().Implement(typeof(DateTime), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassThatDoesNotImplementInterface to implement interface *.DateTime *failure message*" + + ", but *.DateTime is not an interface."); + } + + [Fact] + public void When_asserting_a_type_to_implement_null_it_should_throw() + { + // Arrange + var type = typeof(DummyBaseType<>); + + // Act + Action act = () => + type.Should().Implement(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("interfaceType"); + } } - - [Fact] - public void When_asserting_a_type_implements_a_NonInterface_type_it_fails() - { - // Arrange - var type = typeof(ClassThatDoesNotImplementInterface); - - // Act - Action act = () => - type.Should().Implement(typeof(DateTime), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassThatDoesNotImplementInterface to implement interface *.DateTime *failure message*" + - ", but *.DateTime is not an interface."); - } - - [Fact] - public void When_asserting_a_type_to_implement_null_it_should_throw() + + public class ImplementOfT { - // Arrange - var type = typeof(DummyBaseType<>); - - // Act - Action act = () => - type.Should().Implement(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("interfaceType"); + [Fact] + public void When_asserting_a_type_implementsOfT_an_interface_which_it_does_then_it_succeeds() + { + // Arrange + var type = typeof(ClassThatImplementsInterface); + + // Act + Action act = () => + type.Should().Implement(); + + // Assert + act.Should().NotThrow(); + } } - #endregion - - #region ImplementOfT - - [Fact] - public void When_asserting_a_type_implementsOfT_an_interface_which_it_does_then_it_succeeds() + public class NotImplement { - // Arrange - var type = typeof(ClassThatImplementsInterface); - - // Act - Action act = () => - type.Should().Implement(); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_not_then_it_succeeds() + { + // Arrange + var type = typeof(ClassThatDoesNotImplementInterface); + + // Act + Action act = () => + type.Should().NotImplement(typeof(IDummyInterface)); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_type_implements_an_interface_which_it_does_not_then_it_fails() + { + // Arrange + var type = typeof(ClassThatImplementsInterface); + + // Act + Action act = () => + type.Should().NotImplement(typeof(IDummyInterface), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassThatImplementsInterface to not implement interface *.IDummyInterface " + + "*failure message*, but it does."); + } + + [Fact] + public void When_asserting_a_type_does_not_implement_a_NonInterface_type_it_fails() + { + // Arrange + var type = typeof(ClassThatDoesNotImplementInterface); + + // Act + Action act = () => + type.Should().NotImplement(typeof(DateTime), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected type *.ClassThatDoesNotImplementInterface to not implement interface *.DateTime *failure message*" + + ", but *.DateTime is not an interface."); + } + + [Fact] + public void When_asserting_a_type_not_to_implement_null_it_should_throw() + { + // Arrange + var type = typeof(ClassThatDoesNotImplementInterface); + + // Act + Action act = () => + type.Should().NotImplement(null); + + // Assert + act.Should().ThrowExactly() + .WithParameterName("interfaceType"); + } } - #endregion - - #region NotImplement - - [Fact] - public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_not_then_it_succeeds() + public class NotImplementOfT { - // Arrange - var type = typeof(ClassThatDoesNotImplementInterface); - - // Act - Action act = () => - type.Should().NotImplement(typeof(IDummyInterface)); - - // Assert - act.Should().NotThrow(); + [Fact] + public void When_asserting_a_type_does_not_implementOfT_an_interface_which_it_does_not_then_it_succeeds() + { + // Arrange + var type = typeof(ClassThatDoesNotImplementInterface); + + // Act + Action act = () => + type.Should().NotImplement(); + + // Assert + act.Should().NotThrow(); + } } - - [Fact] - public void When_asserting_a_type_implements_an_interface_which_it_does_not_then_it_fails() - { - // Arrange - var type = typeof(ClassThatImplementsInterface); - - // Act - Action act = () => - type.Should().NotImplement(typeof(IDummyInterface), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassThatImplementsInterface to not implement interface *.IDummyInterface " + - "*failure message*, but it does."); - } - - [Fact] - public void When_asserting_a_type_does_not_implement_a_NonInterface_type_it_fails() - { - // Arrange - var type = typeof(ClassThatDoesNotImplementInterface); - - // Act - Action act = () => - type.Should().NotImplement(typeof(DateTime), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected type *.ClassThatDoesNotImplementInterface to not implement interface *.DateTime *failure message*" + - ", but *.DateTime is not an interface."); - } - - [Fact] - public void When_asserting_a_type_not_to_implement_null_it_should_throw() - { - // Arrange - var type = typeof(ClassThatDoesNotImplementInterface); - - // Act - Action act = () => - type.Should().NotImplement(null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("interfaceType"); - } - - #endregion - - #region NotImplementOfT - - [Fact] - public void When_asserting_a_type_does_not_implementOfT_an_interface_which_it_does_not_then_it_succeeds() - { - // Arrange - var type = typeof(ClassThatDoesNotImplementInterface); - - // Act - Action act = () => - type.Should().NotImplement(); - - // Assert - act.Should().NotThrow(); - } - - #endregion } } diff --git a/Tests/FluentAssertions.Specs/Types/TypeSelectorAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/TypeSelectorAssertionSpecs.cs index 7e48528bed..467ebe4f59 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeSelectorAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeSelectorAssertionSpecs.cs @@ -10,794 +10,784 @@ namespace FluentAssertions.Specs.Types { public class TypeSelectorAssertionSpecs { - #region BeSealed - - [Fact] - public void When_all_types_are_sealed_it_succeeds() + public class BeSealed { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_all_types_are_sealed_it_succeeds() { - typeof(Sealed) - }); - - // Act / Assert - types.Should().BeSealed(); - } - - [Fact] - public void When_any_type_is_not_sealed_it_fails_with_a_meaningful_message() - { - // Arrange - var types = new TypeSelector(new[] + // Arrange + var types = new TypeSelector(new[] + { + typeof(Sealed) + }); + + // Act / Assert + types.Should().BeSealed(); + } + + [Fact] + public void When_any_type_is_not_sealed_it_fails_with_a_meaningful_message() { - typeof(Sealed), - typeof(Abstract) - }); + // Arrange + var types = new TypeSelector(new[] + { + typeof(Sealed), + typeof(Abstract) + }); - // Act - Action act = () => types.Should().BeSealed("we want to test the failure {0}", "message"); + // Act + Action act = () => types.Should().BeSealed("we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be sealed *failure message*, but the following types are not:*\"*.Abstract\"."); + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be sealed *failure message*, but the following types are not:*\"*.Abstract\"."); + } } - #endregion - - #region NotBeSealed - - [Fact] - public void When_all_types_are_not_sealed_it_succeeds() + public class NotBeSealed { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_all_types_are_not_sealed_it_succeeds() { - typeof(Abstract) - }); - - // Act / Assert - types.Should().NotBeSealed(); - } - - [Fact] - public void When_any_type_is_sealed_it_fails_with_a_meaningful_message() - { - // Arrange - var types = new TypeSelector(new[] + // Arrange + var types = new TypeSelector(new[] + { + typeof(Abstract) + }); + + // Act / Assert + types.Should().NotBeSealed(); + } + + [Fact] + public void When_any_type_is_sealed_it_fails_with_a_meaningful_message() { - typeof(Abstract), - typeof(Sealed) - }); + // Arrange + var types = new TypeSelector(new[] + { + typeof(Abstract), + typeof(Sealed) + }); - // Act - Action act = () => types.Should().NotBeSealed("we want to test the failure {0}", "message"); + // Act + Action act = () => types.Should().NotBeSealed("we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage("Expected all types not to be sealed *failure message*, but the following types are:*\"*.Sealed\"."); + // Assert + act.Should().Throw() + .WithMessage("Expected all types not to be sealed *failure message*, but the following types are:*\"*.Sealed\"."); + } } - #endregion - - #region BeDecoratedWith - - [Fact] - public void When_asserting_a_selection_of_decorated_types_is_decorated_with_an_attribute_it_succeeds() + public class BeDecoratedWith { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_asserting_a_selection_of_decorated_types_is_decorated_with_an_attribute_it_succeeds() { - typeof(ClassWithAttribute) - }); - - // Act - Action act = () => - types.Should().BeDecoratedWith(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_selection_of_non_decorated_types_is_decorated_with_an_attribute_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassWithAttribute), - typeof(ClassWithoutAttribute), - typeof(OtherClassWithoutAttribute) - }); - - // Act - Action act = () => - types.Should().BeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be decorated with *.DummyClassAttribute *failure message*" + - ", but the attribute was not found on the following types:" + - "*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_TypeSelector_BeDecoratedWith_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassWithAttribute)); - - // Act - Action act = () => types.Should() - .BeDecoratedWith(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_asserting_a_selection_of_types_with_unexpected_attribute_property_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassWithAttribute), - typeof(ClassWithoutAttribute), - typeof(OtherClassWithoutAttribute) - }); - - // Act - Action act = () => - types.Should() - .BeDecoratedWith( - a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be decorated with *.DummyClassAttribute that matches " + - "(a.Name == \"Expected\") * a.IsEnabled *failure message*, but no matching attribute was found on " + - "the following types:*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); - } - - #endregion - - #region BeDecoratedWithOrInherit - - [Fact] - public void When_asserting_a_selection_of_decorated_types_inheriting_an_attribute_it_succeeds() - { - // Arrange - var types = new TypeSelector(new[] + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithAttribute) + }); + + // Act + Action act = () => + types.Should().BeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_selection_of_non_decorated_types_is_decorated_with_an_attribute_it_fails() { - typeof(ClassWithInheritedAttribute) - }); - - // Act - Action act = () => - types.Should().BeDecoratedWithOrInherit(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_selection_of_non_decorated_types_inheriting_an_attribute_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassWithAttribute), - typeof(ClassWithoutAttribute), - typeof(OtherClassWithoutAttribute) - }); - - // Act - Action act = () => - types.Should().BeDecoratedWithOrInherit("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be decorated with or inherit *.DummyClassAttribute *failure message*" + - ", but the attribute was not found on the following types:" + - "*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); - } - - [Fact] - public void When_injecting_a_null_predicate_into_TypeSelector_BeDecoratedWithOrInherit_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassWithAttribute)); - - // Act - Action act = () => types.Should() - .BeDecoratedWithOrInherit(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - [Fact] - public void When_asserting_a_selection_of_types_with_some_inheriting_attributes_with_unexpected_attribute_property_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassWithAttribute), - typeof(ClassWithInheritedAttribute), - typeof(ClassWithoutAttribute), - typeof(OtherClassWithoutAttribute) - }); - - // Act - Action act = () => - types.Should() - .BeDecoratedWithOrInherit( - a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be decorated with or inherit *.DummyClassAttribute that matches " + - "(a.Name == \"Expected\")*a.IsEnabled *failure message*, but no matching attribute was found " + - "on the following types:*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); - } + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithAttribute), + typeof(ClassWithoutAttribute), + typeof(OtherClassWithoutAttribute) + }); + + // Act + Action act = () => + types.Should().BeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be decorated with *.DummyClassAttribute *failure message*" + + ", but the attribute was not found on the following types:" + + "*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_TypeSelector_BeDecoratedWith_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassWithAttribute)); - #endregion + // Act + Action act = () => types.Should() + .BeDecoratedWith(isMatchingAttributePredicate: null); - #region NotBeDecoratedWith + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } - [Fact] - public void When_asserting_a_selection_of_non_decorated_types_is_not_decorated_with_an_attribute_it_succeeds() - { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_asserting_a_selection_of_types_with_unexpected_attribute_property_it_fails() { - typeof(ClassWithoutAttribute), - typeof(OtherClassWithoutAttribute) - }); - - // Act - Action act = () => - types.Should().NotBeDecoratedWith(); + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithAttribute), + typeof(ClassWithoutAttribute), + typeof(OtherClassWithoutAttribute) + }); + + // Act + Action act = () => + types.Should() + .BeDecoratedWith( + a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be decorated with *.DummyClassAttribute that matches " + + "(a.Name == \"Expected\") * a.IsEnabled *failure message*, but no matching attribute was found on " + + "the following types:*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); + } + } + + public class BeDecoratedWithOrInherit + { + [Fact] + public void When_asserting_a_selection_of_decorated_types_inheriting_an_attribute_it_succeeds() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithInheritedAttribute) + }); + + // Act + Action act = () => + types.Should().BeDecoratedWithOrInherit(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_selection_of_non_decorated_types_inheriting_an_attribute_it_fails() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithAttribute), + typeof(ClassWithoutAttribute), + typeof(OtherClassWithoutAttribute) + }); + + // Act + Action act = () => + types.Should().BeDecoratedWithOrInherit("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be decorated with or inherit *.DummyClassAttribute *failure message*" + + ", but the attribute was not found on the following types:" + + "*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_TypeSelector_BeDecoratedWithOrInherit_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassWithAttribute)); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => types.Should() + .BeDecoratedWithOrInherit(isMatchingAttributePredicate: null); - [Fact] - public void When_asserting_a_selection_of_decorated_types_is_not_decorated_with_an_attribute_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassWithoutAttribute), - typeof(ClassWithAttribute) - }); - - // Act - Action act = () => - types.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to not be decorated *.DummyClassAttribute *failure message*" + - ", but the attribute was found on the following types:*\"*.ClassWithAttribute\"."); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } - [Fact] - public void When_injecting_a_null_predicate_into_TypeSelector_NotBeDecoratedWith_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassWithAttribute)); + [Fact] + public void When_asserting_a_selection_of_types_with_some_inheriting_attributes_with_unexpected_attribute_property_it_fails() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithAttribute), + typeof(ClassWithInheritedAttribute), + typeof(ClassWithoutAttribute), + typeof(OtherClassWithoutAttribute) + }); + + // Act + Action act = () => + types.Should() + .BeDecoratedWithOrInherit( + a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be decorated with or inherit *.DummyClassAttribute that matches " + + "(a.Name == \"Expected\")*a.IsEnabled *failure message*, but no matching attribute was found " + + "on the following types:*\"*.ClassWithoutAttribute*.OtherClassWithoutAttribute\"."); + } + } + + public class NotBeDecoratedWith + { + [Fact] + public void When_asserting_a_selection_of_non_decorated_types_is_not_decorated_with_an_attribute_it_succeeds() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithoutAttribute), + typeof(OtherClassWithoutAttribute) + }); + + // Act + Action act = () => + types.Should().NotBeDecoratedWith(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_selection_of_decorated_types_is_not_decorated_with_an_attribute_it_fails() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithoutAttribute), + typeof(ClassWithAttribute) + }); + + // Act + Action act = () => + types.Should().NotBeDecoratedWith("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to not be decorated *.DummyClassAttribute *failure message*" + + ", but the attribute was found on the following types:*\"*.ClassWithAttribute\"."); + } + + [Fact] + public void When_injecting_a_null_predicate_into_TypeSelector_NotBeDecoratedWith_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassWithAttribute)); - // Act - Action act = () => types.Should() - .NotBeDecoratedWith(isMatchingAttributePredicate: null); + // Act + Action act = () => types.Should() + .NotBeDecoratedWith(isMatchingAttributePredicate: null); - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } - [Fact] - public void When_asserting_a_selection_of_types_with_unexpected_attribute_and_unexpected_attribute_property_it_fails() - { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_asserting_a_selection_of_types_with_unexpected_attribute_and_unexpected_attribute_property_it_fails() { - typeof(ClassWithoutAttribute), - typeof(ClassWithAttribute) - }); + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithoutAttribute), + typeof(ClassWithAttribute) + }); + + // Act + Action act = () => + types.Should() + .NotBeDecoratedWith( + a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to not be decorated with *.DummyClassAttribute that matches " + + "(a.Name == \"Expected\") * a.IsEnabled *failure message*, but a matching attribute was found " + + "on the following types:*\"*.ClassWithAttribute\"."); + } + } + + public class NotBeDecoratedWithOrInherit + { + [Fact] + public void When_asserting_a_selection_of_non_decorated_types_does_not_inherit_an_attribute_it_succeeds() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithoutAttribute), + typeof(OtherClassWithoutAttribute) + }); + + // Act + Action act = () => + types.Should().NotBeDecoratedWithOrInherit(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_a_selection_of_decorated_types_does_not_inherit_an_attribute_it_fails() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassWithoutAttribute), + typeof(ClassWithInheritedAttribute) + }); + + // Act + Action act = () => + types.Should().NotBeDecoratedWithOrInherit("we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to not be decorated with or inherit *.DummyClassAttribute *failure message*" + + ", but the attribute was found on the following types:*\"*.ClassWithInheritedAttribute\"."); + } + + [Fact] + public void When_a_selection_of_types_do_inherit_unexpected_attribute_with_the_expected_properties_it_succeeds() + { + // Arrange + var types = new TypeSelector(typeof(ClassWithInheritedAttribute)); - // Act - Action act = () => - types.Should() - .NotBeDecoratedWith( + // Act + Action act = () => types.Should() + .NotBeDecoratedWithOrInherit( a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to not be decorated with *.DummyClassAttribute that matches " + - "(a.Name == \"Expected\") * a.IsEnabled *failure message*, but a matching attribute was found " + - "on the following types:*\"*.ClassWithAttribute\"."); - } - - #endregion + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to not be decorated with or inherit *.DummyClassAttribute that matches " + + "(a.Name == \"Expected\") * a.IsEnabled *failure message*, but a matching attribute was found " + + "on the following types:*\"*.ClassWithInheritedAttribute\"."); + } - #region NotBeDecoratedWithOrInherit - - [Fact] - public void When_asserting_a_selection_of_non_decorated_types_does_not_inherit_an_attribute_it_succeeds() - { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_a_selection_of_types_do_not_inherit_unexpected_attribute_with_the_expected_properties_it_succeeds() { - typeof(ClassWithoutAttribute), - typeof(OtherClassWithoutAttribute) - }); - - // Act - Action act = () => - types.Should().NotBeDecoratedWithOrInherit(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_a_selection_of_decorated_types_does_not_inherit_an_attribute_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassWithoutAttribute), - typeof(ClassWithInheritedAttribute) - }); - - // Act - Action act = () => - types.Should().NotBeDecoratedWithOrInherit("we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to not be decorated with or inherit *.DummyClassAttribute *failure message*" + - ", but the attribute was found on the following types:*\"*.ClassWithInheritedAttribute\"."); - } - - [Fact] - public void When_a_selection_of_types_do_inherit_unexpected_attribute_with_the_expected_properties_it_succeeds() - { - // Arrange - var types = new TypeSelector(typeof(ClassWithInheritedAttribute)); - - // Act - Action act = () => types.Should() - .NotBeDecoratedWithOrInherit( - a => (a.Name == "Expected") && a.IsEnabled, "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to not be decorated with or inherit *.DummyClassAttribute that matches " + - "(a.Name == \"Expected\") * a.IsEnabled *failure message*, but a matching attribute was found " + - "on the following types:*\"*.ClassWithInheritedAttribute\"."); - } - - [Fact] - public void When_a_selection_of_types_do_not_inherit_unexpected_attribute_with_the_expected_properties_it_succeeds() - { - // Arrange - var types = new TypeSelector(typeof(ClassWithoutAttribute)); - - // Act - Action act = () => types.Should() - .NotBeDecoratedWithOrInherit(a => (a.Name == "Expected") && a.IsEnabled); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_injecting_a_null_predicate_into_TypeSelector_NotBeDecoratedWithOrInherit_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassWithAttribute)); - - // Act - Action act = () => types.Should() - .NotBeDecoratedWithOrInherit(isMatchingAttributePredicate: null); - - // Assert - act.Should().ThrowExactly() - .WithParameterName("isMatchingAttributePredicate"); - } - - #endregion - - #region BeInNamespace - - [Fact] - public void When_a_type_is_in_the_expected_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInDummyNamespace)); + // Arrange + var types = new TypeSelector(typeof(ClassWithoutAttribute)); - // Act - Action act = () => types.Should().BeInNamespace(nameof(DummyNamespace)); + // Act + Action act = () => types.Should() + .NotBeDecoratedWithOrInherit(a => (a.Name == "Expected") && a.IsEnabled); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_type_is_not_in_the_expected_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassInDummyNamespace), - typeof(ClassNotInDummyNamespace), - typeof(OtherClassNotInDummyNamespace) - }); - - // Act - Action act = () => - types.Should().BeInNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be in namespace \"DummyNamespace\" *failure message*, but the following types " + - "are in a different namespace:*\"*.ClassNotInDummyNamespace*.OtherClassNotInDummyNamespace\"."); - } - - [Fact] - public void When_a_type_is_in_the_expected_global_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInGlobalNamespace)); + [Fact] + public void When_injecting_a_null_predicate_into_TypeSelector_NotBeDecoratedWithOrInherit_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassWithAttribute)); - // Act - Action act = () => types.Should().BeInNamespace(null); + // Act + Action act = () => types.Should() + .NotBeDecoratedWithOrInherit(isMatchingAttributePredicate: null); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().ThrowExactly() + .WithParameterName("isMatchingAttributePredicate"); + } } - [Fact] - public void When_a_type_in_the_global_namespace_is_not_in_the_expected_namespace_it_should_throw() + public class BeInNamespace { - // Arrange - var types = new TypeSelector(typeof(ClassInGlobalNamespace)); + [Fact] + public void When_a_type_is_in_the_expected_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInDummyNamespace)); - // Act - Action act = () => types.Should().BeInNamespace(nameof(DummyNamespace)); + // Act + Action act = () => types.Should().BeInNamespace(nameof(DummyNamespace)); - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be in namespace \"DummyNamespace\", but the following types " + - "are in a different namespace:*\"ClassInGlobalNamespace\"."); - } - - [Fact] - public void When_a_type_is_not_in_the_expected_global_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassInDummyNamespace), - typeof(ClassNotInDummyNamespace), - typeof(OtherClassNotInDummyNamespace) - }); - - // Act - Action act = () => types.Should().BeInNamespace(null); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected all types to be in namespace , but the following types are in a different namespace:" + - "*\"*.ClassInDummyNamespace*.ClassNotInDummyNamespace*.OtherClassNotInDummyNamespace\"."); - } + // Assert + act.Should().NotThrow(); + } - #endregion + [Fact] + public void When_a_type_is_not_in_the_expected_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassNotInDummyNamespace), + typeof(OtherClassNotInDummyNamespace) + }); + + // Act + Action act = () => + types.Should().BeInNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be in namespace \"DummyNamespace\" *failure message*, but the following types " + + "are in a different namespace:*\"*.ClassNotInDummyNamespace*.OtherClassNotInDummyNamespace\"."); + } + + [Fact] + public void When_a_type_is_in_the_expected_global_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInGlobalNamespace)); - #region NotBeInNamespace + // Act + Action act = () => types.Should().BeInNamespace(null); - [Fact] - public void When_a_type_is_not_in_the_unexpected_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInDummyNamespace)); + // Assert + act.Should().NotThrow(); + } - // Act - Action act = () => - types.Should().NotBeInNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); + [Fact] + public void When_a_type_in_the_global_namespace_is_not_in_the_expected_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInGlobalNamespace)); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => types.Should().BeInNamespace(nameof(DummyNamespace)); - [Fact] - public void When_a_type_is_not_in_the_unexpected_parent_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be in namespace \"DummyNamespace\", but the following types " + + "are in a different namespace:*\"ClassInGlobalNamespace\"."); + } - // Act - Action act = () => types.Should().NotBeInNamespace(nameof(DummyNamespace)); + [Fact] + public void When_a_type_is_not_in_the_expected_global_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassNotInDummyNamespace), + typeof(OtherClassNotInDummyNamespace) + }); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => types.Should().BeInNamespace(null); - [Fact] - public void When_a_type_is_in_the_unexpected_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassInDummyNamespace), - typeof(ClassNotInDummyNamespace), - typeof(OtherClassNotInDummyNamespace) - }); - - // Act - Action act = () => - types.Should().NotBeInNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected no types to be in namespace \"DummyNamespace\" *failure message*" + - ", but the following types are in the namespace:*\"DummyNamespace.ClassInDummyNamespace\"."); + // Assert + act.Should().Throw() + .WithMessage( + "Expected all types to be in namespace , but the following types are in a different namespace:" + + "*\"*.ClassInDummyNamespace*.ClassNotInDummyNamespace*.OtherClassNotInDummyNamespace\"."); + } } - #endregion - - #region BeUnderNamespace - - [Fact] - public void When_a_type_is_under_the_expected_namespace_it_should_not_throw() + public class NotBeInNamespace { - // Arrange - var types = new TypeSelector(typeof(ClassInDummyNamespace)); + [Fact] + public void When_a_type_is_not_in_the_unexpected_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInDummyNamespace)); - // Act - Action act = () => types.Should().BeUnderNamespace(nameof(DummyNamespace)); + // Act + Action act = () => + types.Should().NotBeInNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_type_is_under_the_expected_nested_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); + [Fact] + public void When_a_type_is_not_in_the_unexpected_parent_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); - // Act - Action act = () => - types.Should().BeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); + // Act + Action act = () => types.Should().NotBeInNamespace(nameof(DummyNamespace)); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_type_is_under_the_expected_parent_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); + [Fact] + public void When_a_type_is_in_the_unexpected_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassNotInDummyNamespace), + typeof(OtherClassNotInDummyNamespace) + }); + + // Act + Action act = () => + types.Should().NotBeInNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected no types to be in namespace \"DummyNamespace\" *failure message*" + + ", but the following types are in the namespace:*\"DummyNamespace.ClassInDummyNamespace\"."); + } + } + + public class BeUnderNamespace + { + [Fact] + public void When_a_type_is_under_the_expected_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInDummyNamespace)); - // Act - Action act = () => types.Should().BeUnderNamespace(nameof(DummyNamespace)); + // Act + Action act = () => types.Should().BeUnderNamespace(nameof(DummyNamespace)); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_type_is_exactly_under_the_expected_global_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInGlobalNamespace)); + [Fact] + public void When_a_type_is_under_the_expected_nested_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); - // Act - Action act = () => types.Should().BeUnderNamespace(null); + // Act + Action act = () => + types.Should().BeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_type_is_under_the_expected_global_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_a_type_is_under_the_expected_parent_namespace_it_should_not_throw() { - typeof(ClassInDummyNamespace), - typeof(ClassNotInDummyNamespace), - typeof(OtherClassNotInDummyNamespace) - }); + // Arrange + var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); - // Act - Action act = () => types.Should().BeUnderNamespace(null); + // Act + Action act = () => types.Should().BeUnderNamespace(nameof(DummyNamespace)); - // Assert - act.Should().NotThrow(); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_a_type_only_shares_a_prefix_with_the_expected_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInDummyNamespaceTwo)); + [Fact] + public void When_a_type_is_exactly_under_the_expected_global_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInGlobalNamespace)); - // Act - Action act = () => - types.Should().BeUnderNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); + // Act + Action act = () => types.Should().BeUnderNamespace(null); - // Assert - act.Should().Throw() - .WithMessage("Expected the namespaces of all types to start with \"DummyNamespace\" *failure message*" + - ", but the namespaces of the following types do not start with it:*\"*.ClassInDummyNamespaceTwo\"."); - } + // Assert + act.Should().NotThrow(); + } - [Fact] - public void When_asserting_a_selection_of_types_not_under_a_namespace_is_under_that_namespace_it_fails() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassInDummyNamespace), - typeof(ClassInInnerDummyNamespace) - }); - - // Act - Action act = () => - types.Should().BeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected the namespaces of all types to start with \"DummyNamespace.InnerDummyNamespace\"" + - ", but the namespaces of the following types do not start with it:*\"*.ClassInDummyNamespace\"."); - } + [Fact] + public void When_a_type_is_under_the_expected_global_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassNotInDummyNamespace), + typeof(OtherClassNotInDummyNamespace) + }); + + // Act + Action act = () => types.Should().BeUnderNamespace(null); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_type_only_shares_a_prefix_with_the_expected_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInDummyNamespaceTwo)); - #endregion + // Act + Action act = () => + types.Should().BeUnderNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); - #region NotBeUnderNamespace + // Assert + act.Should().Throw() + .WithMessage("Expected the namespaces of all types to start with \"DummyNamespace\" *failure message*" + + ", but the namespaces of the following types do not start with it:*\"*.ClassInDummyNamespaceTwo\"."); + } - [Fact] - public void When_a_types_is_not_under_the_unexpected_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(new[] + [Fact] + public void When_asserting_a_selection_of_types_not_under_a_namespace_is_under_that_namespace_it_fails() { - typeof(ClassInDummyNamespace), - typeof(ClassNotInDummyNamespace), - typeof(OtherClassNotInDummyNamespace) - }); - - // Act - Action act = () => - types.Should().NotBeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassInInnerDummyNamespace) + }); - // Assert - act.Should().NotThrow(); - } + // Act + Action act = () => + types.Should().BeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); - [Fact] - public void When_a_type_is_under_the_unexpected_namespace_it_shold_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInDummyNamespace)); - - // Act - Action act = () => - types.Should().NotBeUnderNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected the namespaces of all types to not start with \"DummyNamespace\" *failure message*" + - ", but the namespaces of the following types start with it:*\"*.ClassInDummyNamespace\"."); - } - - [Fact] - public void When_a_type_is_under_the_unexpected_nested_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); - - // Act - Action act = () => - types.Should().NotBeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected the namespaces of all types to not start with \"DummyNamespace.InnerDummyNamespace\"" + - ", but the namespaces of the following types start with it:*\"*.ClassInInnerDummyNamespace\"."); + // Assert + act.Should().Throw() + .WithMessage( + "Expected the namespaces of all types to start with \"DummyNamespace.InnerDummyNamespace\"" + + ", but the namespaces of the following types do not start with it:*\"*.ClassInDummyNamespace\"."); + } } - [Fact] - public void When_a_type_is_under_the_unexpected_parent_namespace_it_should_throw() + public class NotBeUnderNamespace { - // Arrange - var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); - - // Act - Action act = () => types.Should().NotBeUnderNamespace(nameof(DummyNamespace)); + [Fact] + public void When_a_types_is_not_under_the_unexpected_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassNotInDummyNamespace), + typeof(OtherClassNotInDummyNamespace) + }); + + // Act + Action act = () => + types.Should().NotBeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_a_type_is_under_the_unexpected_namespace_it_shold_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInDummyNamespace)); + + // Act + Action act = () => + types.Should().NotBeUnderNamespace(nameof(DummyNamespace), "we want to test the failure {0}", "message"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected the namespaces of all types to not start with \"DummyNamespace\" *failure message*" + + ", but the namespaces of the following types start with it:*\"*.ClassInDummyNamespace\"."); + } + + [Fact] + public void When_a_type_is_under_the_unexpected_nested_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); + + // Act + Action act = () => + types.Should().NotBeUnderNamespace($"{nameof(DummyNamespace)}.{nameof(DummyNamespace.InnerDummyNamespace)}"); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected the namespaces of all types to not start with \"DummyNamespace.InnerDummyNamespace\"" + + ", but the namespaces of the following types start with it:*\"*.ClassInInnerDummyNamespace\"."); + } + + [Fact] + public void When_a_type_is_under_the_unexpected_parent_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInInnerDummyNamespace)); - // Assert - act.Should().Throw() - .WithMessage( - "Expected the namespaces of all types to not start with \"DummyNamespace\"" + - ", but the namespaces of the following types start with it:*\"*.ClassInInnerDummyNamespace\"."); - } + // Act + Action act = () => types.Should().NotBeUnderNamespace(nameof(DummyNamespace)); - [Fact] - public void When_a_type_is_under_the_unexpected_global_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInGlobalNamespace)); + // Assert + act.Should().Throw() + .WithMessage( + "Expected the namespaces of all types to not start with \"DummyNamespace\"" + + ", but the namespaces of the following types start with it:*\"*.ClassInInnerDummyNamespace\"."); + } - // Act - Action act = () => types.Should().NotBeUnderNamespace(null); + [Fact] + public void When_a_type_is_under_the_unexpected_global_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInGlobalNamespace)); - // Assert - act.Should().Throw() - .WithMessage( - "Expected the namespaces of all types to not start with " + - ", but the namespaces of the following types start with it:*\"ClassInGlobalNamespace\"."); - } + // Act + Action act = () => types.Should().NotBeUnderNamespace(null); - [Fact] - public void When_a_type_is_under_the_unexpected_parent_global_namespace_it_should_throw() - { - // Arrange - var types = new TypeSelector(new[] - { - typeof(ClassInDummyNamespace), - typeof(ClassNotInDummyNamespace), - typeof(OtherClassNotInDummyNamespace) - }); - - // Act - Action act = () => types.Should().NotBeUnderNamespace(null); - - // Assert - act.Should().Throw() - .WithMessage( - "Expected the namespaces of all types to not start with , but the namespaces of the following types " + - "start with it:*\"*.ClassInDummyNamespace*.ClassNotInDummyNamespace*.OtherClassNotInDummyNamespace\"."); - } + // Assert + act.Should().Throw() + .WithMessage( + "Expected the namespaces of all types to not start with " + + ", but the namespaces of the following types start with it:*\"ClassInGlobalNamespace\"."); + } - [Fact] - public void When_a_type_only_shares_a_prefix_with_the_unexpected_namespace_it_should_not_throw() - { - // Arrange - var types = new TypeSelector(typeof(ClassInDummyNamespaceTwo)); + [Fact] + public void When_a_type_is_under_the_unexpected_parent_global_namespace_it_should_throw() + { + // Arrange + var types = new TypeSelector(new[] + { + typeof(ClassInDummyNamespace), + typeof(ClassNotInDummyNamespace), + typeof(OtherClassNotInDummyNamespace) + }); + + // Act + Action act = () => types.Should().NotBeUnderNamespace(null); + + // Assert + act.Should().Throw() + .WithMessage( + "Expected the namespaces of all types to not start with , but the namespaces of the following types " + + "start with it:*\"*.ClassInDummyNamespace*.ClassNotInDummyNamespace*.OtherClassNotInDummyNamespace\"."); + } + + [Fact] + public void When_a_type_only_shares_a_prefix_with_the_unexpected_namespace_it_should_not_throw() + { + // Arrange + var types = new TypeSelector(typeof(ClassInDummyNamespaceTwo)); - // Act - Action act = () => types.Should().NotBeUnderNamespace(nameof(DummyNamespace)); + // Act + Action act = () => types.Should().NotBeUnderNamespace(nameof(DummyNamespace)); - // Assert - act.Should().NotThrow(); + // Assert + act.Should().NotThrow(); + } } - - #endregion } } From d1e431846672e1e2c5a429516952741172c68c5d Mon Sep 17 00:00:00 2001 From: ITaluone <44049228+ITaluone@users.noreply.github.com> Date: Mon, 25 Apr 2022 07:17:04 +0200 Subject: [PATCH 42/48] Fix coveralls badge (#1906) * Update README.md * Use branch master for coveralls badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c052de024c..2d2bca3217 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![](https://img.shields.io/nuget/dt/FluentAssertions.svg?label=nuget%20downloads)](https://www.nuget.org/packages/FluentAssertions) [![](https://img.shields.io/librariesio/dependents/nuget/FluentAssertions.svg?label=dependent%20libraries)](https://libraries.io/nuget/FluentAssertions) ![](https://img.shields.io/badge/release%20strategy-githubflow-orange.svg) -[![Coverage Status](https://coveralls.io/repos/github/fluentassertions/fluentassertions/badge.svg?branch=develop)](https://coveralls.io/github/fluentassertions/fluentassertions?branch=develop) +[![Coverage Status](https://coveralls.io/repos/github/fluentassertions/fluentassertions/badge.svg?branch=master)](https://coveralls.io/github/fluentassertions/fluentassertions?branch=master) # About this project A very extensive set of extension methods that allow you to more naturally specify the expected outcome of a TDD or BDD-style unit tests. Targets .NET Framework 4.7, as well as .NET Core 2.1, .NET Core 3.0, .NET 6, .NET Standard 2.0 and 2.1. From ec0bdf44c81232c5e682aefa8b6ed49d31247577 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger | alu-one Date: Mon, 25 Apr 2022 07:55:01 +0200 Subject: [PATCH 43/48] Fix codestyle issue `IDE0055` --- Src/FluentAssertions/Primitives/EnumAssertions.cs | 2 +- .../DataSetSpecs.cs | 2 +- .../DataTableSpecs.cs | 2 +- .../CollectionAssertionSpecs.Contain.cs | 2 +- .../Collections/CollectionAssertionSpecs.Equal.cs | 2 +- .../CollectionAssertionSpecs.HaveCount.cs | 2 +- .../CollectionAssertionSpecs.Satisfy.cs | 2 +- .../Primitives/DateTimeAssertionSpecs.cs | 12 ++++++------ .../Primitives/EnumAssertionSpecs.cs | 8 ++++---- .../Primitives/ObjectAssertionSpecs.cs | 4 ++-- .../StringAssertionSpecs.ContainEquivalentOf.cs | 2 +- .../Specialized/ExecutionTimeAssertionsSpecs.cs | 14 +++++++------- .../Types/MethodBaseAssertionSpecs.cs | 2 +- .../Types/TypeAssertionSpecs.HaveIndexer.cs | 2 +- .../Types/TypeAssertionSpecs.Implement.cs | 2 +- .../Xml/XDocumentAssertionSpecs.cs | 2 +- .../Xml/XmlNodeAssertionSpecs.cs | 2 +- 17 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Src/FluentAssertions/Primitives/EnumAssertions.cs b/Src/FluentAssertions/Primitives/EnumAssertions.cs index c6974a806b..0bbd7aea8c 100644 --- a/Src/FluentAssertions/Primitives/EnumAssertions.cs +++ b/Src/FluentAssertions/Primitives/EnumAssertions.cs @@ -177,7 +177,7 @@ public AndConstraint NotBeDefined(string because = "", params objec .FailWith("but it is.") .Then .ClearExpectation(); - + return new AndConstraint((TAssertions)this); } diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs index a3618cb0cd..f5f0dd4b7c 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataSetSpecs.cs @@ -648,7 +648,7 @@ public void When_data_set_table_count_has_expected_value_equivalence_test_should // Act & Assert dataSet.Should().HaveTableCount(correctTableCount); } - + [Fact] public void Null_data_set_fails() { diff --git a/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs b/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs index dd8c705488..61e5eaa055 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs +++ b/Tests/FluentAssertions.Equivalency.Specs/DataTableSpecs.cs @@ -821,7 +821,7 @@ public void When_data_table_has_expected_column_it_should_succeed() // Act & Assert dataTable.Should().HaveColumn(expectedColumnName); } - + [Fact] public void Null_data_table_has_no_columns_and_fail_the_test() { diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs index 868e32994b..715d7ff3c3 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Contain.cs @@ -238,7 +238,7 @@ public void When_asserting_collection_contains_values_according_to_predicate_but "Expected strings to contain (x == \"xxx\") because we're checking how it reacts to a null subject, but found ."); } } - + public class NotContain { [Fact] diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs index c187a458e1..053f71269c 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Equal.cs @@ -323,7 +323,7 @@ public void When_asserting_equality_with_a_collection_built_from_params_argument act.Should().NotThrow(); } } - + public class NotEqual { [Fact] diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs index a03935bd4a..c4608b52aa 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.HaveCount.cs @@ -176,7 +176,7 @@ public void When_counting_generic_collection_it_should_not_enumerate() collection.GetEnumeratorCallCount.Should().Be(0); } } - + public class NotHaveCount { [Fact] diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs index 516902ff65..ee67c2b44a 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.Satisfy.cs @@ -241,7 +241,7 @@ public void When_elements_are_integers_assertion_fails_then_failure_message_must *Index: 2, Element: 3"); } } - + private class SomeClass { public string Text { get; set; } diff --git a/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs index 6ea464c89d..c7c2a70a0b 100644 --- a/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/DateTimeAssertionSpecs.cs @@ -35,7 +35,7 @@ public void Should_fail_when_asserting_nullable_datetime_value_without_a_value_t action.Should().Throw(); } } - + public class NotHaveValue { [Fact] @@ -829,7 +829,7 @@ public void When_asserting_subject_datetime_is_before_the_same_datetime_it_shoul .WithMessage("Expected subject to be before <2016-06-04>, but found <2016-06-04>."); } } - + public class NotBeBefore { [Fact] @@ -875,7 +875,7 @@ public void When_asserting_subject_datetime_is_not_before_the_same_datetime_it_s act.Should().NotThrow(); } } - + public class BeOnOrBefore { [Fact] @@ -921,7 +921,7 @@ public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected .WithMessage("Expected subject to be on or before <2016-06-03>, but found <2016-06-04>."); } } - + public class NotBeOnOrBefore { [Fact] @@ -968,7 +968,7 @@ public void When_asserting_subject_datetime_is_not_on_or_before_earlier_expected act.Should().NotThrow(); } } - + public class BeAfter { [Fact] @@ -1015,7 +1015,7 @@ public void When_asserting_subject_datetime_is_after_the_same_expected_datetime_ .WithMessage("Expected subject to be after <2016-06-04>, but found <2016-06-04>."); } } - + public class NotBeAfter { [Fact] diff --git a/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs index ba40334cf4..ba7fd96f52 100644 --- a/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/EnumAssertionSpecs.cs @@ -260,7 +260,7 @@ public void When_nullable_enums_are_unequal_it_should_throw(MyEnum? subject, MyE .WithMessage("*because we want to test the failure message*"); } } - + public enum MyEnum { One = 1, @@ -584,7 +584,7 @@ public void When_nullable_enums_have_equal_names_it_should_throw(MyEnum? subject .WithMessage("*because we want to test the failure message*"); } } - + public class NotHaveSameNameAs { [Fact] @@ -643,7 +643,7 @@ public void When_nullable_enums_have_unequal_names_it_should_throw() .WithMessage("*because we want to test the failure message*"); } } - + public enum MyEnumOtherValue { One = 11, @@ -710,7 +710,7 @@ public void When_nullable_enum_is_null_it_should_throw() .WithMessage("*because we want to test the failure message*"); } } - + public class Match { [Fact] diff --git a/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs index ac1acef301..4f57dc2b2e 100644 --- a/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Primitives/ObjectAssertionSpecs.cs @@ -955,7 +955,7 @@ public void When_a_system_exception_is_asserted_to_be_serializable_it_should_com act.Should().NotThrow(); } } - + internal class UnserializableClass { public string Name { get; set; } @@ -1017,7 +1017,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("BirthDay", BirthDay); } } - + public class BeXmlSerializable { [Fact] diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs index 28f06caec2..088c66d9af 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.ContainEquivalentOf.cs @@ -336,7 +336,7 @@ public void When_string_containment_equivalent_of_at_most_once_is_asserted_and_a act.Should().NotThrow(); } } - + public class ContainEquivalentOfLessThan { [Fact] diff --git a/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs b/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs index a027e5f2b5..ecefaefb54 100644 --- a/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs +++ b/Tests/FluentAssertions.Specs/Specialized/ExecutionTimeAssertionsSpecs.cs @@ -73,7 +73,7 @@ public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_ther // Arrange Action someAction = () => { - // lets cause a deadlock + // lets cause a deadlock var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore semaphore.WaitOne(); // oops }; @@ -177,7 +177,7 @@ public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_ther // Arrange Action someAction = () => { - // lets cause a deadlock + // lets cause a deadlock var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore semaphore.WaitOne(); // oops }; @@ -254,7 +254,7 @@ public void When_action_runs_indefinitely_it_should_be_stopped_and_not_throw_if_ // Arrange Action someAction = () => { - // lets cause a deadlock + // lets cause a deadlock var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore semaphore.WaitOne(); // oops }; @@ -330,7 +330,7 @@ public void When_action_runs_indefinitely_it_should_be_stopped_and_not_throw_if_ // Arrange Action someAction = () => { - // lets cause a deadlock + // lets cause a deadlock var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore semaphore.WaitOne(); // oops }; @@ -425,7 +425,7 @@ public void When_action_runs_indefinitely_it_should_be_stopped_and_throw_if_ther // Arrange Action someAction = () => { - // lets cause a deadlock + // lets cause a deadlock var semaphore = new Semaphore(0, 1); // my weapon of choice is a semaphore semaphore.WaitOne(); // oops }; @@ -463,8 +463,8 @@ public void Stopwatch_is_not_stopped_after_first_execution_time_assertion() // Act Action act = () => { - // I know it's not meant to be used like this, - // but since you can, it should still give consistent results + // I know it's not meant to be used like this, + // but since you can, it should still give consistent results ExecutionTime time = someAction.ExecutionTime(); time.Should().BeGreaterThan(100.Milliseconds()); time.Should().BeGreaterThan(200.Milliseconds()); diff --git a/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs index 107a2bb2d9..6790e97c82 100644 --- a/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Types/MethodBaseAssertionSpecs.cs @@ -87,7 +87,7 @@ public void When_asserting_method_return_type_is_null_it_should_throw() .WithParameterName("returnType"); } } - + public class NotReturn { [Fact] diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs index 398bc5eeae..1df8bbdced 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.HaveIndexer.cs @@ -110,7 +110,7 @@ public void When_asserting_a_type_has_an_indexer_with_a_null_parameter_type_list .WithParameterName("parameterTypes"); } } - + public class NotHaveIndexer { [Fact] diff --git a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs index c1b06bf1bc..cff05ffd60 100644 --- a/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs +++ b/Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.Implement.cs @@ -74,7 +74,7 @@ public void When_asserting_a_type_to_implement_null_it_should_throw() .WithParameterName("interfaceType"); } } - + public class ImplementOfT { [Fact] diff --git a/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs index 611b108557..4c03f71d7c 100644 --- a/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XDocumentAssertionSpecs.cs @@ -363,7 +363,7 @@ public void When_a_document_is_equivalent_to_null_it_fails() "Expected theDocument to be equivalent to \"\" *failure message*" + ", but found ."); } - + [Fact] public void When_assertion_an_xml_document_is_equivalent_to_a_different_xml_document_with_different_namespace_prefix_it_should_succeed() { diff --git a/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs index 042ff0498b..4882f98d0f 100644 --- a/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Xml/XmlNodeAssertionSpecs.cs @@ -173,7 +173,7 @@ public void When_asserting_a_null_xml_node_is_not_null_it_should_fail_with_descr .WithMessage("Expected theDocument not to be because we want to test the failure message."); } } - + public class BeEquivalentTo { [Fact] From 717cfbb1ef681c082c219d4919aae1ecab739312 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger | alu-one Date: Mon, 25 Apr 2022 08:27:19 +0200 Subject: [PATCH 44/48] Disable compiler warning for `SA1601` for test projects --- Tests/FluentAssertions.Equivalency.Specs/.editorconfig | 2 ++ Tests/FluentAssertions.Specs/.editorconfig | 3 +++ 2 files changed, 5 insertions(+) diff --git a/Tests/FluentAssertions.Equivalency.Specs/.editorconfig b/Tests/FluentAssertions.Equivalency.Specs/.editorconfig index 436717d4cf..2863a4b34c 100644 --- a/Tests/FluentAssertions.Equivalency.Specs/.editorconfig +++ b/Tests/FluentAssertions.Equivalency.Specs/.editorconfig @@ -127,6 +127,8 @@ dotnet_diagnostic.SA1404.severity = none dotnet_diagnostic.SA1502.severity = none # SA1600: Elements should be documented dotnet_diagnostic.SA1600.severity = none +# SA1601: Partial elements should be documented +dotnet_diagnostic.SA1601.severity = none # SA1602: Enumeration items should be documented dotnet_diagnostic.SA1602.severity = none # SA1611: The documentation for parameter is missing diff --git a/Tests/FluentAssertions.Specs/.editorconfig b/Tests/FluentAssertions.Specs/.editorconfig index f86d2a19dd..96c16843ba 100644 --- a/Tests/FluentAssertions.Specs/.editorconfig +++ b/Tests/FluentAssertions.Specs/.editorconfig @@ -129,6 +129,8 @@ dotnet_diagnostic.SA1404.severity = none dotnet_diagnostic.SA1502.severity = none # SA1600: Elements should be documented dotnet_diagnostic.SA1600.severity = none +# SA1601: Partial elements should be documented +dotnet_diagnostic.SA1601.severity = none # SA1602: Enumeration items should be documented dotnet_diagnostic.SA1602.severity = none # SA1611: The documentation for parameter is missing @@ -139,5 +141,6 @@ dotnet_diagnostic.SA1615.severity = none # SA1005: Single line comments should begin with single space dotnet_diagnostic.SA1005.severity = suggestion + # ReSharper/Rider resharper_expression_is_always_null_highlighting=none From c98fb6332899bc2d96d174d735c69e1d23705ca8 Mon Sep 17 00:00:00 2001 From: Lukas Gasselsberger Date: Sun, 24 Apr 2022 19:49:13 +0200 Subject: [PATCH 45/48] Move all tests from `CollectionAssertionSpecs` to the appropriate files --- ...ectionAssertionSpecs.BeInAscendingOrder.cs | 636 +++++++ ...ctionAssertionSpecs.BeInDescendingOrder.cs | 483 +++++ ...llectionAssertionSpecs.CommonAssertions.cs | 383 ++++ .../Collections/CollectionAssertionSpecs.cs | 1552 ----------------- 4 files changed, 1502 insertions(+), 1552 deletions(-) create mode 100644 Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.CommonAssertions.cs delete mode 100644 Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.cs diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs index 696133e152..4d407d2346 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInAscendingOrder.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; using FluentAssertions.Execution; using Xunit; using Xunit.Sdk; @@ -93,6 +95,305 @@ public void Items_can_be_ordered_by_the_identity_function() // Assert action.Should().NotThrow(); } + + [Fact] + public void When_asserting_empty_collection_with_no_parameters_ordered_in_ascending_it_should_succeed() + { + // Arrange + var collection = new int[] { }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_empty_collection_by_property_expression_ordered_in_ascending_it_should_succeed() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Number); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_single_element_collection_with_no_parameters_ordered_in_ascending_it_should_succeed() + { + // Arrange + var collection = new int[] { 42 }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_single_element_collection_by_property_expression_ordered_in_ascending_it_should_succeed() + { + // Arrange + var collection = new SomeClass[] + { + new SomeClass { Text = "a", Number = 1 } + }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Number); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_using_the_specified_property_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Text, "it should be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*a*b*c*"); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*a*b*c*"); + } + + [Fact] + public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_using_the_specified_property_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Numeric); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Numeric, Comparer.Default); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_in_ascending_order_it_should_succeed() + { + // Arrange + string[] strings = { "alpha", "beta", "theta" }; + + // Act + Action act = () => strings.Should().BeInAscendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_ascending_order_it_should_throw() + { + // Arrange + string[] strings = { "theta", "alpha", "beta" }; + + // Act + Action act = () => strings.Should().BeInAscendingOrder("of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Expected*ascending*of reasons*index 0*"); + } + + [Fact] + public void When_strings_are_in_ascending_order_according_to_a_custom_comparer_it_should_succeed() + { + // Arrange + string[] strings = { "alpha", "beta", "theta" }; + + // Act + Action act = () => strings.Should().BeInAscendingOrder(new ByLastCharacterComparer()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_ascending_order_according_to_a_custom_comparer_it_should_throw() + { + // Arrange + string[] strings = { "dennis", "roy", "thomas" }; + + // Act + Action act = () => strings.Should().BeInAscendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Expected*ascending*of reasons*index 1*"); + } + + [Fact] + public void When_strings_are_in_ascending_order_according_to_a_custom_lambda_it_should_succeed() + { + // Arrange + string[] strings = { "alpha", "beta", "theta" }; + + // Act + Action act = () => strings.Should().BeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_ascending_order_according_to_a_custom_lambda_it_should_throw() + { + // Arrange + string[] strings = { "dennis", "roy", "thomas" }; + + // Act + Action act = () => strings.Should().BeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Expected*ascending*of reasons*index 1*"); + } + + [Fact] + public void When_asserting_the_items_in_a_null_collection_are_ordered_using_the_specified_property_it_should_throw() + { + // Arrange + const IEnumerable collection = null; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Text); + + // Assert + act.Should().Throw() + .WithMessage("*Text*found*null*"); + } + + [Fact] + public void When_asserting_the_items_in_a_null_collection_are_ordered_using_the_given_comparer_it_should_throw() + { + // Arrange + const IEnumerable collection = null; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(Comparer.Default); + + // Assert + act.Should().Throw() + .WithMessage("Expected*found*null*"); + } + + [Fact] + public void When_asserting_the_items_in_a_null_collection_are_ordered_using_the_specified_property_and_the_given_comparer_it_should_throw() + { + // Arrange + const IEnumerable collection = null; + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase); + + // Assert + act.Should().Throw() + .WithMessage("Expected*Text*found*null*"); + } + + [Fact] + public void When_asserting_the_items_in_a_collection_are_ordered_and_the_specified_property_is_null_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().BeInAscendingOrder((Expression>)null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert collection ordering without specifying a property*") + .WithParameterName("propertyExpression"); + } + + [Fact] + public void When_asserting_the_items_in_a_collection_are_ordered_and_the_given_comparer_is_null_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().BeInAscendingOrder(comparer: null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert collection ordering without specifying a comparer*") + .WithParameterName("comparer"); + } + + [Fact] + public void When_asserting_the_items_in_ay_collection_are_ordered_using_an_invalid_property_expression_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().BeInAscendingOrder(o => o.GetHashCode()); + + // Assert + act.Should().Throw() + .WithMessage("Expression*o.GetHashCode()*cannot be used to select a member*"); + } } public class NotBeInAscendingOrder @@ -160,6 +461,341 @@ public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_no .WithMessage("Did not expect collection to be in ascending order because numbers are not ordered," + " but found {1, 2, 2, 3}."); } + + [Fact] + public void When_asserting_empty_collection_by_property_expression_to_not_be_ordered_in_ascending_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Number); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection {empty} to not be ordered \"by Number\" and not result in {empty}."); + } + + [Fact] + public void When_asserting_empty_collection_with_no_parameters_not_be_ordered_in_ascending_it_should_throw() + { + // Arrange + var collection = new int[] { }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder("because I say {0}", "so"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to be in ascending order because I say so, but found {empty}."); + } + + [Fact] + public void When_asserting_single_element_collection_with_no_parameters_not_be_ordered_in_ascending_it_should_throw() + { + // Arrange + var collection = new int[] { 42 }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to be in ascending order, but found {42}."); + } + + [Fact] + public void When_asserting_single_element_collection_by_property_expression_to_not_be_ordered_in_ascending_it_should_throw() + { + // Arrange + var collection = new SomeClass[] + { + new SomeClass { Text = "a", Number = 1 } + }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Number); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_the_items_in_a_ascending_ordered_collection_are_not_ordered_ascending_using_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(Comparer.Default, "it should not be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to be in ascending order*should not be sorted*1*2*3*"); + } + + [Fact] + public void When_asserting_the_items_not_in_an_ascendingly_ordered_collection_are_not_ordered_ascending_using_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] { 3, 2, 1 }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(Comparer.Default); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_in_a_ascending_ordered_collection_are_not_ordered_ascending_using_the_specified_property_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "a", Numeric = 3 }, + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 } + }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Text, "it should not be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*a*b*c*not be ordered*Text*should not be sorted*a*b*c*"); + } + + [Fact] + public void When_asserting_the_items_in_an_ordered_collection_are_not_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "A", Numeric = 1 }, + new { Text = "b", Numeric = 2 }, + new { Text = "C", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should not be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*A*b*C*not be ordered*Text*should not be sorted*A*b*C*"); + } + + [Fact] + public void When_asserting_the_items_not_in_an_ascendingly_ordered_collection_are_not_ordered_ascending_using_the_specified_property_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 3 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 1 } + }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Numeric); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_not_in_an_ascendingly_ordered_collection_are_not_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 3 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 1 } + }; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Numeric, Comparer.Default); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_ascending_order_it_should_succeed() + { + // Arrange + string[] strings = { "beta", "alpha", "theta" }; + + // Act + Action act = () => strings.Should().NotBeInAscendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_in_ascending_order_unexpectedly_it_should_throw() + { + // Arrange + string[] strings = { "alpha", "beta", "theta" }; + + // Act + Action act = () => strings.Should().NotBeInAscendingOrder("of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Did not expect*ascending*of reasons*but found*"); + } + + [Fact] + public void When_strings_are_not_in_ascending_order_according_to_a_custom_comparer_it_should_succeed() + { + // Arrange + string[] strings = { "dennis", "roy", "barbara" }; + + // Act + Action act = () => strings.Should().NotBeInAscendingOrder(new ByLastCharacterComparer()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_unexpectedly_in_ascending_order_according_to_a_custom_comparer_it_should_throw() + { + // Arrange + string[] strings = { "dennis", "thomas", "roy" }; + + // Act + Action act = () => strings.Should().NotBeInAscendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Did not expect*ascending*of reasons*but found*"); + } + + [Fact] + public void When_strings_are_not_in_ascending_order_according_to_a_custom_lambda_it_should_succeed() + { + // Arrange + string[] strings = { "roy", "dennis", "thomas" }; + + // Act + Action act = () => strings.Should().NotBeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_unexpectedly_in_ascending_order_according_to_a_custom_lambda_it_should_throw() + { + // Arrange + string[] strings = { "barbara", "dennis", "roy" }; + + // Act + Action act = () => strings.Should().NotBeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Did not expect*ascending*of reasons*but found*"); + } + + [Fact] + public void When_asserting_the_items_in_a_null_collection_are_not_ordered_using_the_specified_property_it_should_throw() + { + // Arrange + const IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotBeInAscendingOrder(o => o.Text); + }; + + // Assert + act.Should().Throw() + .WithMessage("*Text*found*null*"); + } + + [Fact] + public void When_asserting_the_items_in_a_null_collection_are_not_ordered_using_the_given_comparer_it_should_throw() + { + // Arrange + const IEnumerable collection = null; + + // Act + Action act = () => + { + using var _ = new AssertionScope(); + collection.Should().NotBeInAscendingOrder(Comparer.Default); + }; + + // Assert + act.Should().Throw() + .WithMessage("*found*null*"); + } + + [Fact] + public void When_asserting_the_items_in_a_null_collection_are_not_ordered_using_the_specified_property_and_the_given_comparer_it_should_throw() + { + // Arrange + const IEnumerable collection = null; + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase); + + // Assert + act.Should().Throw() + .WithMessage("*Text*found*null*"); + } + + [Fact] + public void When_asserting_the_items_in_a_collection_are_not_ordered_and_the_specified_property_is_null_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder((Expression>)null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert collection ordering without specifying a property*propertyExpression*"); + } + + [Fact] + public void When_asserting_the_items_in_a_collection_are_not_ordered_and_the_given_comparer_is_null_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(comparer: null); + + // Assert + act.Should().Throw() + .WithMessage("Cannot assert collection ordering without specifying a comparer*comparer*"); + } + + [Fact] + public void When_asserting_the_items_in_ay_collection_are_not_ordered_using_an_invalid_property_expression_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().NotBeInAscendingOrder(o => o.GetHashCode()); + + // Assert + act.Should().Throw() + .WithMessage("Expression*o.GetHashCode()*cannot be used to select a member*"); + } } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs index be98a70524..fc5312909b 100644 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.BeInDescendingOrder.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using FluentAssertions.Execution; using Xunit; using Xunit.Sdk; @@ -36,6 +38,244 @@ public void When_asserting_the_items_in_an_unordered_collection_are_ordered_desc .WithMessage("Expected collection to be in descending order because letters are ordered," + " but found {\"z\", \"x\", \"y\"} where item at index 1 is in wrong order."); } + + [Fact] + public void When_asserting_empty_collection_by_property_expression_ordered_in_descending_it_should_succeed() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().BeInDescendingOrder(o => o.Number); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_empty_collection_with_no_parameters_ordered_in_descending_it_should_succeed() + { + // Arrange + var collection = new int[] { }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_single_element_collection_with_no_parameters_ordered_in_descending_it_should_succeed() + { + // Arrange + var collection = new int[] { 42 }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_single_element_collection_by_property_expression_ordered_in_descending_it_should_succeed() + { + // Arrange + var collection = new SomeClass[] + { + new SomeClass { Text = "a", Number = 1 } + }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(o => o.Number); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_using_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] { "z", "x", "y" }; + + // Act + Action action = () => collection.Should().BeInDescendingOrder(Comparer.Default, "because letters are ordered"); + + // Assert + action.Should().Throw() + .WithMessage("Expected collection to be in descending order because letters are ordered," + + " but found {\"z\", \"x\", \"y\"} where item at index 1 is in wrong order."); + } + + [Fact] + public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_using_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] { "z", "y", "x" }; + + // Act / Assert + collection.Should().BeInDescendingOrder(Comparer.Default); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_using_the_specified_property_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(o => o.Text, "it should be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*c*b*a*"); + } + + [Fact] + public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*c*b*a*"); + } + + [Fact] + public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_using_the_specified_property_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 3 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 1 } + }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(o => o.Numeric); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 3 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 1 } + }; + + // Act + Action act = () => collection.Should().BeInDescendingOrder(o => o.Numeric, Comparer.Default); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_in_descending_order_it_should_succeed() + { + // Arrange + string[] strings = { "theta", "beta", "alpha" }; + + // Act + Action act = () => strings.Should().BeInDescendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_descending_order_it_should_throw() + { + // Arrange + string[] strings = { "theta", "alpha", "beta" }; + + // Act + Action act = () => strings.Should().BeInDescendingOrder("of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Expected*descending*of reasons*index 1*"); + } + + [Fact] + public void When_strings_are_in_descending_order_based_on_a_custom_comparer_it_should_succeed() + { + // Arrange + string[] strings = { "roy", "dennis", "barbara" }; + + // Act + Action act = () => strings.Should().BeInDescendingOrder(new ByLastCharacterComparer()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_descending_order_based_on_a_custom_comparer_it_should_throw() + { + // Arrange + string[] strings = { "dennis", "roy", "barbara" }; + + // Act + Action act = () => strings.Should().BeInDescendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Expected*descending*of reasons*index 0*"); + } + + [Fact] + public void When_strings_are_in_descending_order_based_on_a_custom_lambda_it_should_succeed() + { + // Arrange + string[] strings = { "roy", "dennis", "barbara" }; + + // Act + Action act = () => strings.Should().BeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_descending_order_based_on_a_custom_lambda_it_should_throw() + { + // Arrange + string[] strings = { "dennis", "roy", "barbara" }; + + // Act + Action act = () => strings.Should().BeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Expected*descending*of reasons*index 0*"); + } } public class NotBeInDescendingOrder @@ -89,6 +329,249 @@ public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_ .WithMessage("Did not expect collection to be in descending order because numbers are not ordered," + " but found {\"c\", \"b\", \"a\"}."); } + + [Fact] + public void When_asserting_empty_collection_by_property_expression_to_not_be_ordered_in_descending_it_should_throw() + { + // Arrange + var collection = Enumerable.Empty(); + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Number); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection {empty} to not be ordered \"by Number\" and not result in {empty}."); + } + + [Fact] + public void When_asserting_empty_collection_with_no_parameters_not_be_ordered_in_descending_it_should_throw() + { + // Arrange + var collection = new int[] { }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder("because I say {0}", "so"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to be in descending order because I say so, but found {empty}."); + } + + [Fact] + public void When_asserting_single_element_collection_with_no_parameters_not_be_ordered_in_descending_it_should_throw() + { + // Arrange + var collection = new int[] { 42 }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to be in descending order, but found {42}."); + } + + [Fact] + public void When_asserting_single_element_collection_by_property_expression_to_not_be_ordered_in_descending_it_should_throw() + { + // Arrange + var collection = new SomeClass[] + { + new SomeClass { Text = "a", Number = 1 } + }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Number); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_ordered_descending_using_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] { 3, 2, 1 }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(Comparer.Default, "it should not be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Did not expect collection to be in descending order*should not be sorted*3*2*1*"); + } + + [Fact] + public void When_asserting_the_items_not_in_an_descendingly_ordered_collection_are_not_ordered_descending_using_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(Comparer.Default); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_ordered_descending_using_the_specified_property_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "c", Numeric = 3 }, + new { Text = "b", Numeric = 1 }, + new { Text = "a", Numeric = 2 } + }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Text, "it should not be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*b*c*a*not be ordered*Text*should not be sorted*c*b*a*"); + } + + [Fact] + public void When_asserting_the_items_in_an_ordered_collection_are_not_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_throw() + { + // Arrange + var collection = new[] + { + new { Text = "C", Numeric = 1 }, + new { Text = "b", Numeric = 2 }, + new { Text = "A", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should not be sorted"); + + // Assert + act.Should().Throw() + .WithMessage("Expected collection*C*b*A*not be ordered*Text*should not be sorted*C*b*A*"); + } + + [Fact] + public void When_asserting_the_items_not_in_an_descendingly_ordered_collection_are_not_ordered_descending_using_the_specified_property_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Numeric); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_asserting_the_items_not_in_an_descendingly_ordered_collection_are_not_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_succeed() + { + // Arrange + var collection = new[] + { + new { Text = "b", Numeric = 1 }, + new { Text = "c", Numeric = 2 }, + new { Text = "a", Numeric = 3 } + }; + + // Act + Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Numeric, Comparer.Default); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_not_in_descending_order_it_should_succeed() + { + // Arrange + string[] strings = { "beta", "theta", "alpha" }; + + // Act + Action act = () => strings.Should().NotBeInDescendingOrder(); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_unexpectedly_in_descending_order_it_should_throw() + { + // Arrange + string[] strings = { "theta", "beta", "alpha" }; + + // Act + Action act = () => strings.Should().NotBeInDescendingOrder("of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Did not expect*descending*of reasons*but found*"); + } + + [Fact] + public void When_strings_are_not_in_descending_order_based_on_a_custom_comparer_it_should_succeed() + { + // Arrange + string[] strings = { "roy", "barbara", "dennis" }; + + // Act + Action act = () => strings.Should().NotBeInDescendingOrder(new ByLastCharacterComparer()); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_unexpectedly_in_descending_order_based_on_a_custom_comparer_it_should_throw() + { + // Arrange + string[] strings = { "roy", "dennis", "barbara" }; + + // Act + Action act = () => strings.Should().NotBeInDescendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Did not expect*descending*of reasons*but found*"); + } + + [Fact] + public void When_strings_are_not_in_descending_order_based_on_a_custom_lambda_it_should_succeed() + { + // Arrange + string[] strings = { "dennis", "roy", "barbara" }; + + // Act + Action act = () => strings.Should().NotBeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); + + // Assert + act.Should().NotThrow(); + } + + [Fact] + public void When_strings_are_unexpectedly_in_descending_order_based_on_a_custom_lambda_it_should_throw() + { + // Arrange + string[] strings = { "roy", "dennis", "barbara" }; + + // Act + Action act = () => strings.Should().NotBeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); + + // Assert + act.Should() + .Throw() + .WithMessage("Did not expect*descending*of reasons*but found*"); + } } } } diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.CommonAssertions.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.CommonAssertions.cs new file mode 100644 index 0000000000..2d8123b618 --- /dev/null +++ b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.CommonAssertions.cs @@ -0,0 +1,383 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Sdk; + +namespace FluentAssertions.Specs.Collections +{ + /// + /// Collection assertion specs. + /// + public partial class CollectionAssertionSpecs + { + public class Chainings + { + [Fact] + public void Should_support_chaining_constraints_with_and() + { + // Arrange + var collection = new[] { 1, 2, 3 }; + + // Act / Assert + collection.Should() + .HaveCount(3) + .And + .HaveElementAt(1, 2) + .And + .NotContain(4); + } + + [Fact] + public void When_the_collection_is_ordered_according_to_the_subsequent_ascending_assertion_it_should_succeed() + { + // Arrange + var collection = new[] + { + (1, "a"), + (2, "b"), + (2, "c"), + (3, "a") + }; + + // Act + Action action = () => collection.Should() + .BeInAscendingOrder(x => x.Item1) + .And + .ThenBeInAscendingOrder(x => x.Item2); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_the_collection_is_not_ordered_according_to_the_subsequent_ascending_assertion_it_should_fail() + { + // Arrange + var collection = new[] + { + (1, "a"), + (2, "b"), + (2, "c"), + (3, "a") + }; + + // Act + Action action = () => collection.Should() + .BeInAscendingOrder(x => x.Item1) + .And + .BeInAscendingOrder(x => x.Item2); + + // Assert + action.Should().Throw() + .WithMessage("Expected collection * to be ordered \"by Item2\"*"); + } + + [Fact] + public void When_the_collection_is_ordered_according_to_the_subsequent_ascending_assertion_with_comparer_it_should_succeed() + { + // Arrange + var collection = new[] + { + (1, "a"), + (2, "B"), + (2, "b"), + (3, "a") + }; + + // Act + Action action = () => collection.Should() + .BeInAscendingOrder(x => x.Item1) + .And + .ThenBeInAscendingOrder(x => x.Item2, StringComparer.InvariantCultureIgnoreCase); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_the_collection_is_ordered_according_to_the_multiple_subsequent_ascending_assertions_it_should_succeed() + { + // Arrange + var collection = new[] + { + (1, "a", 1.1), + (2, "b", 1.2), + (2, "c", 1.3), + (3, "a", 1.1) + }; + + // Act + Action action = () => collection.Should() + .BeInAscendingOrder(x => x.Item1) + .And + .ThenBeInAscendingOrder(x => x.Item2) + .And + .ThenBeInAscendingOrder(x => x.Item3); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_the_collection_is_ordered_according_to_the_subsequent_descending_assertion_it_should_succeed() + { + // Arrange + var collection = new[] + { + (3, "a"), + (2, "c"), + (2, "b"), + (1, "a") + }; + + // Act + Action action = () => collection.Should() + .BeInDescendingOrder(x => x.Item1) + .And + .ThenBeInDescendingOrder(x => x.Item2); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_the_collection_is_not_ordered_according_to_the_subsequent_descending_assertion_it_should_fail() + { + // Arrange + var collection = new[] + { + (3, "a"), + (2, "c"), + (2, "b"), + (1, "a") + }; + + // Act + Action action = () => collection.Should() + .BeInDescendingOrder(x => x.Item1) + .And + .BeInDescendingOrder(x => x.Item2); + + // Assert + action.Should().Throw() + .WithMessage("Expected collection * to be ordered \"by Item2\"*"); + } + + [Fact] + public void When_the_collection_is_ordered_according_to_the_subsequent_descending_assertion_with_comparer_it_should_succeed() + { + // Arrange + var collection = new[] + { + (3, "a"), + (2, "b"), + (2, "B"), + (1, "a") + }; + + // Act + Action action = () => collection.Should() + .BeInDescendingOrder(x => x.Item1) + .And + .ThenBeInDescendingOrder(x => x.Item2, StringComparer.InvariantCultureIgnoreCase); + + // Assert + action.Should().NotThrow(); + } + + [Fact] + public void When_the_collection_is_ordered_according_to_the_multiple_subsequent_descending_assertions_it_should_succeed() + { + // Arrange + var collection = new[] + { + (3, "a", 1.1), + (2, "c", 1.3), + (2, "b", 1.2), + (1, "a", 1.1) + }; + + // Act + Action action = () => collection.Should() + .BeInDescendingOrder(x => x.Item1) + .And + .ThenBeInDescendingOrder(x => x.Item2) + .And + .ThenBeInDescendingOrder(x => x.Item3); + + // Assert + action.Should().NotThrow(); + } + } + + private class ByLastCharacterComparer : IComparer + { + public int Compare(string x, string y) + { + return x.Last().CompareTo(y.Last()); + } + } + } + + internal class CountingGenericEnumerable : IEnumerable + { + private readonly IEnumerable backingSet; + + public CountingGenericEnumerable(IEnumerable backingSet) + { + this.backingSet = backingSet; + GetEnumeratorCallCount = 0; + } + + public int GetEnumeratorCallCount { get; private set; } + + public IEnumerator GetEnumerator() + { + GetEnumeratorCallCount++; + return backingSet.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal class CountingGenericCollection : ICollection + { + private readonly ICollection backingSet; + + public CountingGenericCollection(ICollection backingSet) + { + this.backingSet = backingSet; + } + + public int GetEnumeratorCallCount { get; private set; } + + public IEnumerator GetEnumerator() + { + GetEnumeratorCallCount++; + return backingSet.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(TElement item) { throw new NotImplementedException(); } + + public void Clear() { throw new NotImplementedException(); } + + public bool Contains(TElement item) { throw new NotImplementedException(); } + + public void CopyTo(TElement[] array, int arrayIndex) { throw new NotImplementedException(); } + + public bool Remove(TElement item) { throw new NotImplementedException(); } + + public int GetCountCallCount { get; private set; } + + public int Count + { + get + { + GetCountCallCount++; + return backingSet.Count; + } + } + + public bool IsReadOnly { get; private set; } + } + + internal class TrackingTestEnumerable : IEnumerable + { + private readonly int[] values; + + public TrackingTestEnumerable(params int[] values) + { + this.values = values; + Enumerator = new TrackingEnumerator(this.values); + } + + public TrackingEnumerator Enumerator { get; } + + public IEnumerator GetEnumerator() + { + Enumerator.IncreaseEnumerationCount(); + Enumerator.Reset(); + return Enumerator; + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + internal class TrackingEnumerator : IEnumerator + { + private readonly int[] values; + private int loopCount; + private int index; + + public TrackingEnumerator(int[] values) + { + index = -1; + + this.values = values; + } + + public int LoopCount + { + get { return loopCount; } + } + + public void IncreaseEnumerationCount() + { + loopCount++; + } + + public bool MoveNext() + { + index++; + return index < values.Length; + } + + public void Reset() + { + index = -1; + } + + public void Dispose() { } + + object IEnumerator.Current => Current; + + public int Current => values[index]; + } + + internal class OneTimeEnumerable : IEnumerable + { + private readonly IEnumerable items; + private int enumerations; + + public OneTimeEnumerable(params T[] items) => this.items = items; + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public IEnumerator GetEnumerator() + { + if (enumerations++ > 0) + { + throw new InvalidOperationException("OneTimeEnumerable can be enumerated one time only"); + } + + return items.GetEnumerator(); + } + } + + internal class SomeClass + { + public string Text { get; set; } + + public int Number { get; set; } + } +} diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.cs deleted file mode 100644 index 8adc525437..0000000000 --- a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.cs +++ /dev/null @@ -1,1552 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using FluentAssertions.Execution; -using Xunit; -using Xunit.Sdk; - -namespace FluentAssertions.Specs.Collections -{ - /// - /// Collection assertion specs. - /// - public partial class CollectionAssertionSpecs - { - [Fact] - public void Should_support_chaining_constraints_with_and() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act / Assert - collection.Should() - .HaveCount(3) - .And - .HaveElementAt(1, 2) - .And.NotContain(4); - } - - #region Be In Ascending/Descending Order - - #region Empty Collection - is always ordered, in both directions - - [Fact] - public void When_asserting_empty_collection_with_no_parameters_ordered_in_ascending_it_should_succeed() - { - // Arrange - var collection = new int[] { }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_empty_collection_with_no_parameters_not_be_ordered_in_ascending_it_should_throw() - { - // Arrange - var collection = new int[] { }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder("because I say {0}", "so"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to be in ascending order because I say so, but found {empty}."); - } - - [Fact] - public void When_asserting_empty_collection_with_no_parameters_ordered_in_descending_it_should_succeed() - { - // Arrange - var collection = new int[] { }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_empty_collection_with_no_parameters_not_be_ordered_in_descending_it_should_throw() - { - // Arrange - var collection = new int[] { }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder("because I say {0}", "so"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to be in descending order because I say so, but found {empty}."); - } - - [Fact] - public void When_asserting_empty_collection_by_property_expression_ordered_in_ascending_it_should_succeed() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Number); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_empty_collection_by_property_expression_to_not_be_ordered_in_ascending_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Number); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection {empty} to not be ordered \"by Number\" and not result in {empty}."); - } - - [Fact] - public void When_asserting_empty_collection_by_property_expression_ordered_in_descending_it_should_succeed() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().BeInDescendingOrder(o => o.Number); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_empty_collection_by_property_expression_to_not_be_ordered_in_descending_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Number); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection {empty} to not be ordered \"by Number\" and not result in {empty}."); - } - - #endregion - - #region Single Element Collection - is always ordered, in both directions - - [Fact] - public void When_asserting_single_element_collection_with_no_parameters_ordered_in_ascending_it_should_succeed() - { - // Arrange - var collection = new int[] { 42 }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_single_element_collection_with_no_parameters_not_be_ordered_in_ascending_it_should_throw() - { - // Arrange - var collection = new int[] { 42 }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to be in ascending order, but found {42}."); - } - - [Fact] - public void When_asserting_single_element_collection_with_no_parameters_ordered_in_descending_it_should_succeed() - { - // Arrange - var collection = new int[] { 42 }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_single_element_collection_with_no_parameters_not_be_ordered_in_descending_it_should_throw() - { - // Arrange - var collection = new int[] { 42 }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to be in descending order, but found {42}."); - } - - [Fact] - public void When_asserting_single_element_collection_by_property_expression_ordered_in_ascending_it_should_succeed() - { - // Arrange - var collection = new SomeClass[] - { - new SomeClass { Text = "a", Number = 1 } - }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Number); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_single_element_collection_by_property_expression_to_not_be_ordered_in_ascending_it_should_throw() - { - // Arrange - var collection = new SomeClass[] - { - new SomeClass { Text = "a", Number = 1 } - }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Number); - - // Assert - act.Should().Throw(); - } - - [Fact] - public void When_asserting_single_element_collection_by_property_expression_ordered_in_descending_it_should_succeed() - { - // Arrange - var collection = new SomeClass[] - { - new SomeClass { Text = "a", Number = 1 } - }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(o => o.Number); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_single_element_collection_by_property_expression_to_not_be_ordered_in_descending_it_should_throw() - { - // Arrange - var collection = new SomeClass[] - { - new SomeClass { Text = "a", Number = 1 } - }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Number); - - // Assert - act.Should().Throw(); - } - - #endregion - - #region Multi Element Collection - No Parameter / Comparer - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_using_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] { "z", "x", "y" }; - - // Act - Action action = () => collection.Should().BeInDescendingOrder(Comparer.Default, "because letters are ordered"); - - // Assert - action.Should().Throw() - .WithMessage("Expected collection to be in descending order because letters are ordered," + - " but found {\"z\", \"x\", \"y\"} where item at index 1 is in wrong order."); - } - - [Fact] - public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_using_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] { "z", "y", "x" }; - - // Act / Assert - collection.Should().BeInDescendingOrder(Comparer.Default); - } - - [Fact] - public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_ordered_descending_using_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] { 3, 2, 1 }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(Comparer.Default, "it should not be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to be in descending order*should not be sorted*3*2*1*"); - } - - [Fact] - public void When_asserting_the_items_not_in_an_descendingly_ordered_collection_are_not_ordered_descending_using_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(Comparer.Default); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_in_a_ascending_ordered_collection_are_not_ordered_ascending_using_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] { 1, 2, 3 }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(Comparer.Default, "it should not be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Did not expect collection to be in ascending order*should not be sorted*1*2*3*"); - } - - [Fact] - public void When_asserting_the_items_not_in_an_ascendingly_ordered_collection_are_not_ordered_ascending_using_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] { 3, 2, 1 }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(Comparer.Default); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region Multi Element Collection - Property Expression - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_using_the_specified_property_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Text, "it should be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*a*b*c*"); - } - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*a*b*c*"); - } - - [Fact] - public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_using_the_specified_property_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Numeric); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_in_an_ascendingly_ordered_collection_are_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Numeric, Comparer.Default); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_using_the_specified_property_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(o => o.Text, "it should be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*c*b*a*"); - } - - [Fact] - public void When_asserting_the_items_in_an_unordered_collection_are_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*b*c*a*ordered*Text*should be sorted*c*b*a*"); - } - - [Fact] - public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_using_the_specified_property_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 3 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 1 } - }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(o => o.Numeric); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_in_an_descendingly_ordered_collection_are_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 3 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 1 } - }; - - // Act - Action act = () => collection.Should().BeInDescendingOrder(o => o.Numeric, Comparer.Default); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_in_a_descending_ordered_collection_are_not_ordered_descending_using_the_specified_property_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "c", Numeric = 3 }, - new { Text = "b", Numeric = 1 }, - new { Text = "a", Numeric = 2 } - }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Text, "it should not be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*b*c*a*not be ordered*Text*should not be sorted*c*b*a*"); - } - - [Fact] - public void When_asserting_the_items_in_an_ordered_collection_are_not_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "C", Numeric = 1 }, - new { Text = "b", Numeric = 2 }, - new { Text = "A", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should not be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*C*b*A*not be ordered*Text*should not be sorted*C*b*A*"); - } - - [Fact] - public void When_asserting_the_items_not_in_an_descendingly_ordered_collection_are_not_ordered_descending_using_the_specified_property_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Numeric); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_not_in_an_descendingly_ordered_collection_are_not_ordered_descending_using_the_specified_property_and_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().NotBeInDescendingOrder(o => o.Numeric, Comparer.Default); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_in_a_ascending_ordered_collection_are_not_ordered_ascending_using_the_specified_property_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "a", Numeric = 3 }, - new { Text = "b", Numeric = 1 }, - new { Text = "c", Numeric = 2 } - }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Text, "it should not be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*a*b*c*not be ordered*Text*should not be sorted*a*b*c*"); - } - - [Fact] - public void When_asserting_the_items_in_an_ordered_collection_are_not_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_throw() - { - // Arrange - var collection = new[] - { - new { Text = "A", Numeric = 1 }, - new { Text = "b", Numeric = 2 }, - new { Text = "C", Numeric = 3 } - }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase, "it should not be sorted"); - - // Assert - act.Should().Throw() - .WithMessage("Expected collection*A*b*C*not be ordered*Text*should not be sorted*A*b*C*"); - } - - [Fact] - public void When_asserting_the_items_not_in_an_ascendingly_ordered_collection_are_not_ordered_ascending_using_the_specified_property_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 3 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 1 } - }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Numeric); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_asserting_the_items_not_in_an_ascendingly_ordered_collection_are_not_ordered_ascending_using_the_specified_property_and_the_given_comparer_it_should_succeed() - { - // Arrange - var collection = new[] - { - new { Text = "b", Numeric = 3 }, - new { Text = "c", Numeric = 2 }, - new { Text = "a", Numeric = 1 } - }; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Numeric, Comparer.Default); - - // Assert - act.Should().NotThrow(); - } - - #endregion - - #region Multi Element Collection - Using Lambda - - #region Be In Ascending Order - - [Fact] - public void When_strings_are_in_ascending_order_it_should_succeed() - { - // Arrange - string[] strings = { "alpha", "beta", "theta" }; - - // Act - Action act = () => strings.Should().BeInAscendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_not_in_ascending_order_it_should_throw() - { - // Arrange - string[] strings = { "theta", "alpha", "beta" }; - - // Act - Action act = () => strings.Should().BeInAscendingOrder("of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Expected*ascending*of reasons*index 0*"); - } - - [Fact] - public void When_strings_are_in_ascending_order_according_to_a_custom_comparer_it_should_succeed() - { - // Arrange - string[] strings = { "alpha", "beta", "theta" }; - - // Act - Action act = () => strings.Should().BeInAscendingOrder(new ByLastCharacterComparer()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_not_in_ascending_order_according_to_a_custom_comparer_it_should_throw() - { - // Arrange - string[] strings = { "dennis", "roy", "thomas" }; - - // Act - Action act = () => strings.Should().BeInAscendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Expected*ascending*of reasons*index 1*"); - } - - [Fact] - public void When_strings_are_in_ascending_order_according_to_a_custom_lambda_it_should_succeed() - { - // Arrange - string[] strings = { "alpha", "beta", "theta" }; - - // Act - Action act = () => strings.Should().BeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_not_in_ascending_order_according_to_a_custom_lambda_it_should_throw() - { - // Arrange - string[] strings = { "dennis", "roy", "thomas" }; - - // Act - Action act = () => strings.Should().BeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Expected*ascending*of reasons*index 1*"); - } - - #endregion - - #region Not Be In Ascending Order - - [Fact] - public void When_strings_are_not_in_ascending_order_it_should_succeed() - { - // Arrange - string[] strings = { "beta", "alpha", "theta" }; - - // Act - Action act = () => strings.Should().NotBeInAscendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_in_ascending_order_unexpectedly_it_should_throw() - { - // Arrange - string[] strings = { "alpha", "beta", "theta" }; - - // Act - Action act = () => strings.Should().NotBeInAscendingOrder("of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Did not expect*ascending*of reasons*but found*"); - } - - [Fact] - public void When_strings_are_not_in_ascending_order_according_to_a_custom_comparer_it_should_succeed() - { - // Arrange - string[] strings = { "dennis", "roy", "barbara" }; - - // Act - Action act = () => strings.Should().NotBeInAscendingOrder(new ByLastCharacterComparer()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_unexpectedly_in_ascending_order_according_to_a_custom_comparer_it_should_throw() - { - // Arrange - string[] strings = { "dennis", "thomas", "roy" }; - - // Act - Action act = () => strings.Should().NotBeInAscendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Did not expect*ascending*of reasons*but found*"); - } - - [Fact] - public void When_strings_are_not_in_ascending_order_according_to_a_custom_lambda_it_should_succeed() - { - // Arrange - string[] strings = { "roy", "dennis", "thomas" }; - - // Act - Action act = () => strings.Should().NotBeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_unexpectedly_in_ascending_order_according_to_a_custom_lambda_it_should_throw() - { - // Arrange - string[] strings = { "barbara", "dennis", "roy" }; - - // Act - Action act = () => strings.Should().NotBeInAscendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Did not expect*ascending*of reasons*but found*"); - } - - #endregion - - #region Be In Descending Order - - [Fact] - public void When_strings_are_in_descending_order_it_should_succeed() - { - // Arrange - string[] strings = { "theta", "beta", "alpha" }; - - // Act - Action act = () => strings.Should().BeInDescendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_not_in_descending_order_it_should_throw() - { - // Arrange - string[] strings = { "theta", "alpha", "beta" }; - - // Act - Action act = () => strings.Should().BeInDescendingOrder("of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Expected*descending*of reasons*index 1*"); - } - - [Fact] - public void When_strings_are_in_descending_order_based_on_a_custom_comparer_it_should_succeed() - { - // Arrange - string[] strings = { "roy", "dennis", "barbara" }; - - // Act - Action act = () => strings.Should().BeInDescendingOrder(new ByLastCharacterComparer()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_not_in_descending_order_based_on_a_custom_comparer_it_should_throw() - { - // Arrange - string[] strings = { "dennis", "roy", "barbara" }; - - // Act - Action act = () => strings.Should().BeInDescendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Expected*descending*of reasons*index 0*"); - } - - [Fact] - public void When_strings_are_in_descending_order_based_on_a_custom_lambda_it_should_succeed() - { - // Arrange - string[] strings = { "roy", "dennis", "barbara" }; - - // Act - Action act = () => strings.Should().BeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_not_in_descending_order_based_on_a_custom_lambda_it_should_throw() - { - // Arrange - string[] strings = { "dennis", "roy", "barbara" }; - - // Act - Action act = () => strings.Should().BeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Expected*descending*of reasons*index 0*"); - } - - #endregion - - #region Not Be In Descending Order - - [Fact] - public void When_strings_are_not_in_descending_order_it_should_succeed() - { - // Arrange - string[] strings = { "beta", "theta", "alpha" }; - - // Act - Action act = () => strings.Should().NotBeInDescendingOrder(); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_unexpectedly_in_descending_order_it_should_throw() - { - // Arrange - string[] strings = { "theta", "beta", "alpha" }; - - // Act - Action act = () => strings.Should().NotBeInDescendingOrder("of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Did not expect*descending*of reasons*but found*"); - } - - [Fact] - public void When_strings_are_not_in_descending_order_based_on_a_custom_comparer_it_should_succeed() - { - // Arrange - string[] strings = { "roy", "barbara", "dennis" }; - - // Act - Action act = () => strings.Should().NotBeInDescendingOrder(new ByLastCharacterComparer()); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_unexpectedly_in_descending_order_based_on_a_custom_comparer_it_should_throw() - { - // Arrange - string[] strings = { "roy", "dennis", "barbara" }; - - // Act - Action act = () => strings.Should().NotBeInDescendingOrder(new ByLastCharacterComparer(), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Did not expect*descending*of reasons*but found*"); - } - - [Fact] - public void When_strings_are_not_in_descending_order_based_on_a_custom_lambda_it_should_succeed() - { - // Arrange - string[] strings = { "dennis", "roy", "barbara" }; - - // Act - Action act = () => strings.Should().NotBeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last())); - - // Assert - act.Should().NotThrow(); - } - - [Fact] - public void When_strings_are_unexpectedly_in_descending_order_based_on_a_custom_lambda_it_should_throw() - { - // Arrange - string[] strings = { "roy", "dennis", "barbara" }; - - // Act - Action act = () => strings.Should().NotBeInDescendingOrder((sut, exp) => sut.Last().CompareTo(exp.Last()), "of {0}", "reasons"); - - // Assert - act.Should() - .Throw() - .WithMessage("Did not expect*descending*of reasons*but found*"); - } - - private class ByLastCharacterComparer : IComparer - { - public int Compare(string x, string y) - { - return x.Last().CompareTo(y.Last()); - } - } - - #endregion - - #endregion - - #region Null Collection - - [Fact] - public void When_asserting_the_items_in_a_null_collection_are_not_ordered_using_the_specified_property_it_should_throw() - { - // Arrange - const IEnumerable collection = null; - - // Act - Action act = () => - { - using var _ = new AssertionScope(); - collection.Should().NotBeInAscendingOrder(o => o.Text); - }; - - // Assert - act.Should().Throw() - .WithMessage("*Text*found*null*"); - } - - [Fact] - public void When_asserting_the_items_in_a_null_collection_are_not_ordered_using_the_given_comparer_it_should_throw() - { - // Arrange - const IEnumerable collection = null; - - // Act - Action act = () => - { - using var _ = new AssertionScope(); - collection.Should().NotBeInAscendingOrder(Comparer.Default); - }; - - // Assert - act.Should().Throw() - .WithMessage("*found*null*"); - } - - [Fact] - public void When_asserting_the_items_in_a_null_collection_are_not_ordered_using_the_specified_property_and_the_given_comparer_it_should_throw() - { - // Arrange - const IEnumerable collection = null; - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase); - - // Assert - act.Should().Throw() - .WithMessage("*Text*found*null*"); - } - - [Fact] - public void When_asserting_the_items_in_a_null_collection_are_ordered_using_the_specified_property_it_should_throw() - { - // Arrange - const IEnumerable collection = null; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Text); - - // Assert - act.Should().Throw() - .WithMessage("*Text*found*null*"); - } - - [Fact] - public void When_asserting_the_items_in_a_null_collection_are_ordered_using_the_given_comparer_it_should_throw() - { - // Arrange - const IEnumerable collection = null; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(Comparer.Default); - - // Assert - act.Should().Throw() - .WithMessage("Expected*found*null*"); - } - - [Fact] - public void When_asserting_the_items_in_a_null_collection_are_ordered_using_the_specified_property_and_the_given_comparer_it_should_throw() - { - // Arrange - const IEnumerable collection = null; - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.Text, StringComparer.OrdinalIgnoreCase); - - // Assert - act.Should().Throw() - .WithMessage("Expected*Text*found*null*"); - } - - #endregion - - #region Null Parameter - - [Fact] - public void When_asserting_the_items_in_a_collection_are_ordered_and_the_specified_property_is_null_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().BeInAscendingOrder((Expression>)null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert collection ordering without specifying a property*") - .WithParameterName("propertyExpression"); - } - - [Fact] - public void When_asserting_the_items_in_a_collection_are_ordered_and_the_given_comparer_is_null_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().BeInAscendingOrder(comparer: null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert collection ordering without specifying a comparer*") - .WithParameterName("comparer"); - } - - [Fact] - public void When_asserting_the_items_in_a_collection_are_not_ordered_and_the_specified_property_is_null_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder((Expression>)null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert collection ordering without specifying a property*propertyExpression*"); - } - - [Fact] - public void When_asserting_the_items_in_a_collection_are_not_ordered_and_the_given_comparer_is_null_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(comparer: null); - - // Assert - act.Should().Throw() - .WithMessage("Cannot assert collection ordering without specifying a comparer*comparer*"); - } - - #endregion - - #region Invalid Expression - - [Fact] - public void When_asserting_the_items_in_ay_collection_are_ordered_using_an_invalid_property_expression_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().BeInAscendingOrder(o => o.GetHashCode()); - - // Assert - act.Should().Throw() - .WithMessage("Expression*o.GetHashCode()*cannot be used to select a member*"); - } - - [Fact] - public void When_asserting_the_items_in_ay_collection_are_not_ordered_using_an_invalid_property_expression_it_should_throw() - { - // Arrange - var collection = Enumerable.Empty(); - - // Act - Action act = () => collection.Should().NotBeInAscendingOrder(o => o.GetHashCode()); - - // Assert - act.Should().Throw() - .WithMessage("Expression*o.GetHashCode()*cannot be used to select a member*"); - } - - #endregion - - #region Then be in order - - [Fact] - public void When_the_collection_is_ordered_according_to_the_subsequent_ascending_assertion_it_should_succeed() - { - // Arrange - var collection = new[] - { - (1, "a"), - (2, "b"), - (2, "c"), - (3, "a") - }; - - // Act - Action action = () => collection.Should() - .BeInAscendingOrder(x => x.Item1) - .And - .ThenBeInAscendingOrder(x => x.Item2); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_the_collection_is_not_ordered_according_to_the_subsequent_ascending_assertion_it_should_fail() - { - // Arrange - var collection = new[] - { - (1, "a"), - (2, "b"), - (2, "c"), - (3, "a") - }; - - // Act - Action action = () => collection.Should() - .BeInAscendingOrder(x => x.Item1) - .And - .BeInAscendingOrder(x => x.Item2); - - // Assert - action.Should().Throw() - .WithMessage("Expected collection * to be ordered \"by Item2\"*"); - } - - [Fact] - public void When_the_collection_is_ordered_according_to_the_subsequent_ascending_assertion_with_comparer_it_should_succeed() - { - // Arrange - var collection = new[] - { - (1, "a"), - (2, "B"), - (2, "b"), - (3, "a") - }; - - // Act - Action action = () => collection.Should() - .BeInAscendingOrder(x => x.Item1) - .And - .ThenBeInAscendingOrder(x => x.Item2, StringComparer.InvariantCultureIgnoreCase); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_the_collection_is_ordered_according_to_the_multiple_subsequent_ascending_assertions_it_should_succeed() - { - // Arrange - var collection = new[] - { - (1, "a", 1.1), - (2, "b", 1.2), - (2, "c", 1.3), - (3, "a", 1.1) - }; - - // Act - Action action = () => collection.Should() - .BeInAscendingOrder(x => x.Item1) - .And - .ThenBeInAscendingOrder(x => x.Item2) - .And - .ThenBeInAscendingOrder(x => x.Item3); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_the_collection_is_ordered_according_to_the_subsequent_descending_assertion_it_should_succeed() - { - // Arrange - var collection = new[] - { - (3, "a"), - (2, "c"), - (2, "b"), - (1, "a") - }; - - // Act - Action action = () => collection.Should() - .BeInDescendingOrder(x => x.Item1) - .And - .ThenBeInDescendingOrder(x => x.Item2); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_the_collection_is_not_ordered_according_to_the_subsequent_descending_assertion_it_should_fail() - { - // Arrange - var collection = new[] - { - (3, "a"), - (2, "c"), - (2, "b"), - (1, "a") - }; - - // Act - Action action = () => collection.Should() - .BeInDescendingOrder(x => x.Item1) - .And - .BeInDescendingOrder(x => x.Item2); - - // Assert - action.Should().Throw() - .WithMessage("Expected collection * to be ordered \"by Item2\"*"); - } - - [Fact] - public void When_the_collection_is_ordered_according_to_the_subsequent_descending_assertion_with_comparer_it_should_succeed() - { - // Arrange - var collection = new[] - { - (3, "a"), - (2, "b"), - (2, "B"), - (1, "a") - }; - - // Act - Action action = () => collection.Should() - .BeInDescendingOrder(x => x.Item1) - .And - .ThenBeInDescendingOrder(x => x.Item2, StringComparer.InvariantCultureIgnoreCase); - - // Assert - action.Should().NotThrow(); - } - - [Fact] - public void When_the_collection_is_ordered_according_to_the_multiple_subsequent_descending_assertions_it_should_succeed() - { - // Arrange - var collection = new[] - { - (3, "a", 1.1), - (2, "c", 1.3), - (2, "b", 1.2), - (1, "a", 1.1) - }; - - // Act - Action action = () => collection.Should() - .BeInDescendingOrder(x => x.Item1) - .And - .ThenBeInDescendingOrder(x => x.Item2) - .And - .ThenBeInDescendingOrder(x => x.Item3); - - // Assert - action.Should().NotThrow(); - } - - #endregion - - #endregion - } - - internal class CountingGenericEnumerable : IEnumerable - { - private readonly IEnumerable backingSet; - - public CountingGenericEnumerable(IEnumerable backingSet) - { - this.backingSet = backingSet; - GetEnumeratorCallCount = 0; - } - - public int GetEnumeratorCallCount { get; private set; } - - public IEnumerator GetEnumerator() - { - GetEnumeratorCallCount++; - return backingSet.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } - - internal class CountingGenericCollection : ICollection - { - private readonly ICollection backingSet; - - public CountingGenericCollection(ICollection backingSet) - { - this.backingSet = backingSet; - } - - public int GetEnumeratorCallCount { get; private set; } - - public IEnumerator GetEnumerator() - { - GetEnumeratorCallCount++; - return backingSet.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void Add(TElement item) { throw new NotImplementedException(); } - - public void Clear() { throw new NotImplementedException(); } - - public bool Contains(TElement item) { throw new NotImplementedException(); } - - public void CopyTo(TElement[] array, int arrayIndex) { throw new NotImplementedException(); } - - public bool Remove(TElement item) { throw new NotImplementedException(); } - - public int GetCountCallCount { get; private set; } - - public int Count - { - get - { - GetCountCallCount++; - return backingSet.Count; - } - } - - public bool IsReadOnly { get; private set; } - } - - internal class TrackingTestEnumerable : IEnumerable - { - private readonly int[] values; - - public TrackingTestEnumerable(params int[] values) - { - this.values = values; - Enumerator = new TrackingEnumerator(this.values); - } - - public TrackingEnumerator Enumerator { get; } - - public IEnumerator GetEnumerator() - { - Enumerator.IncreaseEnumerationCount(); - Enumerator.Reset(); - return Enumerator; - } - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - - internal class TrackingEnumerator : IEnumerator - { - private readonly int[] values; - private int loopCount; - private int index; - - public TrackingEnumerator(int[] values) - { - index = -1; - - this.values = values; - } - - public int LoopCount - { - get { return loopCount; } - } - - public void IncreaseEnumerationCount() - { - loopCount++; - } - - public bool MoveNext() - { - index++; - return index < values.Length; - } - - public void Reset() - { - index = -1; - } - - public void Dispose() { } - - object IEnumerator.Current => Current; - - public int Current => values[index]; - } - - internal class OneTimeEnumerable : IEnumerable - { - private readonly IEnumerable items; - private int enumerations; - - public OneTimeEnumerable(params T[] items) => this.items = items; - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - public IEnumerator GetEnumerator() - { - if (enumerations++ > 0) - { - throw new InvalidOperationException("OneTimeEnumerable can be enumerated one time only"); - } - - return items.GetEnumerator(); - } - } - - internal class SomeClass - { - public string Text { get; set; } - - public int Number { get; set; } - } -} From 29ab7324224c344c380ee8682b73f1ed04bed54c Mon Sep 17 00:00:00 2001 From: IT-VBFK <49762557+IT-VBFK@users.noreply.github.com> Date: Mon, 25 Apr 2022 07:22:43 +0200 Subject: [PATCH 46/48] Rename CollectionAssertionSpecs.CommonAssertions.cs to CollectionAssertionSpecs.cs --- ...rtionSpecs.CommonAssertions.cs => CollectionAssertionSpecs.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tests/FluentAssertions.Specs/Collections/{CollectionAssertionSpecs.CommonAssertions.cs => CollectionAssertionSpecs.cs} (100%) diff --git a/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.CommonAssertions.cs b/Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.cs similarity index 100% rename from Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.CommonAssertions.cs rename to Tests/FluentAssertions.Specs/Collections/CollectionAssertionSpecs.cs From c33006c2e8857f7a02f1acffbc1e8a45ebd8853b Mon Sep 17 00:00:00 2001 From: ITaluone <44049228+ITaluone@users.noreply.github.com> Date: Wed, 27 Apr 2022 20:03:13 +0200 Subject: [PATCH 47/48] Fix the failure message for occurrence regex (#1913) --- Src/FluentAssertions/Primitives/StringAssertions.cs | 5 +++-- .../Primitives/StringAssertionSpecs.MatchRegex.cs | 6 +++--- docs/_pages/releases.md | 5 +++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/Src/FluentAssertions/Primitives/StringAssertions.cs b/Src/FluentAssertions/Primitives/StringAssertions.cs index a55ad0236d..60ca4084e5 100644 --- a/Src/FluentAssertions/Primitives/StringAssertions.cs +++ b/Src/FluentAssertions/Primitives/StringAssertions.cs @@ -507,8 +507,9 @@ public AndConstraint NotMatch(string wildcardPattern, string becaus .ForConstraint(occurrenceConstraint, actual) .UsingLineBreaks .BecauseOf(because, becauseArgs) - .FailWith($"Expected {{context:string}} to match regex {{0}} {{expectedOccurrence}}{{reason}}, but found it {actual.Times()}.", - regexStr); + .FailWith($"Expected {{context:string}} {{0}} to match regex {{1}} {{expectedOccurrence}}{{reason}}, " + + $"but found it {actual.Times()}.", + Subject, regexStr); } return new AndConstraint((TAssertions)this); diff --git a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs index e84f9342aa..2259176f45 100644 --- a/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs +++ b/Tests/FluentAssertions.Specs/Primitives/StringAssertionSpecs.MatchRegex.cs @@ -225,7 +225,7 @@ public void When_a_string_is_matched_and_the_count_of_matches_do_not_fit_the_exp // Assert act.Should().Throw() - .WithMessage($"Expected subject to match regex*\"Lorem.*\" exactly 2 times, but found it 1 time."); + .WithMessage($"Expected subject*Lorem*to match regex*\"Lorem.*\" exactly 2 times, but found it 1 time*"); } [Fact] @@ -252,7 +252,7 @@ public void When_a_string_is_matched_and_the_expected_count_is_zero_and_string_m // Assert act.Should().Throw() - .WithMessage($"Expected subject to match regex*\"a\" exactly 0 times, but found it 1 time."); + .WithMessage($"Expected subject*a*to match regex*\"a\" exactly 0 times, but found it 1 time*"); } [Fact] @@ -305,7 +305,7 @@ public void When_the_subject_is_empty_and_expected_count_is_more_than_zero_it_fa // Assert act.Should().Throw() - .WithMessage($"Expected subject to match regex* at least 1 time, but found it 0 times.*"); + .WithMessage($"Expected subject*to match regex* at least 1 time, but found it 0 times*"); } [Fact] diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index 3011877865..ada326d6ad 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -16,6 +16,9 @@ sidebar: * Add `For`/`Exclude` to allow exclusion of members inside a collection - [#1782](https://github.com/fluentassertions/fluentassertions/pull/1782) * Added overload for `HaveElement` for `XDocument` and `XElement` to assert on number of XML nodes - [#1880](https://github.com/fluentassertions/fluentassertions/pull/1880) +### Fixes +* Fix the failure message for regex matches (occurrence overload) to include the missing subject - [#1913](https://github.com/fluentassertions/fluentassertions/pull/1913) + ## 6.6.0 ### What's New @@ -32,8 +35,6 @@ sidebar: * Better handling of NaN in various numeric assertions - [#1822](https://github.com/fluentassertions/fluentassertions/pull/1822) & [#1867](https://github.com/fluentassertions/fluentassertions/pull/1867) * `WithMapping` in `BeEquivalentTo` now also works when the root is a collection - [#1858](https://github.com/fluentassertions/fluentassertions/pull/1858) -### Fixes (Extensibility) - ## 6.5.1 ### Fixes From 463edb9bc2ac9c2aafc84d83d1c89bbf644c1f35 Mon Sep 17 00:00:00 2001 From: ITaluone <44049228+ITaluone@users.noreply.github.com> Date: Wed, 18 May 2022 06:04:46 +0200 Subject: [PATCH 48/48] Do not add all arguments of type `T` to the matching events, if one is found (#1920) --- .../EventRaisingExtensions.cs | 65 +++---- .../Events/EventAssertionSpecs.cs | 161 +++++++++++++++++- docs/_pages/releases.md | 1 + 3 files changed, 183 insertions(+), 44 deletions(-) diff --git a/Src/FluentAssertions/EventRaisingExtensions.cs b/Src/FluentAssertions/EventRaisingExtensions.cs index f73e98a6ec..61bff30c47 100644 --- a/Src/FluentAssertions/EventRaisingExtensions.cs +++ b/Src/FluentAssertions/EventRaisingExtensions.cs @@ -53,8 +53,9 @@ public static IEventRecording WithSender(this IEventRecording eventRecording, ob } /// - /// Asserts that at least one occurrence of the events had at least one of the arguments matching a predicate. Returns - /// only the events that matched that predicate. + /// Asserts that at least one occurence of the events had one or more arguments of the expected + /// type which matched the given predicate. + /// Returns only the events that matched both type and optionally a predicate. /// public static IEventRecording WithArgs(this IEventRecording eventRecording, Expression> predicate) { @@ -62,40 +63,33 @@ public static IEventRecording WithArgs(this IEventRecording eventRecording, E Func compiledPredicate = predicate.Compile(); - bool hasArgumentOfRightType = false; - var eventsMatchingPredicate = new List(); + var eventsWithMatchingPredicate = new List(); foreach (OccurredEvent @event in eventRecording) { var typedParameters = @event.Parameters.OfType().ToArray(); - if (typedParameters.Any()) - { - hasArgumentOfRightType = true; - } if (typedParameters.Any(parameter => compiledPredicate(parameter))) { - eventsMatchingPredicate.Add(@event); + eventsWithMatchingPredicate.Add(@event); } } - if (!hasArgumentOfRightType) - { - throw new ArgumentException("No argument of event " + eventRecording.EventName + " is of type <" + typeof(T) + ">."); - } + bool foundMatchingEvent = eventsWithMatchingPredicate.Any(); - if (!eventsMatchingPredicate.Any()) - { - Execute.Assertion - .FailWith("Expected at least one event with arguments matching {0}, but found none.", predicate.Body); - } + Execute.Assertion + .ForCondition(foundMatchingEvent) + .FailWith("Expected at least one event which arguments are of type <{0}> and matches {1}, but found none.", + typeof(T), + predicate.Body); - return new FilteredEventRecording(eventRecording, eventsMatchingPredicate); + return new FilteredEventRecording(eventRecording, eventsWithMatchingPredicate); } /// - /// Asserts that at least one of the occurred events has arguments the match the predicates in the same order. Returns - /// only the events that matched those predicates. + /// Asserts that at least one occurence of the events had one or more arguments of the expected + /// type which matched the predicates in the same order. + /// Returns only the events that matched both type and optionally predicates. /// /// /// If a null is provided as predicate argument, the corresponding event parameter value is ignored. @@ -104,16 +98,12 @@ public static IEventRecording WithArgs(this IEventRecording eventRecording, p { Func[] compiledPredicates = predicates.Select(p => p?.Compile()).ToArray(); - bool hasArgumentOfRightType = false; - var eventsMatchingPredicate = new List(); + var eventsWithMatchingPredicate = new List(); foreach (OccurredEvent @event in eventRecording) { var typedParameters = @event.Parameters.OfType().ToArray(); - if (typedParameters.Any()) - { - hasArgumentOfRightType = true; - } + bool hasArgumentOfRightType = typedParameters.Any(); if (predicates.Length > typedParameters.Length) { @@ -121,7 +111,7 @@ public static IEventRecording WithArgs(this IEventRecording eventRecording, p $"Expected the event to have at least {predicates.Length} parameters of type {typeof(T)}, but only found {typedParameters.Length}."); } - bool isMatch = true; + bool isMatch = hasArgumentOfRightType; for (int index = 0; index < predicates.Length && isMatch; index++) { isMatch = compiledPredicates[index]?.Invoke(typedParameters[index]) ?? true; @@ -129,24 +119,21 @@ public static IEventRecording WithArgs(this IEventRecording eventRecording, p if (isMatch) { - eventsMatchingPredicate.Add(@event); + eventsWithMatchingPredicate.Add(@event); } } - if (!hasArgumentOfRightType) - { - throw new ArgumentException("No argument of event " + eventRecording.EventName + " is of type <" + typeof(T) + ">."); - } + bool foundMatchingEvent = eventsWithMatchingPredicate.Any(); - if (!eventsMatchingPredicate.Any()) + if (!foundMatchingEvent) { - Execute - .Assertion - .FailWith("Expected at least one event with arguments matching {0}, but found none.", - string.Join(" | ", predicates.Where(p => p is not null).Select(p => p.Body.ToString()))); + Execute.Assertion + .FailWith("Expected at least one event which arguments are of type <{0}> and matches {1}, but found none.", + typeof(T), + string.Join(" | ", predicates.Where(p => p is not null).Select(p => p.Body.ToString()))); } - return new FilteredEventRecording(eventRecording, eventsMatchingPredicate); + return new FilteredEventRecording(eventRecording, eventsWithMatchingPredicate); } } } diff --git a/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs b/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs index 871bb98455..b5dc222de4 100644 --- a/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs +++ b/Tests/FluentAssertions.Specs/Events/EventAssertionSpecs.cs @@ -179,7 +179,7 @@ public void When_the_event_parameters_dont_match_it_should_throw() act .Should().Throw() .WithMessage( - "Expected at least one event with arguments matching (args.PropertyName == \"SomeProperty\"), but found none."); + "Expected at least one event which arguments are of type*PropertyChangedEventArgs*matches*(args.PropertyName == \"SomeProperty\"), but found none."); } [Fact] @@ -197,8 +197,8 @@ public void When_the_event_args_are_of_a_different_type_it_should_throw() // Assert act - .Should().Throw() - .WithMessage("No argument of event PropertyChanged is of type *CancelEventArgs>*"); + .Should().Throw() + .WithMessage("Expected*event*argument*type*CancelEventArgs>*"); } [Fact] @@ -321,7 +321,7 @@ public void When_a_non_conventional_event_with_a_specific_argument_was_not_raise // Assert act.Should().Throw().WithMessage( - "Expected at least one event with arguments matching (args == " + wrongArgument + "), but found none."); + "Expected at least one event which arguments*type*Int32*matches*(args == " + wrongArgument + "), but found none."); } [Fact] @@ -340,7 +340,7 @@ public void When_a_non_conventional_event_with_many_specific_arguments_was_not_r // Assert act.Should().Throw().WithMessage( - "Expected at least one event with arguments matching \"(args == \"" + wrongArgument + + "Expected at least one event which arguments*matches*\"(args == \"" + wrongArgument + "\")\", but found none."); } @@ -808,6 +808,157 @@ public void When_monitoring_interface_with_inherited_event_it_should_not_throw() } } + public class WithArgs + { + [Fact] + public void One_matching_argument_type_before_mismatching_types_passes() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new B()); + a.OnEvent(new C()); + + // Act / Assert + IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(); + filteredEvents.Should().HaveCount(1); + } + + [Fact] + public void One_matching_argument_type_after_mismatching_types_passes() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new B()); + + // Act / Assert + IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(); + filteredEvents.Should().HaveCount(1); + } + + [Fact] + public void Throws_when_none_of_the_arguments_are_of_the_expected_type() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new C()); + + // Act + Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(); + + // Assert + act.Should().Throw() + .WithMessage("Expected*event*argument*"); + } + + [Fact] + public void One_matching_argument_type_anywhere_between_mismatching_types_passes() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new B()); + a.OnEvent(new C()); + + // Act / Assert + IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(); + filteredEvents.Should().HaveCount(1); + } + + [Fact] + public void One_matching_argument_type_anywhere_between_mismatching_types_with_parameters_passes() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new B()); + a.OnEvent(new C()); + + // Act / Assert + IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(b => true); + filteredEvents.Should().HaveCount(1); + } + + [Fact] + public void Mismatching_argument_types_with_one_parameter_matching_a_different_type_fails() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new C()); + + // Act + Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(b => true); + + // Assert + act.Should().Throw() + .WithMessage("Expected*event*argument*type*B*none*"); + } + + [Fact] + public void Mismatching_argument_types_with_two_or_more_parameters_matching_a_different_type_fails() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new C()); + + // Act + Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(b => true, b => false); + + // Assert + act.Should().Throw() + .WithMessage("Expected*event*parameters*type*B*found*"); + } + + [Fact] + public void One_matching_argument_type_with_two_or_more_parameters_matching_a_mismatching_type_fails() + { + // Arrange + A a = new A(); + using var aMonitor = a.Monitor(); + + a.OnEvent(new C()); + a.OnEvent(new B()); + + // Act + Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs(b => true, b => false); + + // Assert + act.Should().Throw() + .WithMessage("Expected*event*parameters*type*B*found*"); + } + } + + public class A + { + public event EventHandler Event; + + public void OnEvent(object o) + { + Event.Invoke(nameof(A), o); + } + } + + public class B { } + + public class C { } + public class ClassThatRaisesEventsItself : IInheritsEventRaisingInterface { public event PropertyChangedEventHandler PropertyChanged; diff --git a/docs/_pages/releases.md b/docs/_pages/releases.md index ada326d6ad..af80aee431 100644 --- a/docs/_pages/releases.md +++ b/docs/_pages/releases.md @@ -18,6 +18,7 @@ sidebar: ### Fixes * Fix the failure message for regex matches (occurrence overload) to include the missing subject - [#1913](https://github.com/fluentassertions/fluentassertions/pull/1913) +* Fixed `WithArgs` matching too many events when at least one argument matched the expected type - [#1920](https://github.com/fluentassertions/fluentassertions/pull/1920) ## 6.6.0