### Query Documentation Dynamically Source: https://docs.shouldly.org/documentation/enumerable/unique To get more information not present on the page, make an HTTP GET request to the page URL with an `ask` query parameter containing your question. ```http GET https://docs.shouldly.org/documentation/enumerable/unique.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.shouldly.org/documentation/equality/exampleclasses To get additional information not directly on the page, perform an HTTP GET request to the current page URL with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/equality/exampleclasses.md?ask= ``` -------------------------------- ### Querying Documentation with GET Request Source: https://docs.shouldly.org/documentation/equality/shouldbe-1 To get more information not present on the current page, perform an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/equality/shouldbe-1.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.shouldly.org/documentation/dictionary/containkey To get more information not present on the page, make an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/dictionary/containkey.md?ask= ``` -------------------------------- ### Query Documentation with HTTP GET Source: https://docs.shouldly.org/documentation/equality/shouldbe Demonstrates how to perform an HTTP GET request to query documentation dynamically using the `ask` query parameter. This is useful for retrieving specific information not explicitly present on the page. ```http GET https://docs.shouldly.org/documentation/equality/shouldbe.md?ask= ``` -------------------------------- ### Querying documentation dynamically Source: https://docs.shouldly.org/documentation/enumerable/contain To get additional information not directly on the page, make an HTTP GET request to the page URL with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/enumerable/contain.md?ask= ``` -------------------------------- ### Querying Documentation with GET Request Source: https://docs.shouldly.org/documentation/equality/sameas To get more information not directly on the page, perform an HTTP GET request to the page URL with an 'ask' query parameter containing your question. ```http GET https://docs.shouldly.org/documentation/equality/sameas.md?ask= ``` -------------------------------- ### Query documentation dynamically Source: https://docs.shouldly.org/documentation/dynamicshould To get more information not present on the page, make an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/dynamicshould.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.shouldly.org/documentation/equality/matchapproved Perform an HTTP GET request to the current page URL, including the 'ask' query parameter with your question. The response will provide a direct answer and relevant excerpts. ```http GET https://docs.shouldly.org/documentation/equality/matchapproved.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.shouldly.org/documentation/3to4 To get additional information not directly present on the page, perform an HTTP GET request with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/3to4.md?ask= ``` -------------------------------- ### Querying documentation dynamically Source: https://docs.shouldly.org/documentation/enumerable/allbe To get more information not present on the page, perform an HTTP GET request with the 'ask' query parameter to the current page URL. ```http GET https://docs.shouldly.org/documentation/enumerable/allbe.md?ask= ``` -------------------------------- ### Configure Diff Engine for Shouldly Source: https://docs.shouldly.org/documentation/equality/matchapproved Install the Shouldly.DiffEngine nuget package and call this method in your test setup to enable diff comparisons for failed approvals. ```csharp // In your test setup ShouldlyConfiguration.ShouldMatchApprovedDefaults.ConfigureDiffEngine(); ``` -------------------------------- ### Querying Documentation with GET Request Source: https://docs.shouldly.org/documentation/enumerable/empty To get additional information not directly present on the page, perform an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/enumerable/empty.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.shouldly.org/contributing To get additional information not directly present on a page, perform an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and in natural language. Use this for clarifications, additional context, or related documentation. ```http GET https://docs.shouldly.org/contributing.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.shouldly.org/documentation/completein To get more information not present on the page, perform an HTTP GET request to the current page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/completein.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.shouldly.org/documentation/enumerable/subsetof To get more information not present on the page, make an HTTP GET request to the current page URL with the `ask` query parameter. The question should be specific and in natural language. ```http GET https://docs.shouldly.org/documentation/enumerable/subsetof.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.shouldly.org/documentation/equality/shouldbe-2 To get additional information not directly present on the page, perform an HTTP GET request on the current page URL with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://docs.shouldly.org/documentation/equality/shouldbe-2.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.shouldly.org/documentation/equality/assignableto To get more information not present on the page, make an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.shouldly.org/documentation/equality/assignableto.md?ask= ``` -------------------------------- ### Install Shouldly via Package Manager Console Source: https://docs.shouldly.org/ Use this command to install the Shouldly NuGet package in Visual Studio's Package Manager Console. ```powershell Install-Package Shouldly ``` -------------------------------- ### Install Shouldly via .NET CLI Source: https://docs.shouldly.org/ Use this command to add the Shouldly package to your project using the .NET Core command-line interface. ```bash dotnet add package Shouldly ``` -------------------------------- ### Define Example Classes in C# Source: https://docs.shouldly.org/documentation/equality/exampleclasses These classes are used across various Shouldly documentation examples. They include an abstract `Pet` class with concrete `Cat` and `Dog` implementations, and a `Person` class with name and salary properties. ```csharp namespace Simpsons; public abstract class Pet { public abstract string? Name { get; set; } public override string? ToString() => Name; } public class Cat : Pet { public override string? Name { get; set; } } public class Dog : Pet { public override string? Name { get; set; } } public class Person { public Person() { } public Person(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } public string? Name { get; set; } public int Salary { get; set; } public override string? ToString() => Name; } ``` -------------------------------- ### Verify a collection has a single item Source: https://docs.shouldly.org/documentation/enumerable/have Use ShouldHaveSingleItem to assert that a collection contains exactly one element. This is useful for ensuring uniqueness or expected single-item results. The example demonstrates setup and the assertion itself. ```cs var maggie = new Person { Name = "Maggie" }; var homer = new Person { Name = "Homer" }; var simpsonsBabies = new List { homer, maggie }; simpsonsBabies.ShouldHaveSingleItem(); ``` -------------------------------- ### Shouldly Assertion Example Source: https://docs.shouldly.org/ This shows how to use Shouldly's ShouldBe assertion for more readable code and clearer error messages. ```csharp contestant.Points.ShouldBe(1337); ``` -------------------------------- ### Traditional Assertion Example Source: https://docs.shouldly.org/ This demonstrates the older way of writing assertions using Assert.That, which provides less descriptive error messages on failure. ```csharp Assert.That(contestant.Points, Is.EqualTo(1337)); ``` -------------------------------- ### Exception Message for Failed Assignability Source: https://docs.shouldly.org/documentation/equality/assignableto This is an example of the exception message thrown when an object is not assignable to the expected type. ```text theSimpsonsDog should be assignable to Simpsons.Pet but was Simpsons.Person ``` -------------------------------- ### CompleteIn Exception Message Source: https://docs.shouldly.org/documentation/completein This is an example of the exception message thrown when an action does not complete within the specified timeout for the Should.CompleteIn assertion. It includes the expected completion time and any additional context provided. ```text Delegate should complete in 00:00:00.5000000 but did not Additional Info: Some additional context ``` -------------------------------- ### SubsetOf Assertion Failure Example in C# Source: https://docs.shouldly.org/documentation/enumerable/subsetof This is the exception message displayed when the `simpsonsKids` list is not a subset of the `simpsonsFamily` list, indicating which elements are outside the expected superset. ```csharp simpsonsKids should be subset of [Lisa, Bart, Maggie, Homer, Marge] but [Ralph] is outside subset ``` -------------------------------- ### Check if a reference type is null Source: https://docs.shouldly.org/documentation/equality/null Use `ShouldBeNull` to assert that a reference type is null. This example checks if a string is null. ```cs var myRef = "Hello World"; myRef.ShouldBeNull(); ``` -------------------------------- ### Check if a reference type is not null Source: https://docs.shouldly.org/documentation/equality/null Use `ShouldNotBeNull` to assert that a reference type is not null. This example checks if a nullable string is not null. ```cs string? myRef = null; myRef.ShouldNotBeNull(); ``` -------------------------------- ### Chain assertions after checking for non-null reference type Source: https://docs.shouldly.org/documentation/equality/null Use `ShouldNotBeNull` to assert that a reference type is not null, and chain further assertions on the non-null value. This example checks the length of a string. ```cs var myRef = (string?)"1234"; myRef.ShouldNotBeNull().Length.ShouldBe(5); ``` -------------------------------- ### Check if a nullable value type is not null Source: https://docs.shouldly.org/documentation/equality/null Use `ShouldNotBeNull` to assert that a nullable value type is not null. This example checks if an `int?` is not null. ```cs int? myRef = null; myRef.ShouldNotBeNull(); ``` -------------------------------- ### Check if a nullable value type is null Source: https://docs.shouldly.org/documentation/equality/null Use `ShouldBeNull` to assert that a nullable value type is null. This example checks if an `int?` is null. ```cs int? nullableValue = 42; ullableValue.ShouldBeNull(); ``` -------------------------------- ### ShouldStartWith String Assertion Source: https://docs.shouldly.org/documentation/string/startwith Use this assertion to verify that a string begins with a specified prefix. Ensure the prefix is correctly cased. ```cs var target = "Homer"; target.ShouldStartWith("Bart"); ``` -------------------------------- ### Chain assertions after checking for non-null nullable value type Source: https://docs.shouldly.org/documentation/equality/null Use `ShouldNotBeNull` to assert that a nullable value type is not null, and chain further assertions on the unwrapped value. This example checks a property of a struct. ```cs SomeStruct? nullableValue = new SomeStruct { IntProperty = 41 }; ullableValue.ShouldNotBeNull().IntProperty.ShouldBe(42); ``` -------------------------------- ### ShouldNotStartWith String Assertion Source: https://docs.shouldly.org/documentation/string/startwith Use this assertion to verify that a string does not begin with a specified prefix. This is useful for negative testing. ```cs var target = "Homer Simpson"; target.ShouldNotStartWith("Homer"); ``` -------------------------------- ### Initial Run of ShouldMatchApproved Source: https://docs.shouldly.org/documentation/equality/matchapproved When an approved file does not exist, the test will fail, presenting a diff viewer. The output will indicate that the approval file is missing. ```csharp var simpsonsQuote = "Hi Super Nintendo Chalmers"; simpsonsQuote.ShouldMatchApproved(); ``` -------------------------------- ### Create Main Program Class Source: https://docs.shouldly.org/documentation/getting-started This C# code defines a static class with a method that returns a string. It serves as the main program logic for the project. ```csharp using System; public static class Program { public static string TestWorks() { return "Works"; } } ``` -------------------------------- ### Enable Diff Viewer Source: https://docs.shouldly.org/documentation/equality/matchapproved Opens a diff viewer when files do not match. Requires the Shouldly.DiffEngine package. ```csharp toVerify.ShouldMatchApproved(c => c.Diff()) ``` -------------------------------- ### Set String Comparison Options Source: https://docs.shouldly.org/documentation/equality/matchapproved Configure specific string comparison behaviors like ignoring case or line endings. Combine options using the bitwise OR operator. ```csharp var options = StringCompareShould.IgnoreCase | StringCompareShould.IgnoreLineEndings; toVerify.ShouldMatchApproved(c => c.WithStringCompareOptions(options)) ``` -------------------------------- ### Basic ShouldMatchApproved Usage Source: https://docs.shouldly.org/documentation/equality/matchapproved The fundamental way to use ShouldMatchApproved with a configuration builder. Replace OPTION with a specific configuration method. ```csharp toVerify.ShouldMatchApproved(configurationBuilder => configurationBuilder.OPTION()) ``` -------------------------------- ### Verify all elements in a collection satisfy a condition Source: https://docs.shouldly.org/documentation/enumerable/allbe Use ShouldAllBe to assert that every element in a collection meets a specified predicate. Ensure all necessary objects and lists are initialized before the assertion. ```cs var mrBurns = new Person { Name = "Mr.Burns", Salary = 3000000 }; var kentBrockman = new Person { Name = "Homer", Salary = 3000000 }; var homer = new Person { Name = "Homer", Salary = 30000 }; var millionaires = new List { mrBurns, kentBrockman, homer }; millionaires.ShouldAllBe(m => m.Salary > 1000000); ``` -------------------------------- ### Place Files in Sub-Folder Source: https://docs.shouldly.org/documentation/equality/matchapproved Organizes approved and received files into a specified sub-directory. ```csharp toVerify.ShouldMatchApproved(c => c.SubFolder("Approvals")) ``` -------------------------------- ### Override File Extension Source: https://docs.shouldly.org/documentation/equality/matchapproved Changes the file extension for approved and received files. The default is '.txt'. ```csharp toVerify.ShouldMatchApproved(c => c.WithFileExtension(".cs")) ``` -------------------------------- ### ShouldMatchApproved with Mismatched Content Source: https://docs.shouldly.org/documentation/equality/matchapproved If the received content differs from the approved content, the test fails and displays a detailed comparison of the expected and actual values, highlighting the differences. ```csharp var simpsonsQuote = "Me fail english? That's unpossible"; simpsonsQuote.ShouldMatchApproved(); ``` -------------------------------- ### Apply Scrubber for Dynamic Content Source: https://docs.shouldly.org/documentation/equality/matchapproved Removes or replaces dynamic content, such as dates, from received files using a regular expression. This ensures consistent approvals. ```csharp toVerify.ShouldMatchApproved(c => c.WithScrubber(s => Regex.Replace(s, "\d{1,2}/\d{1,2}/\d{2,4}", "")) ``` -------------------------------- ### Use Discriminator for File Naming Source: https://docs.shouldly.org/documentation/equality/matchapproved Applies a discriminator to the approved and received filenames, useful for data-driven tests. The default filename is `${MethodName}.approved.txt`. ```csharp [Fact] public void Simpsons() { toVerify.ShouldMatchApproved(c => c.WithDiscriminator("Bart")); } ``` -------------------------------- ### Exception message for missing property Source: https://docs.shouldly.org/documentation/dynamicshould This is the expected exception message when DynamicShould.HaveProperty fails because the dynamic object does not have the specified property. ```text Dynamic object "theFuture" should contain property "RobotTeachers" but does not. ``` -------------------------------- ### Locate Test Method Using Attribute Source: https://docs.shouldly.org/documentation/equality/matchapproved Specifies how to locate the test method for approval filenames using a specific attribute. Supports XUnit and NUnit attributes. ```csharp // XUnit "testAttributes".ShouldMatchApproved(b => b.LocateTestMethodUsingAttribute()); // NUnit "testAttributes".ShouldMatchApproved(b => b.LocateTestMethodUsingAttribute()); ``` -------------------------------- ### Assert String Is Empty Source: https://docs.shouldly.org/documentation/string/null Use `ShouldBeEmpty` to assert that a string is an empty string. This assertion will fail if the string is null or contains any characters. ```cs var target = "Homer"; target.ShouldBeEmpty(); ``` -------------------------------- ### ShouldBe Object Comparison Source: https://docs.shouldly.org/documentation/equality/shouldbe Compares two objects for equality using the .Equals method. Ensure the objects have a proper .Equals implementation for accurate comparison. ```cs var theSimpsonsCat = new Cat { Name = "Santas little helper" }; theSimpsonsCat.Name.ShouldBe("Snowball 2"); ``` -------------------------------- ### SatisfyAllConditions with Lambda Expressions Source: https://docs.shouldly.org/documentation/satisfyallconditions Use this overload when you need to access the object being asserted directly within the lambda expressions. Ensure the object and its properties are not null before applying further assertions. ```cs var mrBurns = new Person { Name = null }; mrBurns.ShouldSatisfyAllConditions( () => mrBurns.Name.ShouldNotBeNullOrEmpty(), () => mrBurns.Name.ShouldBe("Mr.Burns")); ``` -------------------------------- ### Shouldly vs Traditional Assertion Comparison Source: https://docs.shouldly.org/ Compares the traditional assertion syntax and error message with Shouldly's syntax and improved error message for diagnosing issues. ```csharp Assert.That(map.IndexOfValue("boo"), Is.EqualTo(2)); // -> Expected 2 but was -1 map.IndexOfValue("boo").ShouldBe(2); // -> map.IndexOfValue("boo") should be 2 but was -1 ``` -------------------------------- ### ShouldThrow Extension for Actions Source: https://docs.shouldly.org/documentation/exceptions/throw Use the `ShouldThrow()` extension method on an `Action` delegate to assert that the action throws a specific exception type. This provides a more fluent syntax for exception testing. ```cs var homer = new Person { Name = "Homer", Salary = 30000 }; var denominator = 1; var action = () => { var y = homer.Salary / denominator; }; action.ShouldThrow(); ``` -------------------------------- ### Assert a collection is empty using ShouldBeEmpty Source: https://docs.shouldly.org/documentation/enumerable/empty Use ShouldBeEmpty to assert that a collection has no elements. This assertion will fail if the collection contains any items, providing details about the number of items and their values. ```cs var homer = new Person { Name = "Homer" }; var powerPlantOnTheWeekend = new List { homer }; powerPlantOnTheWeekend.ShouldBeEmpty(); ``` -------------------------------- ### Assert String Is Null Source: https://docs.shouldly.org/documentation/string/null Use `ShouldBeNull` to assert that a string is null. This assertion will fail if the string has any value, including an empty string. ```cs var target = "Homer"; target.ShouldBeNull(); ``` -------------------------------- ### Assert String Is Not Null Or Empty Source: https://docs.shouldly.org/documentation/string/null Use `ShouldNotBeNullOrEmpty` to assert that a string is neither null nor empty. This is a robust check for ensuring a string has meaningful content. ```cs var target = ""; target.ShouldNotBeNullOrEmpty(); ``` -------------------------------- ### ShouldThrow Extension for Funcs Source: https://docs.shouldly.org/documentation/exceptions/throw Use the `ShouldThrow()` extension method on a `Func` delegate to assert that the function throws a specific exception type. This offers a concise way to test functions that are expected to throw. ```cs var func = () => new Person("Homer"); func.ShouldThrow(); ``` -------------------------------- ### Shouldly Boolean Assertion Exception Source: https://docs.shouldly.org/documentation/equality/shouldbe Illustrates the exception message format when a boolean assertion fails. It clearly shows the expected value, the actual value, and any additional context provided. ```text myValue should be True but was False Additional Info: Some additional context ``` -------------------------------- ### Integer Comparison with ShouldNotBe Source: https://docs.shouldly.org/documentation/equality/notbe Assert that an integer value is not equal to a specific integer. This works for any integer type. ```cs const int one = 1; one.ShouldNotBe(1); ``` -------------------------------- ### Assert String Equality with ShouldBe Source: https://docs.shouldly.org/documentation/equality/shouldbe-2 Use ShouldBe to assert that a string is equal to an expected value. This assertion will fail if the strings do not match, providing a detailed difference report. ```csharp var target = "Homer"; target.ShouldBe("Bart"); ``` -------------------------------- ### Verify Collection Uniqueness Source: https://docs.shouldly.org/documentation/enumerable/unique Use `ShouldBeUnique` to assert that all elements in a list are distinct. This assertion will fail if any element appears more than once, providing details about the duplicated item. ```cs var lisa = new Person { Name = "Lisa" }; var bart = new Person { Name = "Bart" }; var maggie = new Person { Name = "Maggie" }; var simpsonsKids = new List { bart, lisa, maggie, maggie }; simpsonsKids.ShouldBeUnique(); ``` -------------------------------- ### Assert a collection is not empty using ShouldNotBeEmpty Source: https://docs.shouldly.org/documentation/enumerable/empty Use ShouldNotBeEmpty to assert that a collection contains at least one element. This assertion will fail if the collection is empty. ```cs var moesTavernOnTheWeekend = new List(); moesTavernOnTheWeekend.ShouldNotBeEmpty(); ``` -------------------------------- ### Assert String Inequality with ShouldNotBe Source: https://docs.shouldly.org/documentation/equality/shouldbe-2 Use ShouldNotBe to assert that a string is not equal to a specific value. This assertion fails if the string matches the provided value. ```csharp var target = "Bart"; target.ShouldNotBe("Bart"); ``` -------------------------------- ### Assert string does not match a regular expression Source: https://docs.shouldly.org/documentation/string/match Use ShouldNotMatch to assert that a string does not conform to a given regular expression pattern. This is useful for negative assertions. ```cs var target = "Homer Simpson"; target.ShouldNotMatch("Homer .*?"); ``` -------------------------------- ### Verify Object Identity with ShouldBeSameAs Source: https://docs.shouldly.org/documentation/equality/sameas Use ShouldBeSameAs to assert that two object references point to the exact same object in memory. This is useful for checking identity rather than value equality. ```cs var principleSkinner = new Person { Name = "Armin Tamzarian" }; var seymourSkinner = new Person { Name = "Seymour Skinner" }; principleSkinner.ShouldBeSameAs(seymourSkinner); ``` -------------------------------- ### Assert String Is Null Or Empty Source: https://docs.shouldly.org/documentation/string/null Use `ShouldBeNullOrEmpty` to assert that a string is either null or an empty string. This is useful for validating input that should not contain any characters. ```cs var target = "Homer"; target.ShouldBeNullOrEmpty(); ``` -------------------------------- ### Exception when ShouldAllBe fails Source: https://docs.shouldly.org/documentation/enumerable/allbe This is the exception message displayed when the ShouldAllBe assertion fails, indicating which elements did not satisfy the condition. ```text millionaires should satisfy the condition (m.Salary > 1000000) but [Homer] do not ``` -------------------------------- ### Assert string matches a regular expression Source: https://docs.shouldly.org/documentation/string/match Use ShouldMatch to assert that a string conforms to a given regular expression pattern. Ensure the pattern is correctly formatted. ```cs var target = "Homer Simpson"; target.ShouldMatch("Bart .*?"); ``` -------------------------------- ### ShouldBe Numeric Comparison with Tolerance Source: https://docs.shouldly.org/documentation/equality/shouldbe Compares decimal values within a specified tolerance. Useful for floating-point comparisons where exact matches may not be feasible. ```cs const decimal pi = (decimal)Math.PI; pi.ShouldBe(3.24m, 0.01m); ``` -------------------------------- ### ShouldBe TimeSpan Comparison with Tolerance Source: https://docs.shouldly.org/documentation/equality/shouldbe Compares TimeSpan values within a specified tolerance. This overload is helpful when checking if a duration falls within an acceptable range. ```cs var timeSpan = TimeSpan.FromHours(1); timeSpan.ShouldBe(timeSpan.Add(TimeSpan.FromHours(1.1d)), TimeSpan.FromHours(1)); ``` -------------------------------- ### Assert Dictionary Contains Key and Value Source: https://docs.shouldly.org/documentation/dictionary/containkeyandvalue Use ShouldContainKeyAndValue to verify that a dictionary contains a specific key with an expected value. This assertion will fail if the key is missing or if the key exists but has a different value. ```cs var websters = new Dictionary { { "Cromulent", "I never heard the word before moving to Springfield." } }; websters.ShouldContainKeyAndValue("Cromulent", "Fine, acceptable."); ``` -------------------------------- ### Generic SatisfyAllConditions with Lambda Expressions Source: https://docs.shouldly.org/documentation/satisfyallconditions This generic overload is useful when you want to explicitly pass the object as a parameter to your lambda expressions. It provides a clear way to reference the object being tested within each condition. ```cs var mrBurns = new Person { Name = null }; mrBurns.ShouldSatisfyAllConditions( p => p.Name.ShouldNotBeNullOrEmpty(), p => p.Name.ShouldBe("Mr.Burns")); ``` -------------------------------- ### Check if a collection does not contain a specific object Source: https://docs.shouldly.org/documentation/enumerable/contain Use `ShouldNotContain` to assert that a collection does not include a specific object. This is helpful for verifying the absence of certain items. ```cs var homerSimpson = new Person { Name = "Homer" }; var homerGlumplich = new Person { Name = "Homer" }; var lenny = new Person { Name = "Lenny" }; var carl = new Person { Name = "carl" }; var clubOfNoHomers = new List { homerSimpson, homerGlumplich, lenny, carl }; clubOfNoHomers.ShouldNotContain(homerSimpson); ``` -------------------------------- ### ShouldThrow for Funcs Source: https://docs.shouldly.org/documentation/exceptions/throw Use `Should.Throw` to assert that a `Func` delegate, which returns a value, throws a specific exception type when invoked. This is suitable for testing expressions that are expected to fail. ```cs Should.Throw(() => new Person("Homer")); ``` -------------------------------- ### ShouldThrowAsync for Async Operations Source: https://docs.shouldly.org/documentation/exceptions/throw Use `Should.ThrowAsync` to assert that an asynchronous operation, represented by a `Func`, throws a specific exception type. This is useful for testing methods that return `Task`. ```cs Task doSomething() => Task.CompletedTask; var exception = await Should.ThrowAsync(() => doSomething()); ``` -------------------------------- ### ShouldThrow for Actions Source: https://docs.shouldly.org/documentation/exceptions/throw Use `Should.Throw` to assert that a code block, represented as an `Action`, throws a specific exception type. Ensure the code within the action would cause the expected exception. ```cs var homer = new Person { Name = "Homer", Salary = 30000 }; var denominator = 1; Should.Throw(() => { var y = homer.Salary / denominator; }); ``` -------------------------------- ### Object Comparison with ShouldNotBe Source: https://docs.shouldly.org/documentation/equality/notbe Use ShouldNotBe to assert that an object's property is not equal to a specific value. This assertion uses the .Equals method for comparison. ```cs var theSimpsonsCat = new Cat { Name = "Santas little helper" }; theSimpsonsCat.Name.ShouldNotBe("Santas little helper"); ``` -------------------------------- ### Assert Dictionary Does Not Contain Key and Value Source: https://docs.shouldly.org/documentation/dictionary/containkeyandvalue Use ShouldNotContainValueForKey to assert that a dictionary does not contain a specific key with a specific value. This assertion fails if the key exists and has the specified value. ```cs var websters = new Dictionary { { "Chazzwazzers", "What Australians would have called a bull frog." } }; websters.ShouldNotContainValueForKey("Chazzwazzers", "What Australians would have called a bull frog."); ``` -------------------------------- ### ShouldBe DateTime Comparison with Tolerance Source: https://docs.shouldly.org/documentation/equality/shouldbe Compares DateTime values within a specified TimeSpan tolerance. This is useful when comparing dates and times where minor variations are acceptable. ```cs var date = new DateTime(2000, 6, 1); date.ShouldBe(new(2000, 6, 1, 1, 0, 1), TimeSpan.FromHours(1)); ``` -------------------------------- ### ShouldBeLessThanOrEqualTo Assertion Source: https://docs.shouldly.org/documentation/equality/greaterlessthan Use to assert that a value is less than or equal to a specified number. This assertion will fail only if the value is strictly greater than the specified number. ```cs var homer = new Person { Name = "Homer", Salary = 30001 }; homer.Salary.ShouldBeLessThanOrEqualTo(30000); ``` -------------------------------- ### Disable Line Ending Ignoring Source: https://docs.shouldly.org/documentation/equality/matchapproved Use this to enforce line ending sensitive comparisons. By default, Shouldly ignores line endings to prevent build server failures. ```csharp toVerify.ShouldMatchApproved(c => c.DoNotIgnoreLineEndings()) ``` -------------------------------- ### ShouldThrow for Func Source: https://docs.shouldly.org/documentation/exceptions/throw Use `Should.Throw` with a `Func` to assert that an asynchronous operation, represented by a function returning a `Task`, throws a specific exception type. This is useful for testing async methods that don't return a value directly. ```cs var homer = new Person { Name = "Homer", Salary = 30000 }; var denominator = 1; Should.Throw(() => { var task = Task.Factory.StartNew( () => { var y = homer.Salary / denominator; }); return task; }); ``` -------------------------------- ### Check if a collection does not contain an element matching a predicate Source: https://docs.shouldly.org/documentation/enumerable/contain Use `ShouldNotContain` with a predicate to assert that no element in the collection satisfies a given condition. This is useful for ensuring specific criteria are not met by any item. ```cs var mrBurns = new Person { Name = "Mr.Burns", Salary = 3000000 }; var kentBrockman = new Person { Name = "Homer", Salary = 3000000 }; var homer = new Person { Name = "Homer", Salary = 30000 }; var millionaires = new List { mrBurns, kentBrockman, homer }; millionaires.ShouldNotContain(m => m.Salary < 1000000); ``` -------------------------------- ### Check if an element is NOT one of several options Source: https://docs.shouldly.org/documentation/enumerable/oneof Use ShouldNotBeOneOf to assert that a given element is not present in the provided array of options. This is useful for ensuring a value is outside of an expected set. ```cs var apu = new Person { Name = "Apu" }; var homer = new Person { Name = "Homer" }; var skinner = new Person { Name = "Skinner" }; var barney = new Person { Name = "Barney" }; var wiggum = new Person { Name = "Wiggum" }; var theBeSharps = new List { apu, homer, skinner, barney, wiggum }; wiggum.ShouldNotBeOneOf(theBeSharps.ToArray()); ``` -------------------------------- ### DateTime Comparison with ShouldNotBe and Tolerance Source: https://docs.shouldly.org/documentation/equality/notbe Assert that a DateTime value is not within a specified TimeSpan tolerance of another DateTime. This is useful for comparing dates where slight variations are acceptable. ```cs var date = new DateTime(2000, 6, 1); date.ShouldNotBe(new(2000, 6, 1, 1, 0, 1), TimeSpan.FromHours(1.5)); ``` -------------------------------- ### Add Shouldly Assertion to Unit Test Source: https://docs.shouldly.org/documentation/getting-started This C# code demonstrates how to use Shouldly's `ShouldBe` assertion within an NUnit test method to verify the output of the `Program.TestWorks()` method. Ensure Shouldly is added as a NuGet package. ```csharp using NUnit.Framework; using Shouldly; public class Tests { [Test] public void Test1() { Program.TestWorks().ShouldBe("Works"); } } ``` -------------------------------- ### Assert a boolean is false Source: https://docs.shouldly.org/documentation/equality/truefalse Use `ShouldBeFalse()` to assert that a boolean value is false. This assertion will throw an exception if the value is true. ```cs var myValue = true; myValue.ShouldBeFalse(); ``` -------------------------------- ### Assert a boolean is true Source: https://docs.shouldly.org/documentation/equality/truefalse Use `ShouldBeTrue()` to assert that a boolean value is true. This assertion will throw an exception if the value is false. ```cs var myValue = false; myValue.ShouldBeTrue(); ``` -------------------------------- ### Assert String Is Not Null Source: https://docs.shouldly.org/documentation/string/null Use `ShouldNotBeNull` to assert that a string is not null. This is a common check to ensure a variable has been assigned a value. ```cs string? target = null; target.ShouldNotBeNull(); ``` -------------------------------- ### Use Caller Location for Filename Source: https://docs.shouldly.org/documentation/equality/matchapproved Instructs Shouldly to use the caller's location for the approval filename, which is useful when calling ShouldMatchApproved from utility methods. By default, it finds the first non-Shouldly method in the stack trace. ```csharp [Fact] public void MyTest() { SomeUtilityMethod("Foo"); } void SomeUtilityMethod(string toApprove) { toApprove.ShouldMatchApproved(c => c.UseCallerLocation()); } // -> MyTest.received.txt - without UseCallerLocation() the file would be called SomeUtilityMethod.received.txt ``` -------------------------------- ### Disable Diff Viewer Source: https://docs.shouldly.org/documentation/equality/matchapproved Prevents the diff viewer from opening. You can then use Shouldly's error messages and the provided command to approve changes. ```csharp toVerify.ShouldMatchApproved(c => c.NoDiff()) ``` -------------------------------- ### Assert String Ends With Specific Suffix Source: https://docs.shouldly.org/documentation/string/endwith Use ShouldEndWith to verify that a string terminates with the expected characters. An exception is thrown if the string does not end with the specified suffix. ```cs var target = "Homer"; target.ShouldEndWith("Bart"); ``` -------------------------------- ### Assert Action Completes Within Timeout Source: https://docs.shouldly.org/documentation/completein Use Should.CompleteIn to assert that an action, such as a delegate, finishes execution before a specified timeout. If the action exceeds the timeout, an exception is thrown with details about the failure and any custom message provided. ```csharp Should.CompleteIn( action: () => { Thread.Sleep(TimeSpan.FromSeconds(15)); }, timeout: TimeSpan.FromSeconds(0.5), customMessage: "Some additional context"); ``` -------------------------------- ### ShouldNotThrow Action - C# Source: https://docs.shouldly.org/documentation/exceptions/notthrow Use Should.NotThrow with an Action to assert that a block of code does not throw an exception. This is useful for testing operations that should complete successfully. ```csharp var homer = new Person { Name = "Homer", Salary = 30000 }; var denominator = 0; Should.NotThrow(() => { var y = homer.Salary / denominator; }); ``` -------------------------------- ### Check if Dictionary Does Not Contain a Key Source: https://docs.shouldly.org/documentation/dictionary/containkey Use ShouldNotContainKey to assert that a dictionary does not contain a specific key. This assertion will throw an exception if the key is found. ```cs var websters = new Dictionary { { "Chazzwazzers", "What Australians would have called a bull frog." } }; websters.ShouldNotContainKey("Chazzwazzers"); ``` -------------------------------- ### ShouldBe Assertion for Lists Source: https://docs.shouldly.org/documentation/equality/shouldbe-1 Use ShouldBe to assert that a list contains the exact same elements in the same order as another collection. Ensure all elements are correctly initialized before comparison. ```cs var apu = new Person { Name = "Apu" }; var homer = new Person { Name = "Homer" }; var skinner = new Person { Name = "Skinner" }; var barney = new Person { Name = "Barney" }; var theBeSharps = new List { homer, skinner, barney }; theBeSharps.ShouldBe(new[] { apu, homer, skinner, barney }); ``` -------------------------------- ### ShouldBe Enumerable of Numerics Comparison with Tolerance Source: https://docs.shouldly.org/documentation/equality/shouldbe Compares two enumerables of numeric types (float, decimal, double) within a specified tolerance. Each element is compared individually against its counterpart in the other enumerable. ```cs var firstSet = new[] { 1.23m, 2.34m, 3.45001m }; var secondSet = new[] { 1.4301m, 2.34m, 3.45m }; firstSet.ShouldBe(secondSet, 0.1m); ``` -------------------------------- ### Check if an element is one of several options Source: https://docs.shouldly.org/documentation/enumerable/oneof Use ShouldBeOneOf to assert that a given element is present in the provided array of options. This is useful for validating that a value falls within an expected set. ```cs var apu = new Person { Name = "Apu" }; var homer = new Person { Name = "Homer" }; var skinner = new Person { Name = "Skinner" }; var barney = new Person { Name = "Barney" }; var theBeSharps = new List { homer, skinner, barney }; apu.ShouldBeOneOf(theBeSharps.ToArray()); ``` -------------------------------- ### Set Global Default for Line Endings Source: https://docs.shouldly.org/documentation/equality/matchapproved Globally configures Shouldly to be line ending sensitive by default. This change applies before any tests execute. ```csharp ShouldlyConfiguration.ShouldMatchApprovedDefaults.DoNotIgnoreLineEndings() ``` -------------------------------- ### ShouldBeLessThan Assertion Source: https://docs.shouldly.org/documentation/equality/greaterlessthan Use to assert that a value is strictly less than a specified number. This assertion will fail if the value is equal to or greater than the specified number. ```cs var homer = new Person { Name = "Homer", Salary = 300000000 }; homer.Salary.ShouldBeLessThan(30000); ``` -------------------------------- ### ShouldBeGreaterThanOrEqualTo Assertion Source: https://docs.shouldly.org/documentation/equality/greaterlessthan Use to assert that a value is greater than or equal to a specified number. This assertion will fail only if the value is strictly less than the specified number. ```cs var mrBurns = new Person { Name = "Mr. Burns", Salary = 299999999 }; mrBurns.Salary.ShouldBeGreaterThanOrEqualTo(300000000); ``` -------------------------------- ### Assert Boolean Value with Shouldly Source: https://docs.shouldly.org/documentation/equality/shouldbe Use `ShouldBe` to assert that a boolean value is true. Provides additional context in the assertion message. The exception message will detail the expected and actual values. ```cs const bool myValue = false; myValue.ShouldBe(true, "Some additional context"); ``` -------------------------------- ### TimeSpan Comparison with ShouldNotBe and Tolerance Source: https://docs.shouldly.org/documentation/equality/notbe Assert that a TimeSpan value is not within a specified TimeSpan tolerance of another TimeSpan. This overload is useful for comparing durations where minor differences are expected. ```cs var timeSpan = TimeSpan.FromHours(1); timeSpan.ShouldNotBe(timeSpan.Add(TimeSpan.FromHours(1.1d)), TimeSpan.FromHours(1.5d)); ``` -------------------------------- ### Assert object is of a specific type with ShouldBeOfType Source: https://docs.shouldly.org/documentation/equality/oftype Use ShouldBeOfType to assert that an object is an instance of a particular type. This assertion will throw an exception if the object is not of the specified type. ```cs var theSimpsonsDog = new Cat { Name = "Santas little helper" }; theSimpsonsDog.ShouldBeOfType(); ``` -------------------------------- ### Check if a dynamic object has a property Source: https://docs.shouldly.org/documentation/dynamicshould Use DynamicShould.HaveProperty to assert that a dynamic object contains a specific property. This is useful for testing dynamic objects like ExpandoObject. ```cs dynamic theFuture = new ExpandoObject(); DynamicShould.HaveProperty(theFuture, "RobotTeachers"); ``` -------------------------------- ### Check if a List is a Subset of Another List in C# Source: https://docs.shouldly.org/documentation/enumerable/subsetof Use ShouldBeSubsetOf to assert that all elements in `simpsonsKids` are present in `simpsonsFamily`. This assertion is useful for validating collection relationships. ```csharp var lisa = new Person { Name = "Lisa" }; var bart = new Person { Name = "Bart" }; var maggie = new Person { Name = "Maggie" }; var homer = new Person { Name = "Homer" }; var marge = new Person { Name = "Marge" }; var ralph = new Person { Name = "Ralph" }; var simpsonsKids = new List { bart, lisa, maggie, ralph }; var simpsonsFamily = new List { lisa, bart, maggie, homer, marge }; simpsonsKids.ShouldBeSubsetOf(simpsonsFamily); ``` -------------------------------- ### ShouldNotThrow FuncOfTask - C# Source: https://docs.shouldly.org/documentation/exceptions/notthrow Use Should.NotThrow with a Func that returns a Task to assert that the asynchronous operation does not throw an exception. Ensure the Task is returned from the Func. ```csharp var homer = new Person { Name = "Homer", Salary = 30000 }; var denominator = 0; Should.NotThrow(() => { var task = Task.Factory.StartNew( () => { var y = homer.Salary / denominator; }); return task; }); ``` -------------------------------- ### ShouldNotThrow Action Extension - C# Source: https://docs.shouldly.org/documentation/exceptions/notthrow Use the ShouldNotThrow extension method on an Action to assert that the action does not throw an exception. This provides a more fluent syntax for the same assertion. ```csharp var homer = new Person { Name = "Homer", Salary = 30000 }; var denominator = 0; var action = () => { var y = homer.Salary / denominator; }; action.ShouldNotThrow(); ``` -------------------------------- ### Class constraint added to ShouldNotBeNull Source: https://docs.shouldly.org/documentation/3to4 In v4, `ShouldNotBeNull` now has a class constraint, preventing assertions on non-nullable types that logically cannot be null. This change helps identify and fix nonsensical tests. ```csharp const long value = 1; value.ShouldNotBeNull(); ``` -------------------------------- ### Assert Object Identity Difference with ShouldNotBeSameAs Source: https://docs.shouldly.org/documentation/equality/sameas Use ShouldNotBeSameAs to assert that two object references do not point to the same object in memory. This is the inverse of ShouldBeSameAs. ```cs var person = new Person { Name = "Armin Tamzarian" }; person.ShouldNotBeSameAs(person); ``` -------------------------------- ### ShouldBeGreaterThan Assertion Source: https://docs.shouldly.org/documentation/equality/greaterlessthan Use to assert that a value is strictly greater than a specified number. This assertion will fail if the value is equal to or less than the specified number. ```cs var mrBurns = new Person { Name = "Mr. Burns", Salary = 30000 }; mrBurns.Salary.ShouldBeGreaterThan(300000000); ``` -------------------------------- ### Exception message for ShouldHaveSingleItem failure Source: https://docs.shouldly.org/documentation/enumerable/have This shows the exception message format when a collection does not contain a single item. It clearly indicates the expected count, the actual count, and the contents of the collection. ```text simpsonsBabies should have single item but had 2 items and was [Homer, Maggie] ``` -------------------------------- ### Check if Dictionary Contains a Key Source: https://docs.shouldly.org/documentation/dictionary/containkey Use ShouldContainKey to assert that a dictionary contains a specific key. This assertion will throw an exception if the key is not found. ```cs var websters = new Dictionary { { "Embiggen", "To empower or embolden." } }; websters.ShouldContainKey("Cromulent"); ``` -------------------------------- ### Assert object is not of a specific type with ShouldNotBeOfType Source: https://docs.shouldly.org/documentation/equality/oftype Use ShouldNotBeOfType to assert that an object is not an instance of a particular type. This assertion will throw an exception if the object is of the specified type. ```cs var theSimpsonsDog = new Cat { Name = "Santas little helper" }; theSimpsonsDog.ShouldNotBeOfType(); ``` -------------------------------- ### Verify Type Assignability with ShouldBeAssignableTo Source: https://docs.shouldly.org/documentation/equality/assignableto Use ShouldBeAssignableTo to assert that an object is assignable to a specified type. This is useful for checking inheritance or interface implementation. ```cs var theSimpsonsDog = new Person { Name = "Santas little helper" }; theSimpsonsDog.ShouldBeAssignableTo(); ``` -------------------------------- ### ShouldNotThrow Func - C# Source: https://docs.shouldly.org/documentation/exceptions/notthrow Use Should.NotThrow with a Func to assert that the function execution does not throw an exception. This is suitable for testing functions that return a value but should not error. ```csharp string? name = null; Should.NotThrow(() => new Person(name!)); ``` -------------------------------- ### Assert value is not within a range Source: https://docs.shouldly.org/documentation/equality/inrange Use ShouldNotBeInRange to assert that a numeric value does not fall between a specified minimum and maximum (inclusive). This is useful for validating that a value is outside expected bounds. ```cs var mrBurns = new Person { Name = "Mr. Burns", Salary = 30000 }; mrBurns.Salary.ShouldNotBeInRange(30000, 40000); ``` -------------------------------- ### Assert value is within a range Source: https://docs.shouldly.org/documentation/equality/inrange Use ShouldBeInRange to assert that a numeric value falls between a specified minimum and maximum (inclusive). Ensure the value and range bounds are of compatible types. ```cs var homer = new Person { Name = "Homer", Salary = 300000000 }; homer.Salary.ShouldBeInRange(30000, 40000); ``` -------------------------------- ### Assert String Does Not End With Specific Suffix Source: https://docs.shouldly.org/documentation/string/endwith Use ShouldNotEndWith to verify that a string does not terminate with the specified characters. An exception is thrown if the string unexpectedly ends with the specified suffix. ```cs var target = "Homer Simpson"; target.ShouldNotEndWith("Simpson"); ``` -------------------------------- ### Check if a collection contains an element matching a predicate Source: https://docs.shouldly.org/documentation/enumerable/contain Use `ShouldContain` with a predicate to assert that at least one element in the collection satisfies a given condition. This is useful for checking properties or complex criteria. ```cs var homer = new Person { Name = "Homer", Salary = 30000 }; var moe = new Person { Name = "Moe", Salary = 20000 }; var barney = new Person { Name = "Barney", Salary = 0 }; var millionaires = new List { homer, moe, barney }; millionaires.ShouldContain(m => m.Salary > 1000000); ``` -------------------------------- ### Assert String Contains Substring Source: https://docs.shouldly.org/documentation/string/contain Use ShouldContain to verify if a string includes a specific substring. This assertion is case-insensitive. ```cs var target = "Homer"; target.ShouldContain("Bart"); ``` -------------------------------- ### Check if a collection contains a specific object Source: https://docs.shouldly.org/documentation/enumerable/contain Use `ShouldContain` to assert that a collection includes a specific object. Ensure the object's equality is correctly defined. ```cs var mrBurns = new Person { Name = "Mr.Burns", Salary = 3000000 }; var kentBrockman = new Person { Name = "Kent Brockman", Salary = 3000000 }; var homer = new Person { Name = "Homer", Salary = 30000 }; var millionaires = new List { kentBrockman, homer }; millionaires.ShouldContain(mrBurns); ``` -------------------------------- ### ShouldNotThrow Func Extension - C# Source: https://docs.shouldly.org/documentation/exceptions/notthrow Use the ShouldNotThrow extension method on a Func to assert that the function does not throw an exception. This offers a concise way to test function execution. ```csharp string? name = null; var func = () => new Person(name!); func.ShouldNotThrow(); ``` -------------------------------- ### Assert String Does Not Contain Substring Source: https://docs.shouldly.org/documentation/string/contain Use ShouldNotContain to ensure a string does not include a specific substring. This assertion is case-insensitive. ```cs var target = "Homer"; target.ShouldNotContain("Home"); ``` -------------------------------- ### Exception Message for ShouldBe Failure Source: https://docs.shouldly.org/documentation/equality/shouldbe-1 When a ShouldBe assertion fails for an enumerable, the exception message clearly indicates the expected and actual contents, highlighting the differences. ```text theBeSharps should be [Apu, Homer, Skinner, Barney] but was [Homer, Skinner, Barney] difference [*Homer*, *Skinner*, *Barney*, *] ``` -------------------------------- ### Exception for Duplicated Elements Source: https://docs.shouldly.org/documentation/enumerable/unique When `ShouldBeUnique` fails, it throws an exception detailing which element was duplicated and its value. This helps in identifying and resolving uniqueness violations. ```text simpsonsKids should be unique but [Maggie] was duplicated ``` -------------------------------- ### Assert Enum Does Not Have Flag Source: https://docs.shouldly.org/documentation/equality/haveflag Use ShouldNotHaveFlag to verify that an enum value does not contain a specific flag. This is useful for negative assertions. ```cs var actual = TestEnum.FlagOne; var value = TestEnum.FlagOne; actual.ShouldNotHaveFlag(value); ``` -------------------------------- ### Long Comparison with ShouldNotBe Source: https://docs.shouldly.org/documentation/equality/notbe Assert that a long integer value is not equal to a specific integer. This overload handles comparisons between long and int types. ```cs const long aLong = 1L; aLong.ShouldNotBe(1); ``` -------------------------------- ### Assert String Contains Substring Without Whitespace Source: https://docs.shouldly.org/documentation/string/contain Use ShouldContainWithoutWhitespace to check if a string contains a substring after removing all whitespace from both the string and the substring. This is useful for comparing strings where whitespace might differ. ```cs var target = "Homer Simpson"; target.ShouldContainWithoutWhitespace(" Bart Simpson "); ``` -------------------------------- ### Assert Enum Has Flag Source: https://docs.shouldly.org/documentation/equality/haveflag Use ShouldHaveFlag to verify that an enum value contains a specific flag. Ensure the enum type and the flag value are correctly defined. ```cs var actual = TestEnum.FlagTwo; var value = TestEnum.FlagOne; actual.ShouldHaveFlag(value); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.