LP on .NET

January 2, 2012

Why I Blog — 2012

Filed under: .NET,blogging,C# — Larry Parker @ 6:57 pm

I’d like to wish the readers of my blog a very happy New Year and much success in 2012.

I thought I’d take a few minutes to reflect on why I blog.  After all, I don’t get paid for it.  I haven’t written any books, I don’t speak at conferences, and blogging is not part of my job.  Actually, I’m pretty much a no-name in the industry.  Just another C# coder swimming in the vast sea of technological talent. 

So why do it?

Well… it’s because I like it.

Actually, I like programming more, but when I come across something really challenging at work and solve it, or when I learn about a new technique that I find really useful, I find that writing about it enhances my understanding of the subject.

So maybe blogging is a selfish thing.  :-)

But actually, I truly appreciate when someone teaches me something new that helps me in my job (whether it be a colleague, an author of a book, or another blogger) and I find it rewarding when I publish a blog post and someone learns something from it, solves a problem, etc.  And it’s even more rewarding when someone leaves me a note to thank me.

So maybe that’s another selfish aspect of blogging.  I like being thanked for helping someone out. ;-)

Anyway, enough reflections on blogging and my place in the blogosphere.  If you’ve read this far, I hope you like my blog and you’ve found my posts to be useful.  I can’t promise to post every week (it’s tough with a day job), but I hope to continue enough to keep this blog useful and enjoyable for both you and me.

Have a great 2012!!!

Using Internal Interfaces with Moq

Filed under: .NET,C# — Larry Parker @ 4:10 pm

Lately I’ve been using the C# internal modifier more and more for code that I intend to keep, well, internal to my assembly.  This has especially been the case for framework code that I have been writing that will not be accessed by framework consumers.  The internal modifier lets others know that it’s internal implementation, subject to change, hands off, etc.

But one area of my code that I’ve had to begrudgingly keep public has been internally used interfaces because they could not be tested with Moq.  They compile just fine.  It’s just that Moq gives me a runtime error:  Castle.DynamicProxy.Generators.GeneratorException: Type <whatever> is not public. Can not create proxy for types that are not accessible.

But before I get into the details, why would you want to use an internal interface anyway?  Aren’t interfaces by definition supposed to be public?  Well I guess if that were the case then Microsoft wouldn’t allow you to apply the internal modifier to them.  :-)

But seriously, consider the case where you’re doing dependency injection where you hand a class a bunch of interface references in its constructor, but these interfaces are just internal to the assembly.  In other words, you’re writing testable code with injected interfaces to facilitate unit testing.  Just because they’re interfaces doesn’t mean you intend to publish them externally.  Hence the use of internal interfaces.

As an example, say you have a customer manager with an AddCustomer method that calls a persistence layer to add the customer to the database.  The code might look like this:

internal class CustomerManager {
    public CustomerManager(ICustomerPersistence customerPersistence)
    {
        _customerPersistence = customerPersistence;
    }

    private ICustomerPersistence _customerPersistence;

    public void AddCustomer(String customerName)
    {
        _customerPersistence.Add(customerName);
    }
}

internal interface ICustomerPersistence {
    void Add(String customerName);
}

Both the CustomerManager class and the ICustomerPersistence interface are marked as internal because they won’t be used outside the current assembly.  When we create our unit test for the AddCustomer method via Visual Studio’s Create Unit Tests… context menu option, it makes our unit test assembly a “friend” of the assembly containing the CustomerManager class:

[assembly: InternalsVisibleTo("CustomerTest, PublicKey=...")]

 

Now let’s write a unit test for the AddCustomer method that mocks the ICustomerPersistence interface:

[TestMethod()]
public void AddCustomerTest()
{
    var customerPersistenceMock = new Mock<ICustomerPersistence>();

    CustomerManager target = new CustomerManager(customerPersistenceMock.Object);

    String name = "Sue Jones";
    target.AddCustomer(name);
    customerPersistenceMock.Verify(o => o.Add(name));
}

This compiles ok, but when we run the test we get the error mentioned above; i.e. that the ICustomerPersistence interface is not public and that Moq cannot create a proxy for it.

My workaround for this has been to grit my teeth and make the interface public:

public interface ICustomerPersistence {
    void Add(String customerName);
}

But once you do that, developers start asking you what the ICustomerPersistence interface is for (it’s public after all), how they should be using it, where is the documentation, etc.  All these problems because you just wanted to write a unit test that mocks the interface.  :-)

Fortunately, there’s a solution.  You just need to use the InternalsVisibleTo assembly attribute to make Moq a friend of the assembly containing the internal ICustomerPersistence interface.

Unfortunately, the Moq assembly name wasn’t so obvious and I couldn’t find it in the Moq documentation.  But after some searching, I found a couple of blog posts on it.  Since Moq is a signed assembly, you need to provide the public key to the InternalsVisibleTo attribute.  The tricky part is copying the public key correctly, and some of the blogs posts either had it wrong or had it formatted such that copying and pasting didn’t work properly.

But this blog post got it right: 

http://blog.ashmind.com/category/agile/mocking/

I’ll post the code here too, and I hope you’ll be able to copy and paste it into your own AssemblyInfo.cs file (you’ll need to scroll to the right to get the entire public key):

// Make internal interfaces visible to Moq [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] 

 

Now I was able to change all of those public interfaces back to internal, which made my code just a little bit cleaner.

Hope this helps.

Introduction to Unit Testing with Moq

Filed under: .NET,C# — Larry Parker @ 1:31 pm

If you’ve kept up with my blog over the last year or so, you may have noticed that I discussed certain aspects of unit testing (like writing testable code and unit testing using stubs) but haven’t mentioned much about mocking frameworks.

Mocking frameworks, simply put, allow you to easily simulate behavior of objects and interfaces and are therefore very useful for unit testing.  But before I show an example of mocking, let’s see how we can do something similar by writing our own stubs.

The following example is from the Writing Testable Code post:

public class UserManager {
    public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
    {
        _userPersistence = userPersistence;
        _emailManager = emailManager;
    }

    private IUserPersistence _userPersistence;
    private IEmailManager _emailManager;

    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try {
            Boolean result = false;

            if (_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

            return result;
        }
        catch (Exception ex)
        {
            // Log the exception... return false; }
    }
}

public interface IUserPersistence {
    Boolean AddUser(String lastName, String firstName, String emailAddress);
    // Other interface members... }

public interface IEmailManager {
    Boolean SendUserRegistrationEmail(String lastName, String firstName, String emailAddress);
    // Other interface members... }

 

Note that the UserManager constructor takes parameters for the interface references used by RegisterUser.

Now we can write stubs to simulate these interfaces:

public class UserPersistenceStub : IUserPersistence {
    public Boolean AddUser(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

public class EmailManagerStub : IEmailManager {
    public Boolean SendUserRegistrationEmail(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

 

These stubs don’t do very much, but they allow us to use them in a unit test like this:

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceStub = new UserPersistenceStub();
    var emailManagerStub = new EmailManagerStub();

    UserManager target = new UserManager(userPersistenceStub, emailManagerStub);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

 

This test calls the RegisterUser method and simply asserts that it returns true.  If you look at the RegisterUser code, the only way that this will happen is if the SendUserRegistrationEmail method that it calls (via the IEmailManager reference) also returns true.

Since we wrote our IEmailManager stub to do this (i.e. the EmailManagerStub class) and also wrote our test to inject it into the UserManager constructor, our test passes.

So we didn’t even need a mocking framework to write a unit test in this example.  We simply wrote some stubs to simulate the interfaces needed by the method being tested.

However, the problem with stubs is that they are tedious to write.  That’s where a mocking framework comes in.  There are many excellent mocking frameworks out there, but I chose Moq after a colleague gave me a quick demo.

Let’s rewrite our unit test to use Moq instead of stubs.  Assuming we’ve installed Moq and added a reference to our unit test project, we first need to do a “using” statement:

using Moq;

 

Now we can rewrite our test like this:

[TestMethod()]
public void RegisterUserTest()
{
 var userPersistenceMock = new Mock<IUserPersistence>(); var emailManagerMock = new Mock<IEmailManager>(); 
    UserManager target = new UserManager(userPersistenceMock.Object, emailManagerMock.Object);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

 

Instead of creating our own stub classes that implement the injected IUserPersistence and IEmailManager interfaces, we simply use the Mock<T> class and specify the interface we wish to mock.  Then we pass the mocked interfaces into our UserManager constructor with the mocked object’s Object property.

And we’re done.  No stub classes to write.  Wow, that was easy!  :-)

So let’s run our test!

image

Oops.  What happened?

Our test is expecting the RegisterUser method to return true but it didn’t.  As we saw when writing our stubs, the SendUserRegistrationEmail method needs to return true, so that’s what we did for the stub.

But how do we tell Moq to return true for this method?

To do this, we need to set up our mock object like this:

var emailManagerMock = new Mock<IEmailManager>();
emailManagerMock.Setup(o => o.SendUserRegistrationEmail("Smith", "Bert", "bsmith@wherever.com")) .Returns(true);

 

This tells the Moq framework that when IEmailManager.SendUserRegistrationEmail is called with the above parameters that it will return true.  The lambda expression variable (“o” in this case) is typed to the interface being mocked (i.e. IEmailManager).

We also need to do something similar for IUserPersistence so our test can pass.  Here’s the full test:

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceMock = new Mock<IUserPersistence>();
    userPersistenceMock.Setup(o => o.AddUser("Smith", "Bert", "bsmith@wherever.com"))
        .Returns(true);

    var emailManagerMock = new Mock<IEmailManager>();
    emailManagerMock.Setup(o => o.SendUserRegistrationEmail("Smith", "Bert", "bsmith@wherever.com"))
        .Returns(true);

    UserManager target = new UserManager(userPersistenceMock.Object, emailManagerMock.Object);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

 

Now when we run our test it passes! :-)

image

Much easier with Moq than writing our own stubs.  You can consider stubs a thing of the past.

But our test can be simplified a bit.  We don’t really care about specific parameters passed to our interface methods, so we can use Moq’s “It” class to make our test setups a bit more general:

var userPersistenceMock = new Mock<IUserPersistence>();
userPersistenceMock.Setup(o => o.AddUser(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<String>()))
    .Returns(true);

var emailManagerMock = new Mock<IEmailManager>();
emailManagerMock.Setup(o => o.SendUserRegistrationEmail(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<String>()))
    .Returns(true);

 

This tells Moq that we’re setting up a return value of true for these two methods when any parameters are passed to it.  For our test, this is acceptable.

Well, that was a quick introduction to Moq.  Hopefully I’ve demonstrated that mocking frameworks (like Moq) can be very useful for writing unit tests since they make it easy to simulate the behavior of the objects and interfaces used by the code being tested.

Once I grasped the power of Moq, I never looked back.

Happy mocking!

December 27, 2011

Case-Invariant Dictionaries

Filed under: .NET,C# — Larry Parker @ 4:26 pm

A few months back I posted about case-invariant string comparisons using the Equals method and the StringComparison enum.  This approach made it a bit more efficient to compare strings without regards to their case since it wasn’t necessary to convert the strings to lower or upper case.

But what if you have a dictionary that is keyed by a string and you wish the lookup to be case insensitive?  The following unit test demonstrates the problem, using a dictionary of city names and temperatures:

private Dictionary<String, Int32> GetDictionary()
{
    Dictionary<String, Int32> dict = new Dictionary<String, Int32>()
    {
        {"New York", 42},
        {"Boston", 35},
        {"Atlanta", 58}
    };
    return dict;
}

[TestMethod]
public void CaseInsensitive_KeyNotFound_Test()
{
    Dictionary<String, Int32> dict = GetDictionary();

    Assert.IsFalse(dict.ContainsKey("new york"));
}

As the test shows, searching the dictionary for the lower-case city of “new york” fails.  If you ask the user to input a city name and they don’t enter it as mixed case, you’re out of luck.

A workaround is to store the cities in the dictionary as upper (or lower) case and always ensure you search by the same case.  But that gets a bit messy.

Fortunately there’s a better way.  One of the Dictionary<TKey, TValue> constructors takes an IEqualityComparer<TKey> that lets you specify how you would like to compare the key of the dictionary.

The following unit test demonstrates this:

[TestMethod]
public void CaseInsensitive_KeyFound_Test()
{
    Dictionary<String, Int32> dict = new Dictionary<String, Int32>(StringComparer.OrdinalIgnoreCase)
    {
        {"New York", 42},
        {"Boston", 35},
        {"Atlanta", 58}
    };

    Assert.IsTrue(dict.ContainsKey("new york"));
}

In this example, we pass in a StringComparer.OrdinalIgnoreCase parameter that tells the dictionary to perform a case-insensitive string comparison.  This lets us find our New York entry regardless of case.  Now we have a better chance of finding the city when the user searches for it.

This is a very handy technique that also works with HashSet<T>.

Hope this helps.

December 14, 2011

Ignoring Unit Tests

Filed under: .NET,C#,Visual Studio — Larry Parker @ 11:19 pm

Have you ever had a unit test that you didn’t want executed as part of your team’s test runs?  For example, if it requires external data but you haven’t yet set up the test database.  Or you’ve been using a unit test as a workbench for developing some code that you’re interacting with in the debugger and don’t really want it to be run by others.

Up until recently, I would either comment out the [TestMethod] attribute or comment out the entire test method’s code.

But there’s a better way, as a colleague of mine recently advised – the [Ignore] attribute.

Decorating your test method with this attribute will prevent it from being run.

The nice thing about this is your test code will still be compiled and refactored with the rest of your codebase.

When you do want the test to run while you’re working with it, just uncomment the [Ignore] attribute.  Then when you’re ready to check in your test, comment it back and you’re all set to go.

Hope this helps.

September 6, 2011

Using a Collection Initializer with a Dictionary

Filed under: .NET,C#,Software Development — Larry Parker @ 10:39 pm
Tags: , ,

Collection initializers (introduced in C# 3.0) provide an easy way to initialize a collection of items.  For example, instead of doing this…

List<Color> colors = new List<Color>();
colors.Add(new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" });
colors.Add(new Color { Value = 0xFF9400D3, Name = "Dark Violet" });
colors.Add(new Color { Value = 0xFF708090, Name = "Slate Gray" });

…we can do this:

List<Color> colors = new List<Color>
{
    new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" },
    new Color { Value = 0xFF9400D3, Name = "Dark Violet" },
    new Color { Value = 0xFF708090, Name = "Slate Gray" }
};

But what if we want to initialize a dictionary?  The traditional way would be like this:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>();
colors.Add(0xFFF0F8FF, "Alice Blue");
colors.Add(0xFF9400D3, "Dark Violet");
colors.Add(0xFF708090, "Slate Gray");

But how would we use a collection initializer?  When you iterate through a dictionary, each item is a KeyValuePair<TKey, TValue>.  But we can’t do this:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>
{
    new KeyValuePair<UInt32, String>(0xFFF0F8FF, "Alice Blue"),
    new KeyValuePair<UInt32, String>(0xFF9400D3, "Dark Violet"),
    new KeyValuePair<UInt32, String>(0xFF708090, "Slate Gray")
};

The solution is not entirely obvious, but it is succinct:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>
{
    { 0xFFF0F8FF, "Alice Blue" },
    { 0xFF9400D3, "Dark Violet" },
    { 0xFF708090, "Slate Gray" }
};

This is not mentioned in the MSDN link shown above, but MSDN does discuss it here.

Hope this helps!

August 29, 2011

Dependency Injection and Delegates

Filed under: .NET,C#,Software Development — Larry Parker @ 10:46 pm
Tags: , ,

A couple of weeks ago I blogged about writing testable code using dependency injection.  This was done by injecting interface references into a class’s constructor:

public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
{
    _userPersistence = userPersistence;
    _emailManager = emailManager;
}

Assuming we have concrete classes called UserPersistence and EmailManager that implement these interfaces, we could simply inject the dependencies like this:

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), new EmailManager());
}

But what happens if the dependencies cannot actually be injected during construction because it’s too early to create them?  A good example of this is when the concrete classes themselves are constructed with a parameter that is not yet available.

Let’s say that when we register a user we get a guid back from our persistence layer that identifies the user.  Now let’s also say that our IEmailManager interface is written to apply to a single user at a time, and there’s a concrete class called EmailManager with a constructor that looks like this:

public class EmailManager : IEmailManager
{
    public EmailManager(Guid userId)
    {
        _userId = userId;
    }
...
}

Since we don’t know the guid until we register the user (via the UserManager class), we can’t inject an IEmailManager into the UserManager class’s constructor.

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), new EmailManager(<oops!  What’s the guid?>));
}

The solution is to change UserManager’s constructor to take a delegate instead of an interface:

public class UserManager
{
    public UserManager(IUserPersistence userPersistence,
        Func<Guid, IEmailManager> emailManagerFactory)
    {
        _userPersistence = userPersistence;
        _emailManagerFactory = emailManagerFactory;
    }

    private IUserPersistence _userPersistence;
    private Func<Guid, IEmailManager> _emailManagerFactory;

Instead of the UserManager constructor directly taking an IEmailManager, it now takes a delegate that expects a guid and returns an IEmailManager.

Since the delegate is only supplied during UserManager’s construction and not executed, we don’t need to know the guid at this time:

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), o => new EmailManager(o));
}

Our delegate can be passed in several ways, but a lambda expression is a nice easy way to do it (“o” is a local variable of type Guid).

With this new approach, our RegisterUser method from our previous post now looks like this:

public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
{
    try
    {
        Boolean result = false;

        Guid userId = _userPersistence.AddUser(lastName, firstName, emailAddress);

        IEmailManager emailManager = _emailManagerFactory(userId);
        result = emailManager.SendLoginInfo();

        return result;
    }
    catch (Exception ex)
    {
        // Log the exception...

        return false;
    }
}

Note that when we execute our delegate (i.e. the _emailManagerFactory field) we pass in the user ID guid as a parameter (i.e. the value we just obtained from calling the AddUser method) and get back our IEmailManager interface reference.  Now we can call its methods and they will all act on the newly registered user.

Delegates are a great way to defer execution until needed, and this is a very useful technique to let you follow the dependency injection pattern even when you don’t have everything you need during object construction.

Hope this helps.

August 19, 2011

Serializing and Deserializing JSON Data

Filed under: .NET,C#,Software Development — Larry Parker @ 7:31 pm
Tags: , ,

My team is working on a web site that consumes JSON (JavaScript Object Notation) objects, and my job is to provide the back-end services for the data.

I hadn’t worked with JSON before but figured there was a simple way to serialize and deserialize JSON data.  A colleague pointed me to MSDN (always a good start) with this link, and a quick search pointed me to this site which had some nice JSON helpers.

After looking at the examples on both sites, I wrote some extension methods to make things easier.  Here’s what I came up with (after some suggestions on the method names by my team):

public static class JsonExtensionMethods
{
    /// <summary>
    /// Serializes an object to a JSON string.
    /// </summary>
    /// <typeparam name="T">The serializable class.</typeparam>
    /// <param name="entity">The object that will be serialized to JSON.</param>
    /// <returns>Returns a serialized representation of the object as a JSON string.</returns>
    public static String ToJson<T>(this T entity)
        where T : class
    {
        String result = null;

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, entity);
            result = Encoding.Default.GetString(ms.ToArray());
        }

        return result;
    }

    /// <summary>
    /// Deserializes a JSON string into an object.
    /// </summary>
    /// <typeparam name="T">The class to deserialize the JSON string into.</typeparam>
    /// <param name="jsonObject">The serialized object as a JSON string.</param>
    /// <returns>Returns an instance of the concrete class representing the JSON string.</returns>
    public static T FromJson<T>(this String jsonObject)
        where T : class
    {
        T entity = Activator.CreateInstance<T>();

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonObject)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            entity = (T)serializer.ReadObject(ms);
        }

        return entity;
    }
}

Here are some unit tests that show how they are used:

[TestMethod()]
public void SerializeTest()
{
    Customer customer = new Customer { FirstName = "Joe", LastName = "Smith" };

    String actual = customer.ToJson();

    Assert.AreEqual("{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}", actual);
}

[TestMethod()]
public void DeserializeTest()
{
    String jsonObject = "{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}";

    Customer actual = jsonObject.FromJson<Customer>();

    Assert.AreEqual("Joe", actual.FirstName);
    Assert.AreEqual("Smith", actual.LastName);
}

Both of the tests use a class called Customer that looks like this:

[DataContract]
public class Customer
{
    [DataMember]
    public String LastName { get; set; }

    [DataMember]
    public String FirstName { get; set; }
}

Notice that the ToJson extension method is applied to a class, while the FromJson extension method is applied to a string.  The extension methods are a nice touch because you don’t have to go through a static helper class in your code, but instead just use the applicable extension methods directly on your variable (depending if you’re serializing to JSON or deserializing from JSON).

Hope you like it!

August 14, 2011

Writing Testable Code

Filed under: .NET,C#,Software Development — Larry Parker @ 5:59 pm

About a year ago, my idea of unit testing included anything that could be tested no matter how heavy the setup.  This included having an available test database, available web services, and other external resources (like the file system) that were needed to test my code.

While this kind of test environment is useful, it’s more along the lines of an integrated test environment that QA would have set up.  Test likes these can really be categorized as integration tests and not unit tests.

If you want to really unit test your code, you don’t want any of the aforementioned dependencies to be part of your tests.  Unit tests should be fast and should just test a single piece of code – not your entire application’s runtime environment.

Let’s take a look at both of these approaches.  Consider the following code that registers a user with your application:

public class UserManager 
{
    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try 
        {
            String connString = "...";

            using (var connection = new SqlConnection(connString))
            using (var cmd = new SqlCommand())
            {
                cmd.CommandText = @"
INSERT INTO User (LastName, FirstName, EmailAddress)
VALUES (@LastName, @FirstName, @EmailAddress)
";

                cmd.Parameters.Add("LastName", SqlDbType.NVarChar).Value = lastName;
                cmd.Parameters.Add("FirstName", SqlDbType.NVarChar).Value = firstName;
                cmd.Parameters.Add("EmailAddress", SqlDbType.NVarChar).Value = emailAddress;

                connection.Open();
                cmd.Connection = connection;
                cmd.ExecuteNonQuery();
            }

            return true;
        }
        catch (Exception ex)
        {
            // Log the exception... return false;
        }
    }
}

Now let’s write a test for the RegisterUser method.

[TestMethod()]
public void RegisterUserTest()
{
    UserManager target = new UserManager();
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

This test attempts to register a user named Bert Smith and verifies that the registration succeeded (i.e. we assert that the RegisterUser method returned true).

The test is simple enough, but in order to run it we need a database and also a User table in it.  It’s possible to set up a test database like this and ensure that the connection string is supplied for the test.  But now we have a heavy dependency that probably needs to be in a certain state every time we run the test (e.g. we probably don’t already want the user Bert Smith in the database before we run the test).

Let’s step back a second and ask ourselves exactly what we want to test in our RegisterUser test.  Do we want to test that ADO.NET works?  Hopefully Microsoft has already tested that well enough.  Do we want to test that we can write SQL that inserts a row into our User table?  At some point, but not right now.

The job of the RegisterUser method is to register a user with our system.  This probably involves some data validation (like ensuring the email address was supplied and is in a valid format), adding the user to persistent storage (like in a User table in a SQL database), and possibly sending an email to the user to let him know the registration succeeded.

All of these things are possible tasks that the RegisterUser method might need to execute, but we don’t necessarily want to test the tasks themselves – we only want to test that the tasks were called in the expected way.

Consider the email step.  How would we test that anyway?  We could use .NET’s SmtpClient class and have RegisterUser send the registration email to ourselves via our company’s email server (if we had rights to do so) and verify that we did indeed receive the email in our inbox.

The problem with this is that you need to verify that the email arrived in your inbox by looking at your inbox.  But when you run this test along with hundreds of other tests, you are not going to do this.  And neither is an automated test system.

So how do we write our RegisterUser test so we can test what we need without having all of these external dependencies?

The answer is:  dependency injection.

Dependency injection is a pattern whereby dependencies are supplied (or injected) into a system.  There are plenty of discussions about this (Martin Fowler, Wikipedia, etc.), but in a nutshell you simply hand the dependencies (typically as interfaces) to your class or method which then works with them in an abstract way.  In other words, instead of working directly with ADO.NET, your method works with an interface responsible for adding the user to persistent storage.

Let’s revisit the RegisterUser method with a couple of dependencies injected into the UserManager class’s constructor.

public class UserManager 
{
    public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
    {
        _userPersistence = userPersistence;
        _emailManager = emailManager;
    }

    private IUserPersistence _userPersistence;
    private IEmailManager _emailManager;

    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try 
        {
            Boolean result = false;

            if (_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

            return result;
        }
        catch (Exception ex)
        {
            // Log the exception... return false;
        }
    }
}

Notice that our constructor takes two parameters that are interfaces that define our tasks.

public interface IUserPersistence 
{
    Boolean AddUser(String lastName, String firstName, String emailAddress);
    // Other interface members... 
}

public interface IEmailManager 
{
    Boolean SendUserRegistrationEmail(String lastName, String firstName, String emailAddress);
    // Other interface members... 
}

As for the RegisterUser method, what happened to the SQL that will add the user to the User table in our database?  The short answer is, “Who cares?”

Persisting the user to the database is now farmed out to an interface called IUserPersistence that has a method called AddUser.  The SQL will probably be in there, but as far as the RegisterUser method is concerned, it doesn’t care.  Our RegisterUser method just works with the interfaces:

        if (_userPersistence.AddUser(lastName, firstName, emailAddress))
            result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                emailAddress);

This is dependency injection at work.  Our code is now testable and our test can now inject dependencies into the UserManager class without having to have a database and email server set up to run the test!

Let’s rewrite our test and inject some home-grown dependencies.

public class UserPersistenceStub : IUserPersistence 
{
    public Boolean AddUser(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

public class EmailManagerStub : IEmailManager 
{
    public Boolean SendUserRegistrationEmail(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceStub = new UserPersistenceStub();
    var emailManagerStub = new EmailManagerStub();

    UserManager target = new UserManager(userPersistenceStub, emailManagerStub);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

We simply created two stub classes that implement our interfaces and then injected instances of those classes into our UserManager instance.

Now our test runs without the need for a database or an email server.  We were able to achieve this because we rewrote our UserManager class and RegisterUser method as testable code using dependency injection.

Our unit test can be improved (e.g. by using tools like Moq), but I will save that for another post.  For now, the main takeaway of this post is that code can be written to be testable using dependency injection.

It took me a while to realize the importance of writing testable code.  The fact that testable code can be unit tested without needing external resources like databases opens up the door to writing a slew of tests to thoroughly test your code, and this gets you into the area of code coverage and even test-driven development.

More to come on this…

August 3, 2011

Case-invariant String Comparisons

Filed under: .NET,C# — Larry Parker @ 8:23 am

String comparisons are one of those things done fairly frequently in a programmer’s day job.  The fact that our alphabet has upper-case and lower-case versions of each letter makes our job a little harder since we sometimes need to perform case-invariant comparisons.  For example, we may not care about the case of the user’s last name when performing a customer lookup (although that sometimes gets resolved at the SQL level, but that’s another topic).

A simple way to compare strings without regard to case is to simply convert them to the same case.  For example:

String a = "Antwerp";
String b = "ANTWERP";

Boolean areEqual = (a.ToLower() == b.ToLower());

There’s nothing wrong with this approach (we could have used ToUpper as well), but let’s take a deeper look at what’s going on here.

The String.ToLower method has the following signature:

public string ToLower();

This means that it returns a string.  So we start off with our original string, apply the ToLower method to it, and return a new string with all characters lower case.

In our original example, we’re actually doing two ToLower operations, so two strings are returned and finally compared for equality.

Again, there’s nothing really wrong with this approach except that under the covers it seems to be doing a bit more than we need.  What we really want is to simply compare two strings for equality without regard to case.

Fortunately, there is a more efficient way.  The .NET String class provides an overload of the Equals method that lets us specify how we want to compare our string with another string.

public bool Equals(string value, StringComparison comparisonType);

One of the members of the StringComparison enum gives us just what we want, and we can rewrite our code as such:

String a = "Antwerp";
String b = "ANTWERP";

Boolean areEqual = a.Equals(b, StringComparison.OrdinalIgnoreCase);

This performs a string comparison between the two strings by using ordinal sort rules and ignoring case, and the Equals method simply returns a boolean value indicating if the comparison succeeded.  We didn’t have to convert our strings to lower-case, return the new string, and compare with the other converted string.

As a disclaimer, I have not performed benchmark tests on the two approaches to see which one is faster, nor have I inspected the .NET IL code under the covers.

But it just seems more intuitive that comparing existing strings using a designated set of rules would be a more optimal approach.

I find as I continue to work with .NET I start to think about these things a bit more.

Next Page »

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.