Any data driven module, class or method needs to be tested. At this moment anything that is data-drive (which would actually cover almost anything) needs to be verified according to specs to ensure correctness. In this post we will talk about creating tests for Data-Driven WCF Services. For simplicity and ease of use, we are going to use the Enterprise Library Data Application Block to talk to the database.
Before we get deeper into the topic at hand, let’s talk about the unit test environment that I use and recommend for testing data-driven applications.
Testing Context
The basic objective of a unit test is to verify correctness of a an application. Testing every unit in a layer ensures the correctness of the behavior of such units, specially when being used by other units in the application. This way all units can be reused with confidence.
Now in order to maintain confidence in the Unit being tested, we need to ensure that the tests are reliable and that providence confidence in the correctness of the unit under test. When a test sometimes pass and sometimes fails is called an Erratic Test, and in order to maintain confidence we need to avoid such behavior.
Unit Tests, as explained before, focus on testing the a single unit in a system, unlike integration testing. So it is a best practice to have one database instance per developer or tester. Having two developers running the test fixtures at the same time on the same database create an erratic test behavior, which is not acceptable.
Data-Driven Tests
The pattern we are going to follow in this post is a simple form of the Data-Driven Test Pattern, which is described as:
“We store all the information needed for each test in a data file and write an interpreter that reads the file and executes the tests”.
This pattern is mostly used to avoid code duplication, especially when several test cases just change on different data conditions. This way one test can be executed with several test scripts, instead of writing one test for every data condition.
We’ll use a simple form of the pattern, using Sql syntax for scripts instead of Xml data files. I find it easier to just create an Sql script, execute it and continue with the testing.
Each test must have a context setup. There are several patterns that specify that one test method sets up the data context for the others; for example, one test method tests the insertion of data, while the next test method tests the retrieval of the inserted data. I don’t recommend this setting, this leads to Erratic Tests. Every unit test must be independent of each other. This means that every test method must setup its own environment and it must also clean it up to the initial state.
Unit Testing WCF Services
Unit Testing WCF Services is extremely easy. There are two ways to do this:
1) Include the WCF Library as a reference.
2) Load up the WCF Service host and call the service from the test fixture.
Since we are mostly doing unit testing and not integration testing, loading the WCF Library as a reference works fine. For integration purposes I would write one test fixture for each endpoint in the configuration, but this is out of the scope of this post.
Test Code
So we have two service methods: 1) ProjectService.Insert and 2) ProjectService.GetIdByName. This is the interface of such methods:
namespace WCFTesting
{
using System.ServiceModel;
/// <summary>
/// Project Service Contract.
/// </summary>
[ServiceContract]
public interface IProjectService
{
/// <summary>
/// Inserts a new Project.
/// </summary>
/// <param name="id">Project Identifier.</param>
/// <param name="name">Project Name</param>
/// <param name="description">Project Description</param>
/// <returns>True if successful, false otherwise.</returns>
[OperationContract]
bool Insert(int id, string name, string description);
/// <summary>
/// Returns the id of the project that goes by the selected name.
/// </summary>
/// <param name="name">Project Name</param>
/// <returns><c>int</c></returns>
[OperationContract]
int GetIdByName(string name);
}
}
The service method implementation is shown below:
/// <summary>
/// Inserts a new Project in database.
/// </summary>
/// <param name="id">Project Identifier.</param>
/// <param name="name">Project Name</param>
/// <param name="description">Project Description</param>
/// <returns>True if successful, false otherwise.</returns>
public bool Insert(int id, string name, string description)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand command = db.GetStoredProcCommand("[dbo].[InsertProject]");
db.AddInParameter(command, "id", DbType.Int32, id);
db.AddInParameter(command, "name", DbType.String, name);
db.AddInParameter(command, "description", DbType.String, description);
db.AddOutParameter(command, "success", DbType.Boolean, 1);
db.ExecuteNonQuery(command);
bool success = (bool) db.GetParameterValue(command, "success");
return success;
}
/// <summary>
/// Returns the id of the project that goes by the selected name.
/// </summary>
/// <param name="name">Project Name</param>
/// <returns><c>int</c></returns>
public int GetIdByName(string name)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand command = db.GetStoredProcCommand("[dbo].[GetProjectIdByProjectName]");
db.AddInParameter(command, "Name", DbType.String, name);
int id = -1;
using(IDataReader reader = db.ExecuteReader(command)) {
if(reader.Read()) {
id = reader.GetInt32(0);
}
}
return id;
}
Note: All code can be found in the attachment at the end of the post.
As you can see the methods are really simple. We are using a simple call to a stored procedure, getting the results and sending them back to the client.
Now let’s look at the actual unit test fixture:
/// <summary>
/// Test the Service method Insert
/// </summary>
[TestMethod]
public void Insert()
{
using(TransactionScope tranScope = new TransactionScope()) {
int id = 1;
string name = "Project 1";
string description = "Description of Project 1";
Assert.IsTrue(Service.Insert(id, name, description));
Assert.IsTrue(ProjectExists(name, description));
id = 2;
name = "Project 2";
description = "Description of Project 2";
Assert.IsTrue(Service.Insert(id, name, description));
Assert.IsTrue(ProjectExists(name, description));
}
}
/// <summary>
/// Test the Service method GetIdByName
/// </summary>
[TestMethod]
public void GetIdByName()
{
using(TransactionScope tranScope = new TransactionScope()) {
// Insert the Test Data.
SqlHelper.ExecuteSqlScript(Db, @"......UnitTestsScriptsInsertTestProjects.sql");
// Test Service Method.
int id = -1;
string name = "Kook";
id = Service.GetIdByName(name);
Assert.AreEqual<int>(1, id);
name = "Samii";
id = Service.GetIdByName(name);
Assert.AreEqual<int>(2, id);
name = "CPW";
id = Service.GetIdByName(name);
Assert.AreEqual<int>(3, id);
}
}
First we have the insert method, which doesn’t require any existing data, so no script is executed before the service method. We do however wrap everything into a TransactionScope, which ensures that whatever the test does, after the TransactionScope block is out of the scope it will rollback all the changes. I will leave the discussion on Transactions for a later post.
Now, the second method is more interesting. The GetIdByName test method actually needs a setup. We could have created a dependency on the Insert method so that the first test method prepares the data that the GetIdByName method will require to test. But we want to avoid Erratic Test behavior, so we created them completely independent.
The GetIdByName is also wrapped in the TransactionScope so that we can ensure that after the test is done, the data is rolled back to its initial state.
The script (InsertTestProjects.sql) contains three sample projects which the service method will retrieve and we will verify the returned data.
As you can see testing Data-Driven Services is very simple. If you pay close attention to the project you will notice that this way of doing this doesn’t only apply to WCF Services, any .Net assembly can be tested this way.
Hope this helps you on your quest for simplicity and correctness!
Download Test Solution
Test Solution Requirements
- Visual Studio 2008
- Enterprise Library 4.x
- .Net 3.5
- SQL Server 2005
The Database folder contains the table and stored procedures needed by the code. Just modify the ExecuteScripts.bat to set the database authentication info. Also modify the App.config in the UnitTests project in order to run accordingly.
(Disclaimer: This project has been stripped down so that it is easy enough to understand. This second method, iin order to follow Data-Driven Test, should get the expected data from an Xml file, insert it into the database, and compare accordingly. In this sample we have the data hard coded for simplicity. Building an interpreter is our of the scope of this post.)
* References:
- Meszaros, Gerard. “xUnit Test Patterns: Refactoring Test Code”
2007, Pearson Education.
Amazon