How to write custom message when exception thrown like Gallio/MbUnit?

598 Views Asked by At

I am using PostSharp with Gallio/MbUnit.

I would like to be able, from a test case, to catch exceptions and write a custom message for the exceptions I catch to wherever exceptions are written. The exceptions would be caught by a PostSharp aspect. For example, I would like some function WriteToExceptionLog such that

[Serializable] 
public class MyAspect: OnExceptionAspect 
{
    public override void OnException(MethodExecutionArgs args)
    {
        WriteToExceptionLog("My custom message");
    }
}

would catch

[TestFixture]
public class MyClass
{
    [Test]
    public void MyTest()
    {
        throw new NotImplementedException();
    }
}

and the log would show "My custom message" instead of a NotImplementedException.

How would I do this? To where are exception messages written?

1

There are 1 best solutions below

0
On

You don't need to use P# to achieve that:

public class ExceptionInterceptorAttribute : TestAttribute
{
    protected override void Execute(PatternTestInstanceState state)
    {
        try
        {
            base.Execute(state);
        }
        catch (Exception e)
        {
            TestLog.Failures.WriteLine("Intercepted an exception of type: {0}", e.GetType());
        }
    }
}

public class ExceptionInterceptorTests
{
    [ExceptionInterceptor]
    public void With_interceptor()
    {
        throw new NotImplementedException();
    }

    [Test]
    public void Without_interceptor()
    {
        throw new NotImplementedException();
    }
}