Posted on 11/5/2009 11:16:43 AM by Justin Etheredge
I hate these posts. I hate them because I feel like I am drawing attention to another post which made me cringe a little bit. But I think that reacting to these posts is good, because having a healthy debate about topics is good, especially if you can keep from devolving into mud slinging and attacks. The post I am talking about is this one, which is titled “It’s OK Not to Write Unit Tests”. I was surprised to see that it is actually from March of this year, and maybe I have seen it before, maybe not, but this time I felt the need to respond to it.
One thing that I want to say first is that I want to keep this calm and mellow. I used to react very calmly in retort to this kind of post, but over time as I wrote more and more on my blog, I found myself starting to become the “everything is black and white and I’m going to tell you that you’re wrong with my blaring megaphone” kind of writer that I often loathe when I read. Sure, it might not make the best link-bait in the world, but maybe I’ll feel a bit better after I write it. Oh, and the blood pressure might stay down a little bit. Having said all that, here we go…
Continue reading the rest of this post...
Posted on 6/30/2009 10:25:21 PM by Justin Etheredge
The title of this post actually isn’t a question that I get asked very often. I think the reason that I don’t get asked this very often is because of two different reasons. The first reason is that people (and programmers especially) are embarrassed to admit when they don’t know something that they feel like they should know. Secondly, many developers out there think they know exactly what you are talking about when someone says “unit testing”.
Of those developers who think they know what unit testing actually means, I would be willing to bet that only about 10% really do. You see, the problem is that when most developers are asked to define unit testing they will say something like “tests that are run against a project using a unit testing framework”. That is kinda right… well… not really. It isn’t really right at all. In fact, calling frameworks like NUnit, xUnit, MbUnit, MSTest, etc… “unit testing frameworks” is inaccurate. They are instead “automated testing frameworks” which can be used to execute any number of kinds of tests. One of these kinds of tests just happens to be unit tests. There are also integration tests, performance tests, load tests, etc…
Okay, so what exactly is a unit test? It is a test which verifies a “unit”, or the smallest piece of an application which is able to be tested. Ideally, when writing a unit test in C#, you’d want to isolate an individual class and write tests against only its functionality. The developers doesn’t want to pull in external dependencies and doesn’t want to access external processes or services. Unit testing is all about testing small pieces in isolation.
Continue reading the rest of this post...
Posted on 3/31/2009 10:06:17 PM by Justin Etheredge
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.
Posted on 3/13/2009 8:03:00 AM by Justin Etheredge
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.
Posted on 3/10/2009 10:42:53 PM by Justin Etheredge
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!