views:

46

answers:

2

I am creating a mock for my ITransformer interface.

public interface ITransformer
{
    String Transform( String input );
}

I can create a mock that returns an given string based on a specific input:

var mock = new Mock<ITransformer>();
mock.Setup(s => s.Transform("foo")).Returns("bar");

What I would like to do is create a mock with a Transform() method that echoes whatever is passed to it. How would I go about doing this? Is it even possible?

I realise my question might be subverting the way that Moq and mocks in general are supposed to work because I'm not specifying a fixed expectation.

I also know that I could easily create my own class to do this, but I was hoping to find a generic approach that I could use in similar circumstances without having to define a new class each time.

+3  A: 
var mock = new Mock<ITransformer>();
m.Setup(i => i.Transform(It.IsAny<string>())).Returns<string>((string s) => { return s;});
klausbyskov
Your edit makes no sense - `string` is an alias for `System.String`
Ruben Bartelink
Thank you for pointing that out.
klausbyskov
+1  A: 
var mock = new Mock<ITransformer>();
mock.Setup(t => t.Transform(It.IsAny<string>())).Returns((String s) => s);

This should echo back whatever was supplied to the method.

Rob Levine
Although all answers were helpful, this is the clearest.
ctford