Schubert's Blog

A biker and technology enthusiast's
view of the world and TDD & Mocks Part 2

In this blog entry I present two of the four test cases I've used to test the base business logic class from Beta 1. I've used the NUnit testing framework, as it was the simplest to implement with Visual Web Developer 2008. And Rhino Mock to pass in fake anonymous and logged in users to the base class. The code for the base class being tested here, is covered in the previous blog, so head over there if you haven't read it yet. On with the testing, first create fake accounts:

public class BlBaseText
//Faking a normal user account
Mock<IIdentity> FakeLoggedInSpereIIdentity;
//Faking an admin account
  Mock<IIdentity> FakeLoggedInMapzeAdminIIdentity;
//Faking an anonmymous account
  Mock<IIdentity> FakeAnonIIdentity;

In the NUnit setup function, I initialze the fake accounts.

[TestFixtureSetUp] public void Setup() { //Setting up the user account SPere
FakeLoggedInSpereIIdentity = new Mock<IIdentity>(); FakeLoggedInSpereIIdentity.Setup(i => i.IsAuthenticated).Returns(true).Verifiable(); FakeLoggedInSpereIIdentity.Setup(i => i.Name).Returns("SPere").Verifiable(); //Setting up the admin account MapzeAdmin
FakeLoggedInMapzeAdminIIdentity = new Mock<IIdentity>(); FakeLoggedInMapzeAdminIIdentity.Setup(i => i.IsAuthenticated).Returns(true).Verifiable(); FakeLoggedInMapzeAdminIIdentity.Setup(i => i.Name).Returns("MapzeAdmin").Verifiable(); //Setting up the anonymous account
FakeAnonIIdentity = new Mock<IIdentity>(); FakeAnonIIdentity.Setup(i => i.IsAuthenticated).Returns(false).Verifiable(); FakeAnonIIdentity.Setup(i => i.Name).Returns("").Verifiable(); }

Now that we have fake accounts, we can go ahead and setup the acutal test. The four test cases are:

1. The user is authenticated and their username exist in the database. This is the normal scenario and should be the case 90% of the time.

public void ConstructorTest_UserIsAuthenticateAndValidUserName() { //Inject the fake user SPere
BlBase.FakeIIdentity = FakeLoggedInSpereIIdentity.Object; //The MVC state dictionary to store error and messages
ModelStateDictionary dictionary = new ModelStateDictionary(); //Initialise the base business logic class
BlBase blbase = new BlBase(dictionary, new L2SUserService()); //Make sure the current user variable is an instance of the IUser interface
Assert.IsInstanceOf<IUser>(blbase.currentUser); //Make sure the current user id is 1
Assert.AreEqual(1, blbase.currentUser.Id); //Make sure the user name is "SPere"
Assert.AreEqual("SPere", blbase.currentUser.UserName); //And finally make sure there were no errors or messages
Assert.AreEqual(0, dictionary.Count); }

2. The user is authenticated but the username does not exist in the database. Most likely cause of this is the user delete their account, but their authentication cookie is still valid as they were not logged out.

[Test] public void ConstructorTest_IsAuthenticateAndNotValidUserName() { //Create a fake account "NotValidUsername"
var FakeIIdentity = new Mock<IIdentity>();
FakeIIdentity.Setup(i => i.IsAuthenticated).Returns(true).Verifiable();
FakeIIdentity.Setup(i => i.Name).Returns("NotValidUserName").Verifiable();

//Inject the fake user "NotValidUsername"
BlBase.FakeIIdentity = FakeIIdentity.Object;
//The MVC state dictionary to store error and messages
ModelStateDictionary dictionary = new ModelStateDictionary();

//Initialise the base business logic class
BlBase blbase = new BlBase(dictionary, new L2SUserService());

//Make sure the current user variable is null
//Make sure there is an error in the model state dictionary
Assert.AreEqual(1, dictionary.Count);
//Make sure the Severe Error key is present in the dictionary
Assert.AreEqual("SevereError", dictionary.Keys.FirstOrDefault());
//Make sure the message value is 1, so we can show generic severe error
//message and log the user out
Assert.AreEqual("1", dictionary["SevereError"].Errors.First().ErrorMessage);

To prevent this blog from turning into the longest blog post on the internet, I've not posted test 3 and 4, but they are similar. 3. was to check the scenario when the user is authenticated but is suspended and 4. is the scenario when the user is not authenticated. Hope this helps someone. As always, I'm open to suggestion and sharing best practices when it comes to testing, coding, designing and motorbiking Laughing. and TDD & Mocks Part 1

This is my first foray into the world of writing code to test other code and have to admit, I enjoyed it. Ever since, I have tried to use TDD in every project, even if it only means testing a subset of the desired functionality. The finalized Beta 1 website had 490 test cases, 243 to test the Business logic layer, 121 to test the MVC Controllers and 126 to test the helper classes. The only disadvantage of TDD I've found so far is it almost doubles the development time. But the confidence of knowing that the website can cope with all the test cases, thought up during and after development, outweighs the cons.

In this blog entry, I'll discuss the BlBase class,'s base business logic class and cover how I've gone about using NUnit and Rhino Mocks to test it in the next blog entry. Having decided to use LinqToSql as the Data Access Layer, all the business logic classes will need an instance of the data context. They will also need an instance of the current user to carry out selects, inserts and updates against. Making the BlBase class look like:

public class BlBase
//Current user variable, all business logic code have access to the current user
public IUser currentUser;
//The datacontext initialised once per request
public RedStartDataContext currentDataContext;

//Only for testing, inject a fake user identity
public static IIdentity FakeIUser;
//Modelstate dictionary, all business logic code can store
//informative and error messages here
public ModelStateDictionary currentModelState;

The BlBase class has one constructor and no methods. And this constructor has code to intialise the current user and data context variable. The constructor looks like:

//Constructor to initialise the user and data context
public BlBase(ModelStateDictionary ModelState, IUserService UserService)
//save the model state and initialise the data context
currentModelState = ModelState;
currentDataContext = new RedStartDataContext();

//Get the current user

//A little trick here: when this code is live
//HttpContext.Current will never be null. When
//NUnit call this code the FakeIUser will be used
//instead. Mapze Beta 2 has a cleaner implementation.
IIdentity identity;
if (HttpContext.Current != null)
identity = HttpContext.Current.User.Identity;
identity = FakeIUser;

//is the request authenticated
if (identity.IsAuthenticated)
//get the user from db
currentUser = UserService.Get(identity.Name);

//Make sure there is a user with the identity name
//also make sure the user account is not suspended.
//The 1 in the ModelError is picked up by a custom
//MVC error trapping filter and logs out the user.
if(currentUser == null || currentUser.Suspended)
currentModelState.AddModelError("SevereError", 1);

I believe most social networking and user interactive website will have a similar base class for all their business logic classes to inherit from. Making sure this class works correctly is of utmost importance, especially to business that rely on their user base for sales and feedback. The next blog entry shows how I've used NUnit and Rhino Mocks to test this class.