Skip to content

Instantly share code, notes, and snippets.

@asierba
Last active August 29, 2015 14:24
Show Gist options
  • Save asierba/c06427b4b168fac22764 to your computer and use it in GitHub Desktop.
Save asierba/c06427b4b168fac22764 to your computer and use it in GitHub Desktop.
Two xunit tests to show how Automocking can be achieved with AutoFixture
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Xunit;
namespace Autofixture
{
public class Tests
{
[Fact]
public void NormalWay()
{
var dependency1stub = new Mock<IDependecy1>();
var dependency2mock = new Mock<IDependecy2>();
dependency1stub.Setup(x => x.SomeQuery()).Returns(2);
var sut = new SUT(dependency1stub.Object, dependency2mock.Object);
// dependencies coupled to object initialisation!
// If you add or remove dependencies from you SUT, you will have to change EVERY tests
Assert.Equal(4, sut.GetDoubleValue(2));
dependency2mock.Verify(x => x.SomeComand());
}
[Fact]
public void WithAutoFixture()
{
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization());
var dependency1stub = fixture.Freeze<Mock<IDependecy1>>();
var dependency2mock = fixture.Freeze<Mock<IDependecy2>>();
dependency1stub.Setup(x => x.SomeQuery()).Returns(2);
var sut = fixture.Create<SUT>();
// dependencies are not coupled to object initialisation.
// If you add or remove dependencies from you SUT, you WONT have to change tests
Assert.Equal(4, sut.GetDoubleValue(2));
dependency2mock.Verify(x => x.SomeComand());
}
}
public class SUT
{
private readonly IDependecy1 _dependecy1;
private readonly IDependecy2 _dependecy2;
public SUT(IDependecy1 dependecy1, IDependecy2 dependecy2)
{
_dependecy1 = dependecy1;
_dependecy2 = dependecy2;
}
public int GetDoubleValue(int parameter)
{
_dependecy2.SomeComand();
return _dependecy1.SomeQuery() * parameter;
}
}
public interface IDependecy1
{
int SomeQuery();
}
public interface IDependecy2
{
void SomeComand();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment