views:

77

answers:

1

How would I go about mocking an Image with Moq?

It has no constructors (is always generated from factory methods).

Basically I want to do something like this...

var image = new Mock<Image>();
image.Setup(i=>i.Save(someStream,ImageFormat.Jpeg);
var testableObject = new ObjectUnderTest(image.Object);

testableObject.MethodBeingTested();

image.VerifyAll();
+2  A: 

Answered a similar question yesterday, you may wish to take a look at this thread on mocking a static Singleton.

If it's absolutely necessary to mock this behaviour, then the proscribed method is to generate an interface exposing the methods you need, implement it with a concrete class [effectively wrapping Image class] for prod, and Mock the interface for test.

It does sound overkill, but if you need to Mock\verify the interactions between your testable class and Image, that's the way to do it. Alternatively, you can just pass your testable class an actual instance of Image and then compare this instance against an expected output [standard unit test methodology]

johnny g
Thanks for that, your original answer was very helpful. It does seem a little dirty to create an interface and decorator just so you can test it (especially for a framework class). Testing the output would be messy in my case since it would be validating the contents of a stream have the right byes (tedious)
Chris Meek
I think an important question to ask when testing is "What exactly am I testing?". Without knowing more about your problem, I would hazard a guess that you are testing some sort of image manipulation. Strictly speaking, this manipulation should be tested independently of Image, say as a byte stream test or something. Testing a "System" class is usually considered overkill - much like testing WebServices, and I've seen plenty of that too. One may assume CLR is "safe".You want to separate business logic [ie whatever is happening to your Image] from the System class [ie Image].
johnny g