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!!!

Advertisements

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!

Create a free website or blog at WordPress.com.