Saturday, 7 September 2013

How to do mocking with Moq without exposing interfaces to users?

How to do mocking with Moq without exposing interfaces to users?

Let's say I have a class like this:
public class Context {
public void initialize() { ... }
}
and another class using it:
public class Service {
public Context getContext() { return context; }
internal Service(Context ctx) {
context = ctx;
context.initialize();
}
private Context context;
}
Finally, let say I want to write a unit test for Service that verifies
that Context.initalize is called upon class construction. Since it's a
unit test, I would want to mock Context instead of using a real class.
With Moq that requires creating an interface IContext and rewriting the
code as following:
public interface IContext {
void initialize();
}
public class Context : IContext {
public void initialize() { ... }
}
public class Service {
public IContext getContext() { return context; }
internal Service(IContext ctx) {
context = ctx;
context.initialize();
}
private IContext context;
}
[TestFixture()]
public class ServiceTest {
[Test()]
public shouldInitializeContextWhenConstructed() {
Mock<IContext> mockContext = new Mock<IContext>();
Service service = new Service(mockContext);
mockContext.Verify(c => c.initialize(), Times.Once());
}
}
However, since IContext is purely test-related artifact, I would like to
avoid exposing it to the users of the Service class (via
Service.getContext function). What would be the correct solution here?

No comments:

Post a Comment