Trevor
Trevor

Reputation: 4860

Can I create a mock that conforms to an interface and is also aware of methods on its base class?

I'm using Moq to test a presenter in a WinForms app. The presenter has a view. The view conforms to ISomeControl, and inherits from UserControl

In testing this presenter, I want to test that the Show() method on the View was called.

So I create a mock like this:

var someControl = new Mock<ISomeControl>();

But here's the problem: In my application, there's a place where I cast the ISomeControl to a Control so that I can call the base class Show(). And because the Mock only knows it's an ISomeControl, I get the following error:

Unable to cast object of type 'Castle.Proxies.ObjectProxy_1' to type 'System.Windows.Forms.Control'.

Is there a way around this?

Upvotes: 1

Views: 284

Answers (2)

David Culp
David Culp

Reputation: 5480

A mock can be made to implement multiple interfaces

A snippet from the Moq Quick Start shows how to do this:

// implementing multiple interfaces in mock
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
// now the IFoo mock also implements IDisposable :)
disposableFoo.Setup(df => df.Dispose());

//implementing multiple interfaces in single mock
var foo = new Mock<IFoo>();
foo.Setup(f => f.Bar()).Returns("Hello World");
foo.As<IDisposable>().Setup(df => df.Dispose());

Upvotes: 1

Nkosi
Nkosi

Reputation: 247108

Create a base abstract class that inherits both ISomeControl and UserControl for the purpose of mocking in the unit test.

public abstract class SomeDummyControl : UserControl, ISomeControl { 
    //...
}

This should allow for the mock to be aware of both types.

var mock = new Mock<SomeDummyControl>();
//...arrange setup

var dummyControl = mock.Object;
//...pass the dummy as a dependency

//just to show that it should be able to cast
var control = dummyControl as Control;
var someControl = dummyControl as ISomeControl;

The mock can be verified like this when needed

mock.Verify(m => m.Show(), Times.AtLeastOnce()); //verifies that the Show method was called.

Read up more on Moq here Moq Quickstart

Upvotes: 2

Related Questions