Back to Basics Series


22
Feb 10

An Overview Of System.Collections.Generic

I recently put up a post on my blog about some of the new concurrent collections in .NET 4.0, and I noticed that a lot of people were being sent by Google to those posts who were only searching for System.Collections. I figured that maybe people could use a similar overview of the collections available to them in the System.Collections.Generic namespace, since it seems to me that no one uses anything other than List and Dictionary. So, in this post, I am going to take a look at a few of those collections, and explain exactly why you would want to use them.

Keep in mind as you read through this list that you shouldn’t just start switching out collection types in code that you already have working. If something is working and performing properly for you, it is almost always better to take the easier route until you have proof that the easy approach does not work for you.

System.Collections.Generic.List<T>

The first collection that we are going to look at is List<T>. Like I said before, this collection seems to be the fallback, and with good reason. It is unsorted (but supports sorting), items can be added, removed, or inserted at a specific index. It also has indexed access, meaning that items can be accessed directly using a numeric index. You can add Ranges, perform binary searches, perform sequential searches, built in sorting, get the count of items, check for items within it, pass a delegate to it to perform actions, etc… It really is the Swiss Army knife of collections.

Continue reading →


31
Mar 09

Beginning Mocking With Moq 3 – Part 4

Other parts in this series

In this fourth part of this series (which is a bit delayed due to my travels to MIX 09) I am going to discuss mocking multiple interfaces and doing callbacks in Moq 3. While these are not features that you are going to use very often, they are features that when you need them, it is often in situations where you have no other option.

Before we get to these two features, I want to really quickly touch on a previous feature that we have already looked at. On Twitter a little bit ago, there was a question about confirming that a method was not called on the mock. To check the number of calls:

mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));

We can use the same construct to make sure that the method was never called:

mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Never());

It is essentially the equivalent of saying “Times.Exactly(0)”, but it just looks much nicer, and provides a better error message. I just wanted to clear this up in case anyone else was wondering.

Mocking Multiple Interfaces

So now let’s look at mocking multiple interfaces. As we have already seen, if we want to create a mock of an interface then we can do it like this:

var mockFileWriter = new Mock<IFileWriter>();

But a situation that you can often get in is where a method requires a particular method, but then also expects the class to implement IDisposable. With some mocking frameworks this can be problematic. Thankfully Moq 3 provides us with an easy way to implement this by use of the “As” method on the mock itself. Some frameworks refer to this as a multi-mock:

var mockFileWriter = new Mock<IFileWriter>();
mockFileWriter.As<IDisposable>();

Now that our mock supports two interfaces, how do we create expectations and verifications on this mock? Well, in the call above, the “As” method returns a Mock<IDisposable"> which allows us to do setup and perform verification on it. We could either hold onto this mock, or if we wanted to later perform verification we could just call “As” again, since we can’t add an interface twice:

mockFileWriter.As<IDisposable>().Verify(d => d.Dispose());

Extremely powerful and very easy to work with!

Callbacks

Next we are going to look at callbacks, which are a feature in Moq that it is entirely possible that you’ll never use. They allow you to specify a chunk of code to be executed when a method is called. So, looking again at the “WriteLine” method above, we could record every invocation into a list:

var values = new List<string>();
mockFileWriter.Setup(fw => fw.WriteLine("1001,10.53")).Callback((string value) => values.Add(value));

Or we could ignore the parameter and just increment a count or something:

int count = 0;
mockFileWriter.Setup(fw => fw.WriteLine("1001,10.53")).Callback(() => count++);

But since Moq provides functionality in both of these areas for most of what you would want to do, there isn’t really too many different points at which you would need these tools. In fact, if you think you need to use “Callback” you should probably look a little harder to see if Moq can do what you want to do automatically.

Summary

We looked at how to guarantee that a method is never called on a mock. Then we saw how to implement multiple interfaces on a single mock and finally how to use callbacks in Moq. I hope that you found this information useful, and hopefully the next entry in this series will be up soon. In that entry we are going to discuss raising exceptions and events from Mocks.


13
Mar 09

Beginning Mocking With Moq 3 – Part 3

Other parts in this series

Part 1

Part 2

In the previous part of this series, we looked at how you can verify on an interface exactly what was called using Moq’s “Verify” syntax. In this entry we are going to take a look at setting up mocks with return values.

Setting Up Return Values

If you have ever done mocking before in the past then you probably know that the “classic” way of using mocks is to setup the mock before you call it. So in the last post when we had this line:

mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));

which verifies, after the fact, what was called. In the “classic” way of doing things we could have written the test like this: (In Moq 2 the method was called “Expect” not “Setup”)

[Fact]
public void it_should_pass_data_to_file_writer2()
{
    var order = new Order();
    order.OrderId = 1001;
    order.OrderTotal = 10.53M;

    var mockFileWriter = new Mock<IFileWriter>();
    mockFileWriter.Setup(fw => fw.WriteLine("1001,10.53")).AtMostOnce();

    var orderWriter = new OrderWriter(mockFileWriter.Object);    
    orderWriter.WriteOrder(order);

    mockFileWriter.VerifyAll();
}

Here you can see that right after we declare the mock we call “Setup” and pass the expectation to it. We then call “AtMostOnce” to make sure that it is only called a single time. After that we actually perform our test actions. At this point though we haven’t asserted anything, so we have to call “VerifyAll” on the mock that was created. This causes all setup calls to be verified, and an exception will be raised if one of the expectations weren’t met.

So the “Verify” syntax seems so much better, we don’t need to do two calls, or remember to call “VerifyAll” after the fact. So why is the original Setup syntax still there? Well, besides backward compatibility. Part of the reason is that there is one key thing that you can’t do after the fact, and that is setting up return values on method calls. Let’s start this by creating an OrderReader class which uses an IFileReader interface. The IFileReader interface has a line called “ReadLine” which returns a string.

Since we want to mock this IFileReader and call this method on it that returns a value, we need some way to setup the return value. Thanksfully, Moq provides us with an extremely easy way to do this:

public override void EstablishContext()
{
    var mockFileReader = new Mock<IFileReader>();
    mockFileReader.Setup(fr => fr.ReadLine()).Returns("1002,10.34");

    orderReader = new OrderReader(mockFileReader.Object);
}

public override void Because()
{
    order = orderReader.ReadOrder();
}

Moq can see the return type of the method that you are passing in, and then lets you return back an instance of that type. In fact, if a method is returning another interface that you need to mock, then you can return a mock type! This let’s you build up more complex interfaces from mocks.

Now that we have setup the mock and created our order, we simply call the “ReadOrder” method and we get back an order object. All that is left to assert now is that the line from the IFileReader was parsed and turned back into an order correctly:

[Fact]
public void it_should_have_order_id_set()
{            
    Assert.Equal(1002, order.OrderId);            
}

[Fact]
public void it_should_have_order_total_set()
{
    Assert.Equal(10.34M, order.OrderTotal);
}

And that was easy. But I mentioned earlier that we are able to setup two mocks and have one mock returned from the other mock. How does that work?

Returning Mocks From Other Mocks

Well, it works just like you are passing a mock to any other method. So if we have two interfaces like this:

internal interface IDoSomething
{
    IDoSomethingElse GetSomethingElse();
}

internal interface IDoSomethingElse
{
    string GetSomeValue();
}

Then it is as simple as doing this:

var mockSomethingElse = new Mock<IDoSomethingElse>();
mockSomethingElse.Setup(mse => mse.GetSomeValue()).Returns("Something");

var mockSomething = new Mock<IDoSomething>();
mockSomething.Setup(ms => ms.GetSomethingElse()).Returns(mockSomethingElse.Object);

And there you have it, we have created the IDoSomethingElse mock and setup expectations on its return value. Then we mock IDoSomething and when we setup its method, we simply pass the mock.Object into the “Returns” method.

Summary

In this post we have looked at setting up return values on mocks so that we can return canned values from them to satisfy the needs of calling classes. If you are setting up return values on mocks and not really verifying anything that was called on the mock, then technically you are not mocking, but instead stubbing. I guess that is a topic for another day though. I hope you enjoyed this entry, and stay tuned for the next post when we will look at mocking multiple interfaces and callbacks.


10
Mar 09

Beginning Mocking With Moq 3 – Part 2

Other parts in this series

Part 1

Part 3

In the previous entry in this series on beginning mocking using Moq, we looked at how to create a mock and then later verify that some method was called. This is probably the most basic usage of a mocking framework, which is to simply verify a method call. One of the things that is a bit confusing when looking at a statement in a test that uses a lambda is to realize that the code you are seeing in the assertion is not actually executing. So when you see a statement like this:

mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));

The lambda inside of the “Verify” method:

fw => fw.WriteLine("1001,10.53")

Is being turned into an expression tree and then analyzed by Moq, not actually being executed. Whether or not you understand what I mean by that, what you need to understand is that we are merely telling Moq what to look for, not running any code.

In order to show this a bit more clearly, what would happen if in the above code we wanted to verify that any string was passed into the “WriteLine” method, not just a particular string. Well, we simply have to call the “Verify” method like this:

mockFileWriter.Verify(fw => fw.WriteLine(It.IsAny<string>()), Times.Exactly(1));

Here you can see that we replaced the “1001,10.53” string with a method call on the static class “It”:

It.IsAny<string>())

Now it may be more obvious that this code is not being executed because it no longer looks like a simple method call. You can now see that Moq will look at this method call within the “WriteLine” method and adjust the way that it verifies this method. It will still look for exactly one call to “WriteLine” but it will accept any string passed to it, and not just the one that we had previously specified.

There are also a few other ways to verify these methods calls, such as IsRegex:

fw.WriteLine(It.IsRegex("^1001"))

Here we are matching a regex to check that the string starts with 1001. There is also one additional method called “IsInRange” which will check to see if a numerical value is within a particular range.

Verifying With Predicates

To take this a step further, we can use any predicate expression to define what we want to verify as well. For those who don’t know, a Predicate is simply a delegate that returns a boolean value. So, a variable goes in, you do some sort of check and then return a true or false. So if we wanted to check for any string that is longer than 3 characters, then we could call the “It.Is” method like this:

mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.Length > 3)), Times.Exactly(1));

Or if we wanted to check that the string started with “1001,10.53” instead of equaling that, then we could do this:

mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.StartsWith("1001,10.53"))), Times.Exactly(1));

There is no limit to the comparisons that we can do. We could also compare against a local variable:

string expectedValue = "1001,10.53";
mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.StartsWith(expectedValue))), Times.Exactly(1));

This way we can keep the expected value out of the verify, making it arguably easier to read.

Property Verification

Now that you know how to verify that a method was called, what happens if we need to verify that a property was set or read? Well, it actually looks very similar to method call verification above. In order to show this, lets define a “FileName” property on the IFileWriter interface that we will set with a filename by the OrderWriter class. This is likely a poor design in a real application, but it will serve our purpose here.

So now in our OrderWriter we will do this:

public void WriteOrder(Order order)
{
    fileWriter.FileName = order.OrderId + ".txt";
    fileWriter.WriteLine(String.Format("{0},{1}", order.OrderId, order.OrderTotal));
}

Here we set the filename using the order id and then call the “WriteLine” method. So we will need another test:

[Fact]
public void it_should_set_the_file_name()
{
    mockFileWriter.VerifySet(fw => fw.FileName);
}

This test will now only pass if something is assigned to the “FileName” property. The only problem is that we could set anything to this property, it isn’t necessarily what we want. Thankfully Moq provides a way for us to check that it was set to an exact value:

mockFileWriter.VerifySet(fw => fw.FileName = "1001.txt");

Sweet. Everything works as expected. Just as with the methods, we can match against the static “It” class like this:

mockFileWriter.VerifySet(fw => fw.FileName = It.Is<string>(s => s.StartsWith("1001")));

So as you can see, properties are just as easy to work with as methods are.

Wrap Up

In this post we have taken a look at how the verification lambdas work, and how we can use Moq to verify inexact parameter values. We have also taken a look at how we can check parameters using any predicate value. Then finally we take a look at how we can verify property values as well. In future entries in this series we will take a look at returning values, events, callsbacks, etc… So stay tuned!


8
Mar 09

Beginning Mocking With Moq 3 – Part 1

Other parts in this series

Part 2

Part 3

While I was at the ALT.NET and MVP summits, the one topic that came up over and over again was the fact that we don’t focus on the beginners enough. And not necessarily beginners in the sense of brand new developers, but beginners in terms of those who just haven’t been exposed to many of the concepts that we work with so often. Many of us have forgotten how hard it was to grasp some of these concepts. Since Moq 3 went final while I was out of town, I felt like doing an introduction to mocking using Moq 3 was the perfect place to start!

At this point many developers are now doing automated testing, but not necessarily unit testing. The reason I say this is that most developers don’t know how to break their applications down so that the pieces can be tested independently. Mocking is an easy way to replace dependencies during testing so that you don’t need to actually call out to a database, web service, file system, or even just another class. The idea is that you are isolating small pieces of functionality during testing, hence why they call it “unit” testing.

In order to do this you must design your classes to use virtual methods or implement interfaces. To look at a simple example let’s start off with an Order class.

public class Order
{
    public int OrderId { get; set; }
    public decimal OrderTotal { get; set; }
}

Very simple, so that we don’t bury the concept under tons of business logic. The first thing that we are going to do is write the order out to a file, but I want to test this functionality without having to actually write my files somewhere to a disk. To do this I am first going to create an OrderWriter class:

public class OrderWriter
{
    private readonly IFileWriter fileWriter;

    public OrderWriter(IFileWriter fileWriter)
    {
        this.fileWriter = fileWriter;
    }

    public void WriteOrder(Order order)
    {
        fileWriter.WriteLine(String.Format("{0},{1}", order.OrderId, order.OrderTotal));
    }
}

As you can see, this class takes an IFileWriter interface in its constructor and then when “WriteOrder” is called, it formats the string and passes it to the fileWriter field. The IFileWriter interface is very simple and looks like this:

public interface IFileWriter
{
    void WriteLine(string line);
}

By using this interface we have isolated the actual writing of the file to the disk from the formatting of the data that is going to be written to the disk. The tests that we wrote to form our above classes (you are using TDD, aren’t you? :-) look like this:

public class When_an_order_is_to_be_written_to_disk : ContextSpecification
{
    private Order order;
    private Mock<IFileWriter> mockFileWriter;
    private OrderWriter orderWriter;

    public override void EstablishContext()
    {
        order = new Order();
        order.OrderId = 1001;
        order.OrderTotal = 10.53M;

        mockFileWriter = new Mock<IFileWriter>();
        orderWriter = new OrderWriter(mockFileWriter.Object);
    }

    public override void Because()
    {
        orderWriter.WriteOrder(order);
    }        

    [Fact]        
    public void it_should_pass_data_to_file_writer()
    {                    
        mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));
    }        
}

In this test I am using xUnit, which uses the “Fact” attribute to label something a test. It doesn’t use a “TestFixture” attribute or anything. And it uses the class constructor for setup instead of a method with a “Setup” attribute. Personally I really like many of the design decisions that the xUnit guys took.

Lame Disclaimer

You may also notice that these tests were written in the Context/Specification manner, which I am taking a risk by using. Not because the style is risky, but because I’ll probably have 800 people ripping apart the way that I did it. Honestly though, if you have any suggestions on how these could be written in a better way, please let me know. For these tests, I tried to stick to vanilla xUnit in order to keep the new concepts as few as possible.

While these tests may look very different to you, one of the advantages of this style of test comes in when you run them:

 image

See how you can tell what is going on? When you have multiple tests in each context, it looks even better. The more I talk to people who write tests in this style, the more I am sold on it. But anyways, this post isn’t about unit testing styles, so let’s move on!

If you go back and look at the test earlier in this post you can see that we are creating a new Order in the setup:

public override void EstablishContext()
{
    order = new Order();
    order.OrderId = 1001;
    order.OrderTotal = 10.53M;

    mockFileWriter = new Mock<IFileWriter>();
    orderWriter = new OrderWriter(mockFileWriter.Object);
}

Here we are setting up the context of the tests. We create a new order, set some values, then declare a mock IFileWriter and then pass it into the OrderWriter class. So we are going to test if we can write the file to disk, but we don’t want to hit the disk. So what is the point? Right? Well, not really, when writing an order to disk in a real application there could be significant logic in how to format the file. The code to actually write the file to disk should be separately tested to make sure it works, but being able to isolate the formatting of the data for the order and test it, is very useful.

We do this by creating a new “Mock” class and pass it the interface as a generic type parameter that we want to mock. Next we create the “OrderWriter” class and pass in the mocked instance of our IFileWriter interface by accessing the Object property on the Mock<IFileWriter> object. We can’t pass the Mock<IFileWriter> instance to the OrderWriter constructor because it takes an IFileWriter, and this is why the “Object” property is available. Hate to repeat myself, but the process is this:

  1. Create an instance of Moq’s “Mock” class that takes a interface or class with virtual methods as a generic parameter.
  2. Tell the Mock what you want to happen, specifying parameters, and even return values. We will get deeper into this later on.
  3. Get back the mocked interface which will behave in the way in which you told it to. Use this mocked interface in your code.
  4. Call “Verify” or “VerifyAll” on the mock to ensure that what you said would happen actually happened. This step is not always required.

Once we get the mocked interface we can create the OrderWriter class and pass the mocked interface into it. When we pass the order into it, we will format the order and the mocked interface will get called with the formatted string representing the order. Next we want to actually perform the action that we want to test:

public override void Because()
{
    orderWriter.WriteOrder(order);
}

Here we pass the order into the OrderWriter and then next we assert that the method on the IFileWriter interface was called property with the correct values:

[Fact]        
public void it_should_pass_data_to_file_writer()
{                    
    mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));
}

When we call “Verify” on our mock with a lambda we are telling it to check that the call we pass to it actually occurred. The second parameter that we pass to it (which is optional) tells the mock how many times we expected it to be called. So here we are asking the mockFileWriter object if the “WriteLine” method was called with the value “1001,10.53” exactly one time. If this occurred, then the test will pass.

In this post we have looked at creating a mock class, tell it that a particular method will be called, and then verify that it actually happened. In the future posts we are going to look at setting up return values, dealing with properties, dealing with parameters that we don’t know at compile time, events, etc… So stay tuned!