Apr 8 2008

Moq is cool!

Category: Mockingfossmo @ 15:55

So, one of the ways to use a mocking framework, is to simulate a object that you don't want to, or can't, create the ordinary way.
As I mentioned in a previous post, I have started using a new mocking framework called Moq. I really like this framework. It's easy to work with, and has a easy syntax. It heavily uses lambda expressions. I think this gives a very elegant and powerful syntax.

A small example of the syntax:

[Test]
public void Person_ValueIsReturned_ReturnsName()
{
Mock person = new Mock<IPerson>();
person.Expect(x => x.GetNameFromStore()).Return("James");
Employee employee = new Employee(person.Object);
Assert.AreEqual("James", employee.Name);
}

If you is used to working with Rhino Mocks, you probably wonder if I have forgotten to add Record/Playback. The thing is, you don't need it in this framework. It has a more NMock similar syntax.

If you expect a object to be called more than one time, you can write the syntax like this:

int elementCounter = 0;
person.Expect(x => x.GetNameFromStore).Returns(() =>
{
elementCounter++;
if (elementCounter == 1) return "James";
if (elementCounter == 2) return "Roy";
return "Default";
});

I will try to write more about this framework as I learn more about it.

Tags:

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Apr 1 2008

A problem I had with a new mocking framework.

Category: C# | Testing | Mockingfossmo @ 15:21
It took me some time to figure this out, but I finally got it.
If you in RhinoMocks want to create a mock based on a interface, the syntax is like this:

IMyInterface myObject = mock.CreateMock<IMyInterface>();

myObject is now a mock object.

When using Moq (mock-you) mocking framework, you have to add .Object to the mock to get the object.
This syntax I don't find very intuitive.Below is a example of a test using Moq (without Expectations):

[TestFixture]
public class MyTestClass
{
   [Test]
   public void MyTest()
   {
      var mockedTestInterface = new Mock<IMyInterface >();
      MyClass myTest = new MyClass (mockedTestInterface.Object);
   }
}

I guess it will take a little time to get used to the syntax. But, that said,
I really like this framework.

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5