Skip to content

Instantly share code, notes, and snippets.

@jeffdeville
Created July 20, 2010 15:18
Show Gist options
  • Save jeffdeville/483086 to your computer and use it in GitHub Desktop.
Save jeffdeville/483086 to your computer and use it in GitHub Desktop.
YB BDD context
[TestFixture]
public abstract class Context
{
private Exception exception;
protected MockFactory factory;
protected AutoMockContainer container;
[TestFixtureSetUp]
public void initialize()
{
exception = null;
factory = new MockFactory(MockBehavior.Loose);
container = new AutoMockContainer(factory);
setupContext();
try
{
act();
}
catch (Exception e)
{
exception = e;
if (ShouldRethrowException(e.GetType()))
{
throw;
}
}
}
public Exception CaughtException
{
get { return exception; }
}
public abstract void setupContext();
public abstract void act();
private bool ShouldRethrowException(Type exceptionType)
{
ContextExpectedExceptionAttribute attribute = GetExpectedExceptionAttribute();
if (attribute == null)
{
return true;
}
if (attribute.ExceptionType != null && attribute.ExceptionType != exceptionType)
{
return true;
}
return false;
}
private ContextExpectedExceptionAttribute GetExpectedExceptionAttribute()
{
System.Reflection.MemberInfo info = this.GetType();
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i] is ContextExpectedExceptionAttribute)
{
return (ContextExpectedExceptionAttribute)attributes[i];
}
}
return null;
}
}
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public sealed class ContextExpectedExceptionAttribute : Attribute {
public ContextExpectedExceptionAttribute(Type exceptionType)
{
ExceptionType = exceptionType;
}
public Type ExceptionType { get; set; }
}
public abstract class ControllerContext<CONTROLLER, RESULT, DTO> : Context
where CONTROLLER : Controller
where RESULT : ActionResult
{
private CONTROLLER _sut;
public CONTROLLER sut
{
get
{
return _sut = _sut ?? container.Create<CONTROLLER>();
}
}
public RESULT Result { get; set; }
public DTO Dto { get; set; }
public Guid Id { get; set; }
public string UserId { get; set; }
public Mock<T> GetMock<T>() where T : class
{
return container.GetMock<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment