Skip to content

Instantly share code, notes, and snippets.

@hjerpbakk
Last active December 16, 2015 06:19
Show Gist options
  • Save hjerpbakk/5390525 to your computer and use it in GitHub Desktop.
Save hjerpbakk/5390525 to your computer and use it in GitHub Desktop.
Example showing how to mock a method from an interface using Moq. From http://hjerpbakk.com/blog/2013/4/15/moq-mock-a-method-from-an-interface.html
public class MyClass {
private readonly ComplexClass complexClass;
public MyClass(ComplexClass complexClass) {
this.complexClass = complexClass;
}
public void Verify() {
((IVerifiable)complexClass).Verify();
}
// Imagine many more uninteresting methods...
public void Uninteresting1() {
}
}
public class ComplexClass : IVerifiable {
public object NeededProperty { get; set; }
// Verifies the state of the object
public void Verify() {
if(NeededProperty == null) {
// Don't use this exception message in production :)
throw new InvalidOperationException("Method is invalid for the current state of the object");
}
}
// Imagine many more uninteresting methods...
public void Uninteresting2() {
}
}
public interface IVerifiable {
void Verify();
}
[TestClass]
public class MyClassTests {
[TestMethod]
public void Verify_ComplexObjectIsValid_ShouldNotThrowException() {
var complexClass = new ComplexClass();
var myClass = new MyClass(complexClass);
myClass.Verify();
// Test fails with exception :( Must be replaced with a working test.
}
[TestMethod]
public void Verify_ComplexObjectIsValid_ShouldReallyNotThrowException() {
var complexClassFake = new Mock<ComplexClass>();
var verifiable = complexClassFake.As<IVerifiable>();
verifiable.Setup(v => v.Verify()).Verifiable();
var myClass = new MyClass(complexClassFake.Object);
myClass.Verify();
verifiable.Verify();
// Test works as expected :)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment