Skip to content

Instantly share code, notes, and snippets.

@blair55
Created October 10, 2012 21:25
Show Gist options
  • Save blair55/3868513 to your computer and use it in GitHub Desktop.
Save blair55/3868513 to your computer and use it in GitHub Desktop.
AutoMocking with StructureMap and Moq in BDD Cucumber Style
public abstract class GivenA<T> where T : class
{
private MoqAutoMocker<T> _autoMocker = new MoqAutoMocker<T>();
protected T Target { get; private set; }
[SetUp]
public void Setup()
{
Given();
When();
}
protected virtual void Given()
{
Target = _autoMocker.ClassUnderTest;
}
protected virtual void When()
{}
protected Mock<TT> GetMock<TT>() where TT : class
{
return Mock.Get(_autoMocker.Get<TT>());
}
protected void Verify<TT>(Expression<Action<TT>> verify) where TT : class
{
Mock.Get(_autoMocker.Get<TT>()).Verify(verify);
}
}
public class ThenAttribute : TestAttribute
{}
public class TaskRunner
{
private IContextProvider _contextProvider;
private ITask _task;
public TaskRunner(IContextProvider contextProvider, ITask task)
{
_contextProvider = contextProvider;
_task = task;
}
public void RunTaskWithContext()
{
var context = _contextProvider.GetContext();
_task.Run(context);
}
}
public interface IContextProvider
{
string GetContext();
}
public interface ITask
{
void Run(string context);
}
public class WhenIRunTaskWithContext : GivenA<TaskRunner>
{
private string _context = "context code";
public override Given()
{
base.Given();
GetMock<IContextProvider>().Setup(m => m.GetContext()).Returns(_context);
}
public override void When()
{
Target.RunTaskWithContext();
}
[Then]
public void TheContextIsFetched()
{
Verify<IContextProvider>(m => m.GetContext());
}
[Then]
public void TheTaskIsRunWithContext()
{
Verify<ITask>(m => m.Run(_context));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment