This post describes how to use MSpec tests to implement test-driven development (TDD). Details on TDD can be found on this wikipedia page. Machine.specifications is simple to install through the Nuget package manager, more information can be found on the MSpec site. Here Machine Fakes is also used to create the unit tests, more information on this can be found here. This blog post will be analogous to Behaviour-driven development (BDD) with SpecFlow - Part 1, hence a direct comparison is able to be made between the two testing methodologies. The example below will show the Mspec test for the command query that gets all users from the database.
By convention Mspec classes are titled in snake case. The Subject attribute is added, although this is not essential it is good practice to do so. The test class inherits from WithSubject (from Machine.Fakes) with the type being the class where the testable code resides.
Note: the following code snippets are all contained within the class declared above.
The Mspec test is comprised of three delegates. Firstly, the Establish, followed by the Because, and ending It delegate(s). Prior to these, the required properties are declared as below.
"Establish" delegate
To start, the users to store in the data context are created. Here a generator class is used but not shown for brevity. Next the data context is initialised and the users Bill and Steph are added and saved.
"Because" delegate
The Because delegate simply tell the Execute method on the subject (i.e. the GetAllUsersQuery in this case) to run and assign the result to the result property.
"It" delegate
Finally, the result is checked to ensure that it contains bill and steph as we would expect. Although not shown above, it would be good practice to also verify the count of the result is equal to 2.
It is important to note that this is just one of many ways of creating Mspec tests for test driven development. For example, it is possible to use an in memory or a local test database. Additionally, in the above a generator class is utilised, but there are alternative methods to reduce the duplication of code for tests that require common data.
Comments
Post a Comment