LP on .NET

April 3, 2013

Dependency Injection – A Compromise

Filed under: .NET,C#,Software Development — Larry Parker @ 9:38 pm

I’ve blogged a lot over the past few years about writing testable code, as well as using stubs and mocking frameworks in unit tests to test all that testable code.

The common denominator to all this has been dependency injection.  To quote myself from a previous post:

Dependency injection is a pattern whereby dependencies are supplied (or injected) into a system. … 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.

I also said this in another post:

It seems that I can’t say enough about dependency injection these days. It gives me an incredible amount of control over my code in the form of testability and modularity.

I’ve been using this pattern for a couple of years now.  It really has given me an incredible amount of control over my code, especially in the form of testability.  I love writing unit tests that can mock out some or all of the injected interfaces.  It really makes testing simple.

But incredible control in the form of modularity?  When’s the last time I swapped out my persistence layer with a new module that provided a new and improved persistence layer?  Or swapped out a configuration manager with a better one by simply editing an app.config setting that pointed to another assembly?

Let me think.

Still thinking…

Hmmm.  Haven’t done it.  Except perhaps as a proof-of-concept and maybe a demo or two.

As for “simply handing the dependencies” to my classes, it’s simple in theory.  Until you end up with a constructor that takes a whole bunch of parameters and you end up writing code like this just to create an instance of your class:

   1: WidgetProvisioningManager widgetProvisioningManager = new WidgetProvisioningManager(

   2:     new WidgetProvisioningDataManager(systemContext),

   3:     new WidgetDbProvisioningDataManager(databaseServer),

   4:     o => new OrganizationDataManager(o),

   5:     (u, c) => new EmployeeDataManager(u, c),

   6:     emailServerConfiguration,

   7:     (m, t) => QueueManager.Enqueue(m, t, null),

   8:     executionContext.LogWriter,

   9:     new WidgetMembershipManager());

So much for the simple part.  Try showing this to another developer who needs to actually work with your WidgetProvisioningManager class.  “Yes Joe, to create a new instance of my WidgetProvisioningManager class, you do need to pass in seven parameters to the constructor.”  (pause)  “You got a problem with that?”

There are other options, like inversion of control containers such as StructureMap.  I’ve looked at these a bit but have not been able to warm up to them.  Too much up-front configuration, and your application becomes too dependent on them at runtime (whereas something like Moq never leaves the lab).

So now what?

Without getting into all of the heated discussions about which pattern is best (and I have encountered many both on the web and in the office), may I suggest a compromise.

Make your class’s public constructor as simple as possible, but no simpler (Einstein would love your constructor).  And developers who use your classes will not complain that they don’t have to pass in seven parameters.

As for testability, dependency injection still plays a part, as do mocking frameworks.  But make the constructor with the seven parameters internal so nobody else has to see it (and make your assembly’s internals available only to your unit test assemblies).

Using this approach, we can have our cake and eat it too.  Our WidgetProvisioningManager class now has two constructors.  The easy one marked as public for everyone to use:

   1: public WidgetProvisioningManager()

   2: {

   3:     _widgetProvisioningDataManager = new WidgetProvisioningDataManager(AppRuntime.SystemContext);

   4:     _widgetDbProvisioningDataManager = new WidgetDbProvisioningDataManager(AppRuntime.DatabaseServer);

   5:     _organizationDataManagerFactory = o => new OrganizationDataManager(o);

   6:     _employeeDataManagerFactory = (u, c) => new EmployeeDataManager(u, c);

   7:     _emailServerConfiguration = AppRuntime.EmailServerConfiguration;

   8:     _enqueueFunc = (m, t) => QueueManager.Enqueue(m, t, null);

   9:     _logWriter = AppRuntime.LogWriter;

  10:     _widgetMembershipManager =  new WidgetMembershipManager();

  11: }

And the DI constructor marked as internal for your unit tests:

   1: internal WidgetProvisioningManager(IWidgetProvisioningDataManager widgetProvisioningDataManager = null,

   2:     WidgetDbProvisioningDataManager widgetDbProvisioningDataManager = null,

   3:     Func<IContext, IOrganizationDataManager> organizationDataManagerFactory = null,

   4:     Func<IContext, EmailServerConfiguration, IEmployeeDataManager> employeeDataManagerFactory = null,

   5:     EmailServerConfiguration emailServerConfiguration = null,

   6:     Func<Int32, String, Int64> enqueueFunc = null,

   7:     ILogWriter logWriter = null,

   8:     IWidgetMembershipManager widgetMembershipManager = null)

   9: {

  10:     _widgetProvisioningDataManager = widgetProvisioningDataManager;

  11:     _widgetDbProvisioningDataManager = widgetDbProvisioningDataManager;

  12:     _organizationDataManagerFactory = organizationDataManagerFactory;

  13:     _employeeDataManagerFactory = employeeDataManagerFactory;

  14:     _emailServerConfiguration = emailServerConfiguration;

  15:     _enqueueFunc = enqueueFunc;

  16:     _logWriter = logWriter;

  17:     _widgetMembershipManager = widgetMembershipManager;

  18: }

Note that both constructors save things to private fields (the ones with the underscore prefix), and the rest of the class just uses interfaces and doesn’t care where they came from.

The public constructor creates concrete classes so consumers of the class can just use your class without any headaches.

The internal constructor is the one with all the (optional) parameters, so you can still go to town using mocking frameworks for your unit tests.

So that’s my dependency injection compromise.

Hope this helps.

March 9, 2013

OPENXML and Leading/Trailing Spaces

Filed under: SQL Server — Larry Parker @ 6:15 pm

SQL Server’s XML support can be a handy way to extract data out of a database and insert it into another database.  But there’s one thing you need to watch out for.  OPENXML “fixes” up your data by trimming leading and trailing spaces.  I suppose this could be viewed as helpful (e.g. an email address was mistakenly entered with a leading space), but it could have nasty side effects when your customer’s data really needs those spaces.

For example, suppose we have a table containing messages that will be displayed on a signboard outside a restaurant and we need to move the data from one database to another.  Also, assume that our application uses FOR XML to extract the data from the source database, and then uses OPENXML to insert it into the target database.

   1: DECLARE @messageData xml

   2:  

   3: -- This data can come from anywhere, but say it's extracted out of a database using FOR XML RAW:

   4: --      SELECT MessageGroupId, MessageId, MessageText

   5: --      FROM MessageLine

   6: --      FOR XML RAW, ROOT('Table')

   7: SET @messageData = '<Table Name="dbo.Message">

   8:   <row MessageGroupId="100" MessageId="1" MessageText="Welcome to Joe''s Restaurant!" />

   9:   <row MessageGroupId="100" MessageId="2" MessageText="     *** Early bird specials every night ***" />

  10:   <row MessageGroupId="100" MessageId="3" MessageText="Specials include:" />

  11:   <row MessageGroupId="100" MessageId="4" MessageText="     Meatloaf" />

  12:   <row MessageGroupId="100" MessageId="5" MessageText="     Sirloin Steak" />

  13:   <row MessageGroupId="100" MessageId="6" MessageText="     Baked Chicken" />

  14: </Table>

  15: '

  16:  

  17: DECLARE @docHandle int

  18:  

  19: EXEC sp_xml_preparedocument @docHandle OUTPUT, @messageData

  20:  

  21: -- And now we want to insert the message data into another database, for example:

  22: INSERT INTO MessageLine

  23: (MessageGroupId, MessageId, MessageText)

  24: SELECT MessageGroupId, MessageId, MessageText

  25: FROM OPENXML(@docHandle, N'/Table/row')

  26: WITH (MessageGroupId Int, MessageId Int, MessageText NVarChar(100)) AS x

  27:  

  28: EXEC sp_xml_removedocument @docHandle; 

The messages get inserted into the target database, but they look like this:

image

When displayed on the sign outside our restaurant, the meatloaf, sirloin steak and baked chicken all run over to the left.  Not good for business.  Smile

A solution is to use SQL Server’s nodes() method instead of OPENXML.

   1: -- Insert using nodes() method instead of OPENXML

   2: INSERT INTO MessageLine

   3: (MessageGroupId, MessageId, MessageText)

   4: SELECT T.m.value('@MessageGroupId', 'Int') AS MessageGroupId,

   5:        T.m.value('@MessageId', 'Int') AS MessageId,

   6:        T.m.value('@MessageText', 'NVarChar(100)') AS MessageText

   7: FROM @messageData.nodes('/Table/row') AS T(m)

Now our sign looks just the way the customer wants:

image

The nodes() method preserves the leading and trailing spaces, and is a bit easier to use than OPENXML as well because you don’t have to mess with preparing and removing the @docHandle variable.

There are a couple of caveats to this.  In the value() method, be sure to map the TEXT data type to VARCHAR(MAX), NTEXT to NVARCHAR(MAX), and IMAGE to VARBINARY(MAX).  Also, when copying XML columns, you need to use the query() method instead of value().

So a little extra work in that respect, but the nodes() method will do a better job of copying your data verbatim than OPENXML.

Hope this helps.

June 3, 2012

Writing Explicit Code with Dependency Injection

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

It seems that I can’t say enough about dependency injection these days.  It gives me an incredible amount of control over my code in the form of testability and modularity.

One of the additional benefits I have gained by following this pattern is that my code has become more explicit.  What do I mean by that?

Consider the following example of “classic” programming:

CustomerDataManager customerDataManager = new CustomerDataManager();

Customer customer = customerDataManager.GetCustomerById(1001);

This code is simple enough.  We just create an instance of our customer data manager, call the GetCustomerById method, and get our customer back.  The GetCustomerById method hits the database with the appropriate SQL statement (or using some other data access technology) and we’re done.  The code looks like this:

public class CustomerDataManager
{
    public CustomerDataManager()
    {
        _connString = ConfigurationManager.ConnectionStrings["MainDbConnectionString"].ConnectionString;
    }

    private String _connString;

    public Customer GetCustomerById(Int32 customerId)
    {
        Customer customer = ... // hit db using above connection string

        return customer;
    }
}

Note the connection string obtained in the constructor using the .NET ConfigurationManager class.  This requires your app to have the following in its app.config file:

<configuration>
  <connectionStrings>
    <add name="MainDbConnectionString" connectionString="Data Source=.; Initial Catalog=TheDb; etc...;"/>
  </connectionStrings>

And we’re done.  The customer data manager can now be used by anyone on your team.  All that they need to know is that their executable’s app.config file needs a connection string called MainDbConnectionString.  But you’ve documented that (right? Smile), so that won’t be a problem for anyone.

Well, it turns out that the developers on your team using your CustomerDataManager class already have their own connection string defined in their executable’s app.config and it’s not called MainDbConnectionString.  You ask them why it’s not called MainDbConnectionString.  They ask you why you’re not calling it ApplicationDbConnectionString.  And like the north and south going Zax, you just stare each other down with your arms folded.

OK, hopefully it’s not that bad.  But why even go there?  Why have your data manager define an external dependency like an app.config setting in the first place?

The way around this whole thing is to just inject the connection string into the constructor and remove the dependency.

Let’s rewrite our customer data manager’s constructor to handle this:

public CustomerDataManager(String connString)
{
    _connString = connString;
}

Now your CustomerDataManager class is out of the business of app.config settings.  It doesn’t know or care anything about configuration and doesn’t need to access the dubious ConfigurationManager class (dubious because it makes it so easy to create dependencies like this).

And now your CustomerDataManager class can be used by the developer who gets all of his connection strings from an encrypted XML file, and can also be used by the other guy who gets them from the registry (using his own encryption algorithm, of course).  They don’t mind passing the connection string into your data manager and can’t stop talking about how easy your classes are to work with.

You’re a hero.

All because your code was explicit and didn’t make any assumptions about its runtime environment.

February 12, 2012

Deleting a Line in the Visual Studio Text Editor

Filed under: .NET,C#,Visual Studio — Larry Parker @ 6:07 pm

After programming in Visual Studio for almost a decade, I recently found out (by accident) an easier way to delete a line.

Instead of first selecting the line with Shift-Down-Arrow and then pressing the Delete key, you can just press Shift-Delete.

Simple!

January 31, 2012

Obtaining SQL Identity Information

Filed under: Software Development,SQL Server — Larry Parker @ 7:05 pm

I found a great query today on this blog for obtaining information about SQL identity columns.  Here’s my updated version to handle SQL schemas:

SELECT IDENT_SEED(TABLE_SCHEMA + '.' + TABLE_NAME) AS Seed,
    IDENT_INCR(TABLE_SCHEMA + '.' + TABLE_NAME) AS Increment,
    IDENT_CURRENT(TABLE_SCHEMA + '.' + TABLE_NAME) AS Current_Identity,
    TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), 'TableHasIdentity') = 1
  AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_SCHEMA + '.' + TABLE_NAME

This allows you to easily find out every table in your database that has an identity column, and what the seed, increment, and current values are.

Super helpful!

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.

Next Page »

Blog at WordPress.com.