Category: Tools

Simplifying Rhino.Mocks, Round III: kinds of mocks

My last two posts regarding Rhino.Mocks, attracted quite a lot of attention. Focusing on solution I proposed for limiting complexity around creation different kinds of mocks, one thing was pointed out by few people as not the best solution. Ayende called it “in your face! API design”, that is stating the kind of mock you want to create explicitly, via method parameter.

I don’t think that doing it via method name is any less explicit, but let’s not go there. Instead, let’s think for a while – why do we need 4 kinds of mocks anyway?

All differences boil down to one thing – how the mock handles unrecorded calls:

  • StrictMock (_repo.CreateMock overloads), any unexpected call results in exception being thrown.
  • DynamicMock (_repo.DynamicMock overloads), any unexpected call returns default(T), where T is return type, that is null or 0 for value types.
  • PartialMock (_repo.PartialMock overloads), this works only for classes and any unexpected call is not intercepted but forwarded to the actual method of that class.
  • Stub (_repo.Stub), this is similar to DynamicMock with addition, that if you assign a value to a property, it remembers that value.

Those are all very important differences but I’d say quite subtle. Subtle to a point, that I am willing to agree that specifying them upfront either via explicitly named creation method, or via explicit parameter is throwing “in your face!” decisions that you shouldn’t have to be concerned about at this point.

Morten Lyhr noticed this as well, and he suggested the following solution:

public class LoginPresenterFixture
{
   private MockRepository _mockRepository;
   private LoginPresenter _loginPresenter;
   private LoginView _loginView;
   [SetUp]
   public void Init()
   {
      _mockRepository = new MockRepository();
      _loginView = _mockRepository.DynamicMock<LoginView>();
      CreateLoginPresenter();
   }
   private void CreateLoginPresenter()
   {
      _loginPresenter = new LoginPresenter(_loginView);
   }
   [Test]
   public void Strict_Test_Not_As_Often_Used()
   {
      //Override default mock kind
      _mockRepository.StrictMockBehaviour(_loginView);//this is important
      using (_mockRepository.Record())
      {
         Expect.Call(_loginView.ShowView);
      }
      using (_mockRepository.Playback())
      {
         _loginPresenter.Show();
      }
   }
}

It’s some way of dealing with it but it still requires you to explicitly assign behavior to mock object.

It’s still incorrect level of granularity though: instead of class level (different class per different mock kind) we now deal with it on object level (different kind per object).

I’d however move it yet one step further, to method level (different kind per method).

It might look something like this:

   [Test]
   public void Strict_Test_Not_As_Often_Used()
   {
      using (_mockRepository.Record())
      {
         Expect.Call(_loginView.ShowView);
         //Decide what to do with unexpected calls:
         Expect.For(_loginView).NothingElse();//this is important
      }
      using (_mockRepository.Playback())
      {
         _loginPresenter.Show();
      }
   }

Again, difference is very subtle, but important: instead of explicitly deciding about kind of mock, we decide about what to do about unexpected calls, which is more natural and closer to the actual problem. Different kinds of mocks, are just proposed solutions. The ‘kind’ is no longer a property of the mock object.

It also makes it easier to start with mocking framework: decision about what to do about unexpected calls is not thrown at your face at the very first lines, hidden behind terms like “Partial” or “Dynamic”. Instead you make that decision explicitly (and this time it’s a good thing) in last responsible moment that is in the actual test.

Technorati Tags: , , ,

Simplifying Rhino.Mocks

[UPDATE]: Example code is updated. I realized that Kind.Multi is not needed, since you can infer that from passed parameters (when ctorArgs are present, user obviously wants to create MultiMock). I also changed default Kind to Relaxed, since this is the most common one.

Ayende wrote today about his ideas for new version of Rhino.Mocks. I like the new syntax (looks similar to what MoQ offers), but there’s one more change I’d like to see.

Here’s the list of all methods of MockRepository, used to create some kind of mock:

 

public T CreateMock<T>(params object[] argumentsForConstructor);
public object CreateMock(Type type, params object[] argumentsForConstructor);
public T CreateMockWithRemoting<T>(params object[] argumentsForConstructor);
public object CreateMockWithRemoting(Type type, params object[] argumentsForConstructor);
public T CreateMultiMock<T>(params Type[] extraTypes);
public object CreateMultiMock(Type mainType, params Type[] extraTypes);
public T CreateMultiMock<T>(Type[] extraTypes, params object[] argumentsForConstructor);
public object CreateMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor);
public T DynamicMock<T>(params object[] argumentsForConstructor);
public object DynamicMock(Type type, params object[] argumentsForConstructor);
public T DynamicMockWithRemoting<T>(params object[] argumentsForConstructor);
public object DynamicMockWithRemoting(Type type, params object[] argumentsForConstructor);
public T DynamicMultiMock<T>(params Type[] extraTypes);
public object DynamicMultiMock(Type mainType, params Type[] extraTypes);
public T DynamicMultiMock<T>(Type[] extraTypes, params object[] argumentsForConstructor);
public object DynamicMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor);
public static T GenerateStub<T>(params object[] argumentsForConstructor);
public static object GenerateStub(Type type, params object[] argumentsForConstructor);
public T PartialMock<T>(params object[] argumentsForConstructor) where T : class;
public object PartialMock(Type type, params object[] argumentsForConstructor);
public T PartialMultiMock<T>(params Type[] extraTypes);
public T PartialMultiMock<T>(Type[] extraTypes, params object[] argumentsForConstructor);
public object PartialMultiMock(Type type, params Type[] extraTypes);
public object PartialMultiMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor);
public T Stub<T>(params object[] argumentsForConstructor);
public object Stub(Type type, params object[] argumentsForConstructor);

26 methods including 2 static methods (most of them in 2 flavors: generic and 1.1-like). I guess that’s a lot. I can imagine this can be a little overwhelming for new users.

I understand that tearing interface of MockRepository would not be the best idea, but I think that creating a Facade to it might simplify things a lot.

public class MockRepositorySlim
{
    private static readonly Dictionary<Kind, Func<MockRepository, Type, object[], Type[], object>> _mockMethods =
        new Dictionary<Kind, Func<MockRepository, Type, object[], Type[], object>>(9)
            {
                {Kind.Relaxed,(r, t, cp, et) => et.Length > 0 ? r.DynamicMultiMock(t, et, cp) : r.DynamicMock(t, cp)},
                {Kind.Strict, (r, t, cp, et) => et.Length > 0 ? r.CreateMultiMock(t, et, cp) : r.CreateMock(t, cp)},
                {Kind.Stub, (r, t, cp, et) => r.Stub(t, cp)},
                {Kind.Partial,(r, t, cp, et) => et.Length > 0 ? r.PartialMultiMock(t, et, cp) : r.PartialMock(t, cp)},
                {Kind.Strict | Kind.WithRemoting, (r, t, cp, et) => r.CreateMockWithRemoting(t, cp)},
                {Kind.Relaxed | Kind.WithRemoting, (r, t, cp, et) => r.DynamicMockWithRemoting(t, cp)}
            };
 
    private readonly MockRepository _repo = new MockRepository();
 
    public TTypeToMock Mock<TTypeToMock>()
    {
        return Mock<TTypeToMock>(Kind.Relaxed, new Type[0], new object[0]);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind)
    {
        return Mock<TTypeToMock>(mockKind, new Type[0], new object[0]);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind, params object[] ctorArgs)
    {
        return Mock<TTypeToMock>(mockKind, new Type[0], ctorArgs);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind, params Type[] extraTypes)
    {
        return Mock<TTypeToMock>(mockKind, extraTypes, new object[0]);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind, Type[] extraTypes, params object[] ctorArgs)
    {
        if (extraTypes == null) throw new ArgumentNullException("extraTypes");
        if (ctorArgs == null) throw new ArgumentNullException("ctorArgs");
 
        if (mockKind == Kind.WithRemoting)
            mockKind &= Kind.Strict;
        else if (!_mockMethods.ContainsKey(mockKind))
        {
            if ((mockKind & Kind.WithRemoting) != 0)
                throw new ArgumentException("This kind of mock does not support remoting.");
            throw new ArgumentException("Invalid mock kind.", "mockKind");
        }
        //NOTE: possibly with lock in this call
        var mock = (TTypeToMock) _mockMethods[mockKind](_repo, typeof (TTypeToMock), ctorArgs, extraTypes);
        return mock;
    }
}
internal static class KindExtensions
{
    public static bool IsSet(this Kind kind, Kind value)
    {
        return (kind & value) == 0;
    }
}
 
 
[Flags]
public enum Kind
{
    Strict=0,
    WithRemoting=1,
    Relaxed=2,
    Stub=4,
    Partial=8
}

Now we have only 5 methods, 4 of which call the 5th one. I guess that’s simpler solution. Is it any better?

Technorati Tags: , ,

Amazing Wii remote demo.

I’m speechless.

Technorati Tags: , ,

Mocking with Moq and Rhino.Mocks

Last week I’ve read quite a few new blogposts about Moq mocking framework. I had looked at it once, when it was first released, but I didn’t find it interesting back then. Now that version 2.0 was released I decided to give it a go once again.

Here’s very simple model I created:

model

It’s a class with one method that uses helper object to obtain a value and possibly raise an event.

Here’s the whole code:

public interface IHelper
    {
        int Param { set; }
        string SomeMethod();
    }
    public class MyClass
    {
        public MyClass(IHelper helper)
        {
            Helper = helper;
        }
 
        public IHelper Helper { set; private get; }
 
        public event EventHandler MyEvent = delegate { };
 
        public void DoSomething(int parameter)
        {
            Helper.Param = parameter;
            string result = Helper.SomeMethod();
            if (result != null)
                MyEvent(null, EventArgs.Empty);
        }
    }

Now, to the fun part:

Let’s see how we can verify that when SomeMethod returns null, MyEvent is indeed not raised. First with Rhino.Mocks

   1:          [Test]
   2:          public void DoDomething_should_NOT_raise_MyEvent_when_helperSomeMethod_returns_null_Rhino()
   3:          {
   4:              var helper = _mocks.CreateMock<IHelper>();
   5:              var subscriber = _mocks.CreateMock<IEventSubscriber<EventArgs>>();
   6:              using (_mocks.Record())
   7:              {
   8:                  Expect.Call(helper.Param = 3);
   9:                  Expect.Call(helper.SomeMethod()).Return(null);
  10:                  DoNotExpect.Call(() => subscriber.Method(null, EventArgs.Empty));
  11:              }
  12:              using (_mocks.Playback())
  13:              {
  14:                  var sut = new MyClass(helper);
  15:                  sut.MyEvent += subscriber.Method;
  16:                  sut.DoSomething(3);
  17:              }
  18:          }

18 lines of code (you could cut that down to 13 simply by using ReplayAll() instead of Record() and VerifyAll in TearDown method instead of Playback, but I prefer it this way. My code is clean and quite well serves as documentation: Especially thanks to explicit usage of DoNotExpect.

The only awkward thing, is that whereas in both Expect call, I insert bare calls, in DoNotExpect.Call I had to use lambda. It’s a small inconsistency.

Now how would the same test look like with Moq?

   1:          [Test]
   2:          public void DoDomething_should_NOT_raise_MyEvent_when_helperSomeMethod_returns_null_Moq()
   3:          {
   4:              var helper = new Mock<IHelper>(MockBehavior.Strict);
   5:              var subscriber = new Mock<IEventSubscriber<EventArgs>>(MockBehavior.Strict);
   6:              helper.Expect(h => h.Param = 3);
   7:              helper.Expect(h => h.SomeMethod()).Returns((string)null);
   8:   
   9:              var sut = new MyClass(helper.Object);
  10:              sut.MyEvent += subscriber.Object.Method;
  11:              sut.DoSomething(3);
  12:          }

12 lines including one empty to visually divide setup part from testing part. Nice. There’s however one BIG problem with this code: it won’t compile. As I said earlier, You can’t have assignment in Expressions, and that’s what Moq is using, so if you want to set some properties on your mock… well – you’re out of luck. I also don’t like the fact that I have to cast null, to string. This seems redundant, but it’s only a small annoyance.

Bigger problem is that I can’t explicitly state that I expect MyEvent not to be raised.

Another thing, I couldn’t find a way to get hold of event raiser. I guess it’s just not there, so if you want to test events… you’re out of luck too.

Moq is interesting project for sure, it’s simple (simplistic) syntax made me think, about how complicated Rhino.Mocks became. Sure it’s orders of magnitude more powerful, but some unification of interfaces, even for a price of breaking some old code would be highly desired. I can imagine that for a newcomer current learning curve may seem steep. Especially the fact of using static classes makes API much less discoverable.

So I will stick to Rhino.Mocks, as it Moq is still to simple for serious use, but I’m glad it’s there. It brings some fresh ideas to the table, and there’s nothing better than a little competition.

Technorati Tags: , , ,

Fighting with events: Rhino.Mocks strongly typed EventRaiser attempt #2

I just spent good few hours trying to fight awkward limitations of .NET framework in regard to generics, events, delegates and expression trees. And I’m actually not much further than when I started. It bothers me: why put artificial limitations in regard to delegates as generic constraints? I wish I could do:

public IEventManager<T1,T2> Metod<T1,T2,TEvent>(TEvent @event) where TEvent: Func<T1,T2>

(this will not compile, can not use delegates as constraints…) or even better:

public IEventManager<T1,T2> Metod<T1,T2,TEvent>(TEvent @event) where TEvent: void delegate(T1,T2)

This seems to ruin my every idea. Even worse, when I looked for help at Expression Trees, I learned that you can’t have assignments in them, so this will not compile:

public event EventHandler<CancelEventArgs> MyEvent;

 

//somewhere else

Expression<Action<EventHandler<CancelEventArgs>>> exp = x=>MyEvent+=x;

Currently I’m trying to find a way to overcome the fact, that you can’t implicitly cast delegate type to another type with same signature. If I succeed It might be possible to write something roughly similar to:

public class Client

{

    public event EventHandler<CancelEventArgs> MyEvent;

 

    private static void Main(string[] args)

    {

        var repository = new XtoffMockRepository();

        var client = new Client();

        var myEventManager =

            repository.Mock(client.MyEvent);

    }

}

 

public class XtoffMockRepository : MockRepository

{

    public IEventManager<TEvent> Mock<TEvent>(TEvent @event)

    {   ...   }

}

 

public interface IEventManager<T>

{   ...   }

This is however still quite far from what I want to accomplish. In an ideal world, IEventManager<T> would have it’s generic parameter being not TEvent (i.e. EventHandler<CancelEventArgs> in this example) but IEventManager<T1,T2>, where it’s parameters correspond to event method’ parameters (object and CancelEventArgs respectively).

[UPDATE]

As I just noticed I call repository.Mock event inside the class that declares event. This is the only place where passing it as a parameter will work, so this solution will not work either.

Technorati Tags:

Smarties – new productivity plug-in for Visual Studio

I’ve missed it, but two days ago Smarties v1.0 has been released. This is a new productivity plug-in for Visual Studio, with lots of useful refactorings, and strong emphasis on managing #regions. There are quite a few screencasts on the website, so better go and check them out for yourself. The tool is not free, but very reasonably priced, and there’s a trial version. Highly recommended.

Real Desktop

Since probably Windows 95 or even earlier (I’m not that old) Desktop did not change. There was Windows 98 and it’s active content, Linux with its 4 desktops and more recently Compiz, but they all were just  variations around basic idea: 2D space where you put some icons, some background and that would be the end of it.

Until… I saw this:

And then I installed this. It seems to be some  variation of the same idea (much limited compared to what is presented on this YouTube video) but it has one simple advantage: it’s available right now. And it’s fun.

desktop

I installed the free version, that seems to have almost all options grayed out, but it’s fun. I only miss ability to pile stuff up, and fish-eye browse (or I just didn’t discover it yet). Anyway, go check it out.

 

 

 

 

 

 

Technorati Tags: , ,

ReSharper 4.0 EAP… you said what? January?

January came and went, and much anticipated ReSharper 4.0 Early Access Program is still not available. It seems, that we’ll have to wait another two weeks, before I stop turning off ReSharper every time I want to write something using new C# 3.0 features. What bothers me however is that, although I do understand the vastness of the tool, I’m more and leaning towards agreeing with Alan’s comment on a recent post. C# is getting bigger, .NET is getting bigger, and it looks like JetBrains starts having troubles to keep up. I hope I’m wrong.

Technorati Tags: , , ,

Cheating an application

I have contact with lots of different software. However yesterday I came across an application, that completely blew my mind… in a negative sense. This particular application uses its own custom file format, that is basically zip, with special files and folders inside, much like Open XML and Open Office file formats work. What’s different however, is that it requires you to have WinZip installed in order for it to work. And by WinZip, I mean WinZip, not just some generic compressing/decompressing program that supports zip format. This thing is so ridiculous that I just don’t know what to say. ANY software that requires the user to use some other specific tool is broken by design, but requiring your users to buy other commercial tool to do such basic thing as compression/decompression… it’s just rude.

Well, anyway, as I really had no other choice but to use it, I decided not to give up and see how much it really needs actual WinZip. To do this I took invaluable tool from SysInternals (now part of Microsoft) called Process Monitor. With it you can see how processes on your system interact with each other and with the system. So I set it up, ran the evil program, made it do its thing, and then I could analyze what showed up in Process Monitor.

There were two important things to notice in the log:

  1. How the program identified WinZip’s exeprocmon1
    When you install it, you have to point it to a directory, where you have your WnZip installed. Important thing to see here, is ‘filter’ attribute in Details column. The way I understand it, it tells us, that the program was looking exactly for “winzip32.exe”. So it seemed like it doesn’t use WinZip’s libraries, nor it’s (if WinZip actually has one) automation model, but it just call winzip32.exe with command line parameters.
  2. What are command line parameters it passes to WinZip32.exe
    procmon2 Few (hundred) lines below I found out answer, when I looked at command line WinZip was actually called with: -a -x ‘path to where it wanted zip file to be saved’ ‘path to files it wants to compress’. (it called WinZip in few other places, with other commands, like when extracting files, but the general way to do this stayed the same)

It seems, that WinZip’s command line parameters are not public, but this little site, helped me with that. At this point, it looked like all this application really needs, is a executable called winzip32.exe that supports few of WinZip’s command line parameters. All I needed to do, was to find one. Unfortunately, after checking out few free compression/decompression tools I wasn’t any closer to the solution, as none of them would interpret those parameters the way WinZip does.

Then I decided to write my own using some free library. The actual code is not interesting, only interesting thing about it is that it was less than 30 LOC long and took me 15 minutes to implement (including time spent on learning the library). Now, you can look at it from two perspectives. One is, that with 30 lines of code, I saved my company quite an amount of money, it would have to spend on several WinZip licenses. The other is, makers of that tool required you to buy 3rd party tool to do something that can be done in few lines of code. I won’t comment on that…

Technorati Tags: ,

XCopy deployment of MbUnit

Yesterday I blogged about advantages and disadvantages of XCopy deployment. I didn’t say however, about one important scenario, where you may need not to use any installers in order to deploy software to a new machine, and that is, setting up project on a new developer’s machine. J.P. blogged about it a few times, so I won’t repeat his words, and get straight to the point.

One piece of software that you certainly will need is Unit Testing framework. My favorite one – MbUnit, can be however downloaded only as installable package, so you will need to perform few additional steps in order to create your own custom package.

First you have to grab the installer, from here. When you download it, don’t run it, but extract its content to a directory, with 7-zip or similar tool.MbUnit folder structure You should end up with similar folder structure. Ignore two uppermost folders: those contain installer files. You can also skip documentation files, and VSSNippets folder (which contains code snippets for Visual Studio, as its name implies), and that leaves us with .exe, .dll and .config files. Which of them you’re going to use, depends on which elements of functionality you’re going to use.

To better see interdependencies between those assemblies, I created dependency diagram with NDepend. MBUnitGraph If you take close look at it, you’ll notice that only assemblies having dependency on NGraphviz assemblies are… other NGraphviz assemblies. Same with XsdTidy, that is not used by anyone.

Now, to actually write your tests with MbUnit, you certainly are going to need

  • MbUnit.Framework.dll

and its dependencies:

  • QuickGraph.dll
  • QuickGraph.Algorithms.dll
  • Refly.dll
  • TestFu.dll

If you’re going to test non-public members you’ll also need

  • MbUnit.Framework.2.0.dll

Those are core libraries. The rest depends on how you’re going to run your tests. There are basically four options here

  • MbUnit.MSBuild.Tasks.dll, if you run tests as part of your MsBuild build
  • MbUnit.Tasks.dll, if you run tests as part of your NAnt build
  • MbUnit.Cons.exe and
  • MbUnit.Cons.exe.config, to run tests from the command line
  • MbUnit.GUI.exe and
  • MbUnit.GUI.exe.config to run tests from GUI program.

There are also TestDriven.Framework.dll and MbUnit.AddIn.dll used by TestDriven.Net to run tests from Visual Studio, but I don’t know if they will work without being actually installed (or at least put in Program Files).

Using this approach you can create package that weights around 1MB instead of over 3MB, and can be put in a self contained project directory structure.

Technorati Tags: , ,