Skip to content

Instantly share code, notes, and snippets.

@bitsprint
Created June 20, 2013 08:25
Show Gist options
  • Select an option

  • Save bitsprint/5821126 to your computer and use it in GitHub Desktop.

Select an option

Save bitsprint/5821126 to your computer and use it in GitHub Desktop.
Test With Mocks base class (inherit from test)
namespace Core.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Moq;
public static class MoqVerifier
{
public static void VerifyAll<T>(T mockFieldContainer) where T : class
{
MocksFor(mockFieldContainer.GetType(), mockFieldContainer)
.ForEach(x =>
{
x.VerifyAll();
if (x.Behavior != MockBehavior.Strict)
{
throw new Exception("All Mocks must use MockBehavior.Strict!");
}
});
}
private static List<Mock> MocksFor<T>(Type type, T container)
{
var thisMocks = type
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.FieldType.BaseType == typeof(Mock))
.Select(x => x.GetValue(container))
.Cast<Mock>()
.ToList();
if (type.BaseType != typeof(object))
{
thisMocks.AddRange(MocksFor(type.BaseType, container));
}
return thisMocks;
}
}
}
namespace Core.Tests
{
using System;
using System.Linq.Expressions;
using Moq;
using NUnit.Framework;
[TestFixture]
public class TestWithMocks
{
[TearDown]
public void VerifyAll()
{
MoqVerifier.VerifyAll(this);
}
protected Expression<Func<T, bool>> GetAny<T>()
{
return It.IsAny<Expression<Func<T, bool>>>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment