{"_id":"55435bf2795b590d001dc8a3","project":"553dec691a946a0d00ad6f27","category":{"_id":"5543585f795b590d001dc89a","version":"553dec691a946a0d00ad6f2a","__v":9,"pages":["554358c8b7f4540d00fcef43","55435b69b7f4540d00fcef46","55435bf2795b590d001dc8a3","55435ec262b30e0d004b1706","555636f626e9bc0d0044ea81","55563946ea5e120d00188550","555639cc26e9bc0d0044ea8d","5561dd7bb40338210035f905","56bafe8ccec63e0d00f0d2eb"],"project":"553dec691a946a0d00ad6f27","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-05-01T10:41:35.279Z","from_sync":false,"order":1,"slug":"usage","title":"Usage"},"user":"54c4b05742190d0d00f5fbde","version":{"_id":"553dec691a946a0d00ad6f2a","project":"553dec691a946a0d00ad6f27","__v":2,"createdAt":"2015-04-27T07:59:37.477Z","releaseDate":"2015-04-27T07:59:37.477Z","categories":["553dec691a946a0d00ad6f2b","5543585f795b590d001dc89a"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.0.0","version":"1.0"},"__v":6,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-05-01T10:56:50.267Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":5,"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Anonymous value support\"\n}\n[/block]\nThe use of the [anonymous variable pattern](http://blogs.msdn.com/b/ploeh/archive/2008/11/17/anonymous-variables.aspx) is a good pattern to use when you want to use values in your tests whose exact value isn't significant. By including a specific value you are making it look like that value is important in some way, which steals cognitive load from the test reader while they need to figure out that the value doesn't actually matter.\n\nThis is relevant when defining a test data builder because of the initial values that you set the different parameters to by default. For instance, if you had code like this:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"class CustomerBuilder : TestDataBuilder<Customer, CustomerBuilder>\\n{\\n    public CustomerBuilder()\\n    {\\n        WithFirstName(\\\"Rob\\\");\\n        WithLastName(\\\"Moore\\\");\\n        WhoJoinedIn(2013);\\n    }\\n\\n    public CustomerBuilder WithFirstName(string firstName)\\n    {\\n        return Set(x => x.FirstName, firstName);\\n    }\\n  \\n    ...\\n}\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\nIn that case the values \"Rob\", \"Moore\" and 2013 look significant on initial inspection. In reality it shouldn't matter what they are; any test where those values matter should specify them to [make the intent clear](http://robdmoore.id.au/blog/2014/02/23/making-intent-clear-derived-values-automated-testing-series/).\n\nWhen you use the Get method in a builder and you haven't called Set it will automatically generate an anonymous value for each requested value. This not only allows you to get rid of those insignificant values, but it allows you to trim down the constructor of your builder - making the builders terser and quicker to write.\n\nGiven we aren't talking about variables but rather values we have thus named the pattern anonymous values rather than anonymous variables.\n\nThere are a number of default conventions that are followed to determine what value to use via the [Anonymous Value Fixture](https://github.com/TestStack/TestStack.Dossier/blob/master/TestStack.Dossier/AnonymousValueFixture.cs) class. This works through the application of anonymous value suppliers - which are processed in order to determine if a value can be provided and if so a value is retrieved. At the time of writing the default suppliers are the following (applied in this order):\n\n  * `DefaultEmailValueSupplier` - Supplies an email address for all string properties with a property name containing 'email'\n  * `DefaultFirstNameValueSupplier` - Supplies a first name for all string properties with a property name containing 'firstname' (case insensitive)\n  * `DefaultLastNameValueSupplier` - Supplies a last name for all string properties with a property name containing 'lastname' or 'surname' (case insensitive)\n  * `DefaultStringValueSupplier` - Supplies the property name followed by a random GUID for all string properties\n  * `DefaultValueTypeValueSupplier` - Supplies an [AutoFixture generated value](http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture/) for any value types (e.g. int, double, etc.)\n  * `DefaultValueSupplier` - Supplies default(T)\n\nThis gets you started for the most basic of cases, but from there you have a lot of flexibility to apply your own suppliers on both a global basis (via `AnonymousValueFixture.GlobalValueSuppliers`) and a local basis for each fixture instance (via `fixture.LocalValueSuppliers`) - you just need to implement `IAnonymousValueSupplier`. See the [tests for examples](https://github.com/TestStack/TestStack.Dossier/blob/master/TestStack.Dossier.Tests/GetAnonymousTests.cs).\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Standalone value generation\"\n}\n[/block]\nWhile `AnonymousValueFixture` is integrated in to the test data builder infrastructure, it's perfectly acceptable (and encouraged!) to use it on it's own as a powerful way to generate anonymous values for your tests. See below the canonical example of a calculator add method test. Note: this test is also a good example of the [Derived Values pattern](http://robdmoore.id.au/blog/2014/02/23/making-intent-clear-derived-values-automated-testing-series/).\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"public class CalculatorShould\\n{\\n  private AnonymousValueFixture Any = new AnonymousValueFixture();\\n  private _calculator = new Calculator();\\n  \\n  public void AddTwoPositiveNumbersCorrectly()\\n  {\\n    var x = Any.PositiveInteger();\\n    var y = Any.PositiveInteger();\\n    var expectedResult = x + y;\\n    \\n    var result = _calculator.Add(x, y);\\n    \\n    result.ShouldBe(expectedResult);\\n  }\\n}\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Equivalence classes support\"\n}\n[/block]\nThe principle of [constrained non-determinism](http://blog.ploeh.dk/2009/03/05/ConstrainedNon-Determinism/) frees you from having to worry about the fact that anonymous values can be random as long as they fall within the [equivalence class](http://xunitpatterns.com/equivalence%20class.html) of the value that is required for your test.\n\nWe think the same concept can and should be applied to test data builders. More than that, we think it enhances the ability for the test data builders to [act as documentation](http://robdmoore.id.au/blog/2013/05/26/test-data-generation-the-right-way-object-mother-test-data-builders-nsubstitute-nbuilder/). Having a constructor that reads like this for instance tells you something interesting about the Year property:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"class CustomerBuilder : TestDataBuilder<Customer, CustomerBuilder>\\n{\\n    public CustomerBuilder()\\n    {\\n        WhoJoinedIn(Any.YearAfter2001());\\n    }\\n\\n    ...\\n}\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\nYou may well use value objects that protect and describe the integrity of the data (which is great), but you can still create an equivalence class for the creation of the value object so I still think it's relevant beyond primitives.\n\nWe have some built-in equivalence classes that you can use to get started quickly for common scenarios. At the time of writing the following are available (as extension methods of the `AnonymousValueFixture` class that is defined in a property called `Any` on the test data builder base class):\n\n  * `Any.String()`\n  * `Any.StringMatching(string regexPattern)`\n  * `Any.StringStartingWith(string prefix)`\n  * `Any.StringEndingWith(string suffix)`\n  * `Any.StringOfLength(int length)`\n  * `Any.PositiveInteger()`\n  * `Any.NegativeInteger()`\n  * `Any.IntegerExcept(int[] exceptFor)`\n  * `Any.Of<TEnum>()`\n  * `Any.Except<TEnum>(TEnum[] except)`\n  * `Any.EmailAddress()`\n  * `Any.UniqueEmailAddress()`\n  * `Any.Language()`\n  * `Any.FemaleFirstName()`\n  * `Any.MaleFirstName()`\n  * `Any.FirstName()`\n  * `Any.LastName()`\n  * `Any.Suffix()`\n  * `Any.Title()`\n  * `Any.Continent()`\n  * `Any.Country()`\n  * `Any.CountryCode()`\n  * `Any.Latitude()`\n  * `Any.Longitude()`\n\nThere is nothing stopping you using the anonymous value fixture outside of the test data builders - you can create a property called `Any` that is an instance of the `AnonymousValueFixture` class in any test class.\n\nAlso, you can easily create your own extension methods for the values and data that makes sense for your application. See the [source code for examples to copy](https://github.com/TestStack/TestStack.Dossier/tree/master/TestStack.Dossier/EquivalenceClasses).\n\nA couple of things to note:\n\n* You have the ability to stash information in the fixture by using the dynamic `Bag` property\n* You also have an `AutoFixture` instance available to use via the `Fixture` property\n\n> **Side note:** We feel that Dossier does some things that are not easy to do in AutoFixture, hence why we don't \"just use AutoFixture\" - we see Dossier as complimentary to AutoFixture because they are trying to achieve different (albeit related) things.\n\nWe got the idea for the `Any.Whatever()` syntax from the [TDD Toolkit by Grzegorz Gałęzowski](https://github.com/grzesiek-galezowski/tdd-toolkit). We really like it and we also highly recommend his [TDD e-book](https://github.com/grzesiek-galezowski/tdd-ebook).","excerpt":"","slug":"anonymous-values-and-equivalence-classes","type":"basic","title":"Anonymous Values and Equivalence Classes"}

Anonymous Values and Equivalence Classes


[block:api-header] { "type": "basic", "title": "Anonymous value support" } [/block] The use of the [anonymous variable pattern](http://blogs.msdn.com/b/ploeh/archive/2008/11/17/anonymous-variables.aspx) is a good pattern to use when you want to use values in your tests whose exact value isn't significant. By including a specific value you are making it look like that value is important in some way, which steals cognitive load from the test reader while they need to figure out that the value doesn't actually matter. This is relevant when defining a test data builder because of the initial values that you set the different parameters to by default. For instance, if you had code like this: [block:code] { "codes": [ { "code": "class CustomerBuilder : TestDataBuilder<Customer, CustomerBuilder>\n{\n public CustomerBuilder()\n {\n WithFirstName(\"Rob\");\n WithLastName(\"Moore\");\n WhoJoinedIn(2013);\n }\n\n public CustomerBuilder WithFirstName(string firstName)\n {\n return Set(x => x.FirstName, firstName);\n }\n \n ...\n}", "language": "csharp" } ] } [/block] In that case the values "Rob", "Moore" and 2013 look significant on initial inspection. In reality it shouldn't matter what they are; any test where those values matter should specify them to [make the intent clear](http://robdmoore.id.au/blog/2014/02/23/making-intent-clear-derived-values-automated-testing-series/). When you use the Get method in a builder and you haven't called Set it will automatically generate an anonymous value for each requested value. This not only allows you to get rid of those insignificant values, but it allows you to trim down the constructor of your builder - making the builders terser and quicker to write. Given we aren't talking about variables but rather values we have thus named the pattern anonymous values rather than anonymous variables. There are a number of default conventions that are followed to determine what value to use via the [Anonymous Value Fixture](https://github.com/TestStack/TestStack.Dossier/blob/master/TestStack.Dossier/AnonymousValueFixture.cs) class. This works through the application of anonymous value suppliers - which are processed in order to determine if a value can be provided and if so a value is retrieved. At the time of writing the default suppliers are the following (applied in this order): * `DefaultEmailValueSupplier` - Supplies an email address for all string properties with a property name containing 'email' * `DefaultFirstNameValueSupplier` - Supplies a first name for all string properties with a property name containing 'firstname' (case insensitive) * `DefaultLastNameValueSupplier` - Supplies a last name for all string properties with a property name containing 'lastname' or 'surname' (case insensitive) * `DefaultStringValueSupplier` - Supplies the property name followed by a random GUID for all string properties * `DefaultValueTypeValueSupplier` - Supplies an [AutoFixture generated value](http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture/) for any value types (e.g. int, double, etc.) * `DefaultValueSupplier` - Supplies default(T) This gets you started for the most basic of cases, but from there you have a lot of flexibility to apply your own suppliers on both a global basis (via `AnonymousValueFixture.GlobalValueSuppliers`) and a local basis for each fixture instance (via `fixture.LocalValueSuppliers`) - you just need to implement `IAnonymousValueSupplier`. See the [tests for examples](https://github.com/TestStack/TestStack.Dossier/blob/master/TestStack.Dossier.Tests/GetAnonymousTests.cs). [block:api-header] { "type": "basic", "title": "Standalone value generation" } [/block] While `AnonymousValueFixture` is integrated in to the test data builder infrastructure, it's perfectly acceptable (and encouraged!) to use it on it's own as a powerful way to generate anonymous values for your tests. See below the canonical example of a calculator add method test. Note: this test is also a good example of the [Derived Values pattern](http://robdmoore.id.au/blog/2014/02/23/making-intent-clear-derived-values-automated-testing-series/). [block:code] { "codes": [ { "code": "public class CalculatorShould\n{\n private AnonymousValueFixture Any = new AnonymousValueFixture();\n private _calculator = new Calculator();\n \n public void AddTwoPositiveNumbersCorrectly()\n {\n var x = Any.PositiveInteger();\n var y = Any.PositiveInteger();\n var expectedResult = x + y;\n \n var result = _calculator.Add(x, y);\n \n result.ShouldBe(expectedResult);\n }\n}", "language": "csharp" } ] } [/block] [block:api-header] { "type": "basic", "title": "Equivalence classes support" } [/block] The principle of [constrained non-determinism](http://blog.ploeh.dk/2009/03/05/ConstrainedNon-Determinism/) frees you from having to worry about the fact that anonymous values can be random as long as they fall within the [equivalence class](http://xunitpatterns.com/equivalence%20class.html) of the value that is required for your test. We think the same concept can and should be applied to test data builders. More than that, we think it enhances the ability for the test data builders to [act as documentation](http://robdmoore.id.au/blog/2013/05/26/test-data-generation-the-right-way-object-mother-test-data-builders-nsubstitute-nbuilder/). Having a constructor that reads like this for instance tells you something interesting about the Year property: [block:code] { "codes": [ { "code": "class CustomerBuilder : TestDataBuilder<Customer, CustomerBuilder>\n{\n public CustomerBuilder()\n {\n WhoJoinedIn(Any.YearAfter2001());\n }\n\n ...\n}", "language": "csharp" } ] } [/block] You may well use value objects that protect and describe the integrity of the data (which is great), but you can still create an equivalence class for the creation of the value object so I still think it's relevant beyond primitives. We have some built-in equivalence classes that you can use to get started quickly for common scenarios. At the time of writing the following are available (as extension methods of the `AnonymousValueFixture` class that is defined in a property called `Any` on the test data builder base class): * `Any.String()` * `Any.StringMatching(string regexPattern)` * `Any.StringStartingWith(string prefix)` * `Any.StringEndingWith(string suffix)` * `Any.StringOfLength(int length)` * `Any.PositiveInteger()` * `Any.NegativeInteger()` * `Any.IntegerExcept(int[] exceptFor)` * `Any.Of<TEnum>()` * `Any.Except<TEnum>(TEnum[] except)` * `Any.EmailAddress()` * `Any.UniqueEmailAddress()` * `Any.Language()` * `Any.FemaleFirstName()` * `Any.MaleFirstName()` * `Any.FirstName()` * `Any.LastName()` * `Any.Suffix()` * `Any.Title()` * `Any.Continent()` * `Any.Country()` * `Any.CountryCode()` * `Any.Latitude()` * `Any.Longitude()` There is nothing stopping you using the anonymous value fixture outside of the test data builders - you can create a property called `Any` that is an instance of the `AnonymousValueFixture` class in any test class. Also, you can easily create your own extension methods for the values and data that makes sense for your application. See the [source code for examples to copy](https://github.com/TestStack/TestStack.Dossier/tree/master/TestStack.Dossier/EquivalenceClasses). A couple of things to note: * You have the ability to stash information in the fixture by using the dynamic `Bag` property * You also have an `AutoFixture` instance available to use via the `Fixture` property > **Side note:** We feel that Dossier does some things that are not easy to do in AutoFixture, hence why we don't "just use AutoFixture" - we see Dossier as complimentary to AutoFixture because they are trying to achieve different (albeit related) things. We got the idea for the `Any.Whatever()` syntax from the [TDD Toolkit by Grzegorz Gałęzowski](https://github.com/grzesiek-galezowski/tdd-toolkit). We really like it and we also highly recommend his [TDD e-book](https://github.com/grzesiek-galezowski/tdd-ebook).