{"project":"54c51af02418480d0028a2b4","version":{"__v":3,"_id":"54c51af02418480d0028a2b7","project":"54c51af02418480d0028a2b4","createdAt":"2015-01-25T16:33:52.715Z","releaseDate":"2015-01-25T16:33:52.715Z","categories":["54c51af12418480d0028a2b8","54cd18ea380ecd0d00ca1961","54cd18f0380ecd0d00ca1962"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.0.0","version":"1.0"},"category":{"__v":4,"_id":"54cd18ea380ecd0d00ca1961","pages":["54cd193f3be4370d0082ad26","54cd1967380ecd0d00ca1963","54cd19841097810d0009ab88","54cd199b1097810d0009ab8a"],"project":"54c51af02418480d0028a2b4","version":"54c51af02418480d0028a2b7","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-01-31T18:03:22.937Z","from_sync":false,"order":2,"slug":"customization","title":"Customization"},"_id":"54cd199b1097810d0009ab8a","user":"54c4ca54686bce0d00efe1b9","__v":0,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-01-31T18:06:19.865Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"auth":"required","params":[],"url":""},"isReference":false,"order":999,"body":"# Introduction #\nI’ve been using BDDfy with NUnit for writing acceptance tests for quite awhile now. But for unit testing I have continued to use mspec with [machine fakes](https://github.com/machine/machine.fakes) and Moq for auto-mocking. The more I used BDDfy, the more I liked it, and the less I liked the context switch into another framework. I found myself wanting to write unit tests in the Given When Then format and didn't like having to maintain two sets of helper code for NUnit and mspec. I loved the reporting in BDDfy and started to think it would be pretty cool to have similar reporting for my unit tests. Basically, I wanted a consistent experience across all my automated testing.\n\nMSpec uses the [testcase class per fixture](http://xunitpatterns.com/Testcase%20Class%20per%20Fixture.html) style of testing, which is how I use BDDfy for acceptance testing, so it makes sense to continue with that style for the BDDfy unit tests. When I am doing acceptance tests I have a base ScenarioFor< T> class, where the T represents the System Under Test (SUT). Because these are full system tests, I resolve this SUT using the same inversion of control container that my application uses, which works nicely. The IoC container acts as a [SUT factory](http://blog.ploeh.dk/2009/02/13/SUTFactory/). With unit tests, I also want to have a SUT factory, but instead I want it to be an auto-mocking container.\n\nWhen we started writing unit tests for the [Seleno](http://teststack.github.io/pages/Seleno.html) project, I thought it would be a good opportunity to try some of these ideas out.\n\n# Specification Base Fixture #\nThe Specification base fixture class wires up BDDFy. It provides methods that BDDfy knows about in its default configuration for setting up and tearing down the fixture (each test class will implement its own specific Given When Then methods that BDDfy will also find). The Run method has the NUnit Test attribute and so will be called by the testing framework and it just calls BDDFy to run the test. I prefer to use NUnit myself, but you could just as easily substitute XUnit or MsTest attributes if you prefer. One thing I really like about this approach is that I only have to put the TestFixture and Test attributes in this one class and then all of the test classes I create inherit them and don't need any attributes. All the test runners still picks the classes up as tests and ReSharper even puts its little run test icons in each test class as normal. This class is also the one place that BDDfy gets called. \n\n    [TestFixture]\n    public abstract class Specification : ISpecification\n    {\n        [Test]\n        public virtual void Run()\n        {\n            string title = BuildTitle();\n            this.BDDfy(title, Category);\n        }\n\n        protected virtual string BuildTitle()\n        {\n            return Title ?? GetType().Name.Humanize(LetterCasing.Title);\n        }\n\n        // BDDfy methods\n        public virtual void EstablishContext() { }\n        public virtual void Setup() { }\n        public virtual void TearDown() { }\n\n        public virtual Type Story { get { return GetType(); } }\n        public virtual string Title { get; set; }\n        public string Category { get; set; }\n    }\n\n#Auto-Mocking #\nThe SpecificationFor<T> class inherits from the Specification class and adds an auto-mocking container for creating the SUT. An auto-mocking container decouples a unit test from the mechanics of creating the SUT and automatically supplies dynamic mocks in place of all of the SUT's dependencies. They are commonly implemented by combining an IoC container with a mocking framework, which is what I will be doing here. I prefer [NSubstitute](http://nsubstitute.github.io/) for mocking these days, so my friend [Rob Moore's](http://robdmoore.id.au/) [AutoSubstitute](http://nuget.org/packages/AutofacContrib.NSubstitute) auto-mocking container is ideal.\n\nThe AutoSubstitute field provides access to the container for full access to its functionality. SubstituteFor is provided as a convenience method to gain access to NSubstitute substitutes.\n\n    public abstract class SpecificationFor<T> : Specification\n    {\n        public T SUT { get; set; }\n        protected AutoSubstitute AutoSubstitute;\n\n        protected SpecificationFor()\n        {\n            AutoSubstitute = CreateContainer();\n            InitialiseSystemUnderTest();\n        }\n\n        public virtual void InitialiseSystemUnderTest()\n        {\n             SUT = AutoSubstitute.Resolve<T>();\n        }\n\n        public TSubstitute SubstituteFor<TSubstitute>() where TSubstitute : class\n        {\n            return AutoSubstitute.ResolveAndSubstituteFor<TSubstitute>();\n        }\n\n        public override Type Story\n        {\n            get { return typeof(T); }\n        }\n\n        private static AutoSubstitute CreateContainer()\n        {\n            Action<ContainerBuilder> autofacCustomisation = c => c\n                .RegisterType<T>()\n                .FindConstructorsWith(t =>  t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n                .PropertiesAutowired();\n            return new AutoSubstitute(autofacCustomisation);\n        }\n    }\n\nNotice that the InitialiseSystemUnderTest is virtual, so if you need to create the SUT yourself rather than having AutoSubstitute do it then you can just override it in your test class. It runs before any of the test methods so they can all safely interact with the SUT confident that it has been created.\n\n# What's in a Story? #\nWhen moving from scenarios to unit tests I had to think what I wanted to do with the Story that is part of BDD. BDDfy actually doesn't require stories, so one option was to do nothing. However, when you don't have a story the report shows the namespace instead, and I don't find that particularly helpful or attractive. A Story's purpose in BDD is to group related Scenarios and to provide metadata about that grouping, so I think the same logic can be applied to unit tests. \n\nBy creating a base specification class that related tests inherit from, they will all be grouped together on the report, and the name of that class will be used in the heading, much like a Story grouping would look like on a BDD report. This class is often a convenient place to create variables that are common to all of the test cases. So, for example, if you create a base class called PageNavigatorSpecification, the report grouping will read \"Specifications For: Page Navigator.\" That is achieved by adding the following custom story metadata scanner.\n\n    public class SpecStoryMetaDataScanner : IStoryMetaDataScanner\n    {\n        public virtual StoryMetaData Scan(object testObject, Type explicityStoryType = null)\n        {\n            var specification = testObject as ISpecification;\n            if (specification == null)\n                return null;\n\n            string specificationTitle = CreateSpecificationTitle(specification);\n            var story = new StoryAttribute() {Title = specificationTitle};\n            return new StoryMetaData(specification.Story, story);\n        }\n\n        private string CreateSpecificationTitle(ISpecification specification)\n        {\n            string suffix = \"Specification\";\n            string title = specification.Story.Name;\n            if (title.EndsWith(suffix))\n                title = title.Remove(title.Length - suffix.Length, suffix.Length);\n            return title;\n        }\n    }\n\nAnd here is what the specifications look like in the BDDfy report:\n\n![BDDfy unit test report](/img/BDDfy/Customizing/bddfy-unit-test-report.png)\n\n# Unit Testing #\nHere is an example of some tests that we have written for Seleno using this approach. Firstly, an example of a Specification class, the grouping class analagous to the BDDFy story that all the PageReader specification classes will inherit from. There is normally no need to override the Story as the SpecificationFor class will automatically convert the generic T into an English name. In this case though it will convert PageReader< TestViewModel> into PageReader`, so it is a convenient hack to override the property with PageReaderSpecification which will more attractively produce \"Page Reader\" on the report.\n\n    abstract class PageReaderSpecification : SpecificationFor<PageReader<TestViewModel>>\n    {\n        public override Type Story\n        {\n            get { return typeof (PageReaderSpecification); }\n        }\n    }\n\nEach specification for the PageReader component inherits from the PageReaderSpecification. There are often no Given steps as the auto-mocking container has taken care of instantiating the SUT for you. It has also created a Substitute for the IExecutor dependency of the PageReader class and in the verification phase of the test you can just call SubstituteFor< IExecutor> to call NSubstitute verification methods on the substitute.  \n\n    class When_checking_an_element_exists_and_is_visible_with_property : PageReaderSpecification\n    {\n        public When_checking_an_element_exists_and_is_visible_with_property()\n        {\n            SUT.ExistsAndIsVisible(x => x.Item);\n        }\n\n        public void Then_it_should_execute_the_relevant_script_with_jquery_id_selector()\n        {\n            SubstituteFor<IExecutor>()\n                .Received()\n                .ScriptAndReturn<bool>(\"$(\\\"#Item\\\").is(':visible')\");\n        }\n    }\n\nThis test shows that you can also setup Substitute behaviour in the setup phase of the test.\n\n\tclass When_getting_a_web_element_strongly_typed_text : PageReaderSpecification\n    {\n        private DateTime _result;\n        private readonly DateTime _the03rdOfJanuary2012At21h21 = new DateTime(2012, 01, 03, 21, 21, 00);\n\n        [Given(\"Given a web element contains the text 03/01/2012 21:21\")]\n        public void Given_a_web_element_contains_the_text_03_01_2012_21_21()\n        {\n            SubstituteFor<IElementFinder>()\n                .Element(Arg.Any<By>())\n                .Returns(SubstituteFor<IWebElement>());\n\n            SubstituteFor<IWebElement>().Text.Returns(\"03/01/2012 21:21\");\n        }\n\n        public void When_getting_the_web_element_matching_a_view_model_property()\n        {\n            _result = SUT.TextAsType(viewModel => viewModel.Modified);\n        }\n\n        public void Then_it_should_return_the_corresponding_typed_value_of_the_web_element_text()\n        {\n            _result.Should().Be(_the03rdOfJanuary2012At21h21);\n        }\n    }\n\n# Another approach #\nIt's worth looking at another example of sharing a base context class. As I said above, it is not just for making the report work, it can be quite helpful to share context there. [Matt Honeycutt](http://trycatchfail.com/blog/) has an interesting style for reusing context classes in his very cool [SpecsFor BDD framework](http://specsfor.com/) that this approach also supports:\n\n\tpublic class given\n    {\n        public abstract class the_command_is_valid : SpecificationFor<CommandProcessor>\n        {\n            protected void Given_the_command_is_valid()\n            {\n                SubFor<IValidateCommand<TestCommand>>().Validate(Arg.Any<TestCommand>()).Returns(new ExecutionResult(null));\n                SubFor<IValidateCommandFactory>().ValidatorForCommand(Arg.Any<TestCommand>()).Returns(SubFor<IValidateCommand<TestCommand>>());\n            }\n        }\n    }\n\n    public class processing_a__valid_command : given.the_command_is_valid\n    {\n        private TestCommand _command = new TestCommand();\n        private ExecutionResult _result;\n\n        public void when_processing_a_valid_command()\n        {\n            _result = SUT.Execute(_command);\n        }\n\n        public void Then_the_processor_should_find_the_validator_for_the_command()\n        {\n            SubFor<IValidateCommandFactory>().Received().ValidatorForCommand(_command);\n        }\n\n        public void AndThen_validate_the_command()\n        {\n            SubFor<IValidateCommand<TestCommand>>().Received().Validate(_command);\n        }\n\n        public void AndThen_the_processor_should_find_the_handler_for_the_command()\n        {\n            SubFor<IHandleCommandFactory>().Received().HandlerForCommand(_command);\n        }\n\n        public void AndThen_the_command_is_processed_successfully()\n        {\n            _result.IsSuccessful.Should().BeTrue();\n        }\n\n        public void AndThen_the_result_is_logged()\n        {\n            SubFor<ILog>().Received().Info(Arg.Any<string>());\n        }\n    }\n\nAnd this comes out very nicely on the report:\n\n![BDDfy unit test report](/img/BDDfy/Customizing/bddfy-unit-test-report-2.png)\n\n\nYou can find the code on [github](https://github.com/TestStack/TestStack.Seleno/tree/master/src/TestStack.Seleno.Tests/Specify).","excerpt":"","slug":"example-using-bddfy-for-unit-testing","type":"basic","title":"Example - using BDDfy for unit testing"}

Example - using BDDfy for unit testing


# Introduction # I’ve been using BDDfy with NUnit for writing acceptance tests for quite awhile now. But for unit testing I have continued to use mspec with [machine fakes](https://github.com/machine/machine.fakes) and Moq for auto-mocking. The more I used BDDfy, the more I liked it, and the less I liked the context switch into another framework. I found myself wanting to write unit tests in the Given When Then format and didn't like having to maintain two sets of helper code for NUnit and mspec. I loved the reporting in BDDfy and started to think it would be pretty cool to have similar reporting for my unit tests. Basically, I wanted a consistent experience across all my automated testing. MSpec uses the [testcase class per fixture](http://xunitpatterns.com/Testcase%20Class%20per%20Fixture.html) style of testing, which is how I use BDDfy for acceptance testing, so it makes sense to continue with that style for the BDDfy unit tests. When I am doing acceptance tests I have a base ScenarioFor< T> class, where the T represents the System Under Test (SUT). Because these are full system tests, I resolve this SUT using the same inversion of control container that my application uses, which works nicely. The IoC container acts as a [SUT factory](http://blog.ploeh.dk/2009/02/13/SUTFactory/). With unit tests, I also want to have a SUT factory, but instead I want it to be an auto-mocking container. When we started writing unit tests for the [Seleno](http://teststack.github.io/pages/Seleno.html) project, I thought it would be a good opportunity to try some of these ideas out. # Specification Base Fixture # The Specification base fixture class wires up BDDFy. It provides methods that BDDfy knows about in its default configuration for setting up and tearing down the fixture (each test class will implement its own specific Given When Then methods that BDDfy will also find). The Run method has the NUnit Test attribute and so will be called by the testing framework and it just calls BDDFy to run the test. I prefer to use NUnit myself, but you could just as easily substitute XUnit or MsTest attributes if you prefer. One thing I really like about this approach is that I only have to put the TestFixture and Test attributes in this one class and then all of the test classes I create inherit them and don't need any attributes. All the test runners still picks the classes up as tests and ReSharper even puts its little run test icons in each test class as normal. This class is also the one place that BDDfy gets called. [TestFixture] public abstract class Specification : ISpecification { [Test] public virtual void Run() { string title = BuildTitle(); this.BDDfy(title, Category); } protected virtual string BuildTitle() { return Title ?? GetType().Name.Humanize(LetterCasing.Title); } // BDDfy methods public virtual void EstablishContext() { } public virtual void Setup() { } public virtual void TearDown() { } public virtual Type Story { get { return GetType(); } } public virtual string Title { get; set; } public string Category { get; set; } } #Auto-Mocking # The SpecificationFor<T> class inherits from the Specification class and adds an auto-mocking container for creating the SUT. An auto-mocking container decouples a unit test from the mechanics of creating the SUT and automatically supplies dynamic mocks in place of all of the SUT's dependencies. They are commonly implemented by combining an IoC container with a mocking framework, which is what I will be doing here. I prefer [NSubstitute](http://nsubstitute.github.io/) for mocking these days, so my friend [Rob Moore's](http://robdmoore.id.au/) [AutoSubstitute](http://nuget.org/packages/AutofacContrib.NSubstitute) auto-mocking container is ideal. The AutoSubstitute field provides access to the container for full access to its functionality. SubstituteFor is provided as a convenience method to gain access to NSubstitute substitutes. public abstract class SpecificationFor<T> : Specification { public T SUT { get; set; } protected AutoSubstitute AutoSubstitute; protected SpecificationFor() { AutoSubstitute = CreateContainer(); InitialiseSystemUnderTest(); } public virtual void InitialiseSystemUnderTest() { SUT = AutoSubstitute.Resolve<T>(); } public TSubstitute SubstituteFor<TSubstitute>() where TSubstitute : class { return AutoSubstitute.ResolveAndSubstituteFor<TSubstitute>(); } public override Type Story { get { return typeof(T); } } private static AutoSubstitute CreateContainer() { Action<ContainerBuilder> autofacCustomisation = c => c .RegisterType<T>() .FindConstructorsWith(t => t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) .PropertiesAutowired(); return new AutoSubstitute(autofacCustomisation); } } Notice that the InitialiseSystemUnderTest is virtual, so if you need to create the SUT yourself rather than having AutoSubstitute do it then you can just override it in your test class. It runs before any of the test methods so they can all safely interact with the SUT confident that it has been created. # What's in a Story? # When moving from scenarios to unit tests I had to think what I wanted to do with the Story that is part of BDD. BDDfy actually doesn't require stories, so one option was to do nothing. However, when you don't have a story the report shows the namespace instead, and I don't find that particularly helpful or attractive. A Story's purpose in BDD is to group related Scenarios and to provide metadata about that grouping, so I think the same logic can be applied to unit tests. By creating a base specification class that related tests inherit from, they will all be grouped together on the report, and the name of that class will be used in the heading, much like a Story grouping would look like on a BDD report. This class is often a convenient place to create variables that are common to all of the test cases. So, for example, if you create a base class called PageNavigatorSpecification, the report grouping will read "Specifications For: Page Navigator." That is achieved by adding the following custom story metadata scanner. public class SpecStoryMetaDataScanner : IStoryMetaDataScanner { public virtual StoryMetaData Scan(object testObject, Type explicityStoryType = null) { var specification = testObject as ISpecification; if (specification == null) return null; string specificationTitle = CreateSpecificationTitle(specification); var story = new StoryAttribute() {Title = specificationTitle}; return new StoryMetaData(specification.Story, story); } private string CreateSpecificationTitle(ISpecification specification) { string suffix = "Specification"; string title = specification.Story.Name; if (title.EndsWith(suffix)) title = title.Remove(title.Length - suffix.Length, suffix.Length); return title; } } And here is what the specifications look like in the BDDfy report: ![BDDfy unit test report](/img/BDDfy/Customizing/bddfy-unit-test-report.png) # Unit Testing # Here is an example of some tests that we have written for Seleno using this approach. Firstly, an example of a Specification class, the grouping class analagous to the BDDFy story that all the PageReader specification classes will inherit from. There is normally no need to override the Story as the SpecificationFor class will automatically convert the generic T into an English name. In this case though it will convert PageReader< TestViewModel> into PageReader`, so it is a convenient hack to override the property with PageReaderSpecification which will more attractively produce "Page Reader" on the report. abstract class PageReaderSpecification : SpecificationFor<PageReader<TestViewModel>> { public override Type Story { get { return typeof (PageReaderSpecification); } } } Each specification for the PageReader component inherits from the PageReaderSpecification. There are often no Given steps as the auto-mocking container has taken care of instantiating the SUT for you. It has also created a Substitute for the IExecutor dependency of the PageReader class and in the verification phase of the test you can just call SubstituteFor< IExecutor> to call NSubstitute verification methods on the substitute. class When_checking_an_element_exists_and_is_visible_with_property : PageReaderSpecification { public When_checking_an_element_exists_and_is_visible_with_property() { SUT.ExistsAndIsVisible(x => x.Item); } public void Then_it_should_execute_the_relevant_script_with_jquery_id_selector() { SubstituteFor<IExecutor>() .Received() .ScriptAndReturn<bool>("$(\"#Item\").is(':visible')"); } } This test shows that you can also setup Substitute behaviour in the setup phase of the test. class When_getting_a_web_element_strongly_typed_text : PageReaderSpecification { private DateTime _result; private readonly DateTime _the03rdOfJanuary2012At21h21 = new DateTime(2012, 01, 03, 21, 21, 00); [Given("Given a web element contains the text 03/01/2012 21:21")] public void Given_a_web_element_contains_the_text_03_01_2012_21_21() { SubstituteFor<IElementFinder>() .Element(Arg.Any<By>()) .Returns(SubstituteFor<IWebElement>()); SubstituteFor<IWebElement>().Text.Returns("03/01/2012 21:21"); } public void When_getting_the_web_element_matching_a_view_model_property() { _result = SUT.TextAsType(viewModel => viewModel.Modified); } public void Then_it_should_return_the_corresponding_typed_value_of_the_web_element_text() { _result.Should().Be(_the03rdOfJanuary2012At21h21); } } # Another approach # It's worth looking at another example of sharing a base context class. As I said above, it is not just for making the report work, it can be quite helpful to share context there. [Matt Honeycutt](http://trycatchfail.com/blog/) has an interesting style for reusing context classes in his very cool [SpecsFor BDD framework](http://specsfor.com/) that this approach also supports: public class given { public abstract class the_command_is_valid : SpecificationFor<CommandProcessor> { protected void Given_the_command_is_valid() { SubFor<IValidateCommand<TestCommand>>().Validate(Arg.Any<TestCommand>()).Returns(new ExecutionResult(null)); SubFor<IValidateCommandFactory>().ValidatorForCommand(Arg.Any<TestCommand>()).Returns(SubFor<IValidateCommand<TestCommand>>()); } } } public class processing_a__valid_command : given.the_command_is_valid { private TestCommand _command = new TestCommand(); private ExecutionResult _result; public void when_processing_a_valid_command() { _result = SUT.Execute(_command); } public void Then_the_processor_should_find_the_validator_for_the_command() { SubFor<IValidateCommandFactory>().Received().ValidatorForCommand(_command); } public void AndThen_validate_the_command() { SubFor<IValidateCommand<TestCommand>>().Received().Validate(_command); } public void AndThen_the_processor_should_find_the_handler_for_the_command() { SubFor<IHandleCommandFactory>().Received().HandlerForCommand(_command); } public void AndThen_the_command_is_processed_successfully() { _result.IsSuccessful.Should().BeTrue(); } public void AndThen_the_result_is_logged() { SubFor<ILog>().Received().Info(Arg.Any<string>()); } } And this comes out very nicely on the report: ![BDDfy unit test report](/img/BDDfy/Customizing/bddfy-unit-test-report-2.png) You can find the code on [github](https://github.com/TestStack/TestStack.Seleno/tree/master/src/TestStack.Seleno.Tests/Specify).