moq icon indicating copy to clipboard operation
moq copied to clipboard

rethrow exceptions from callback

Open DmitryBryluk opened this issue 8 years ago • 8 comments

suppose we have complex object which have as a parameter some action object. action usually executes with no exception, but when it throws, complex object handles the exception itself without passing out, "eats the exception". so, if we have some test assertions in action mock, exceptions from these assertions are eaten too, and test is passed with no error.

is there an option to rethrow any exception from callback into caller function, or may be some reference closure during setup, which may execute callback inside caller? (btw closure is not always desirable, since some actions should really happen for complex object caller)

public TestClass()
{
    this.actionObjectMock = new Mock<ActionObject>();
    this.complexObject = new ComplexObject(this.actionObjectMock.Object);
}

[Fact]
public void TestComplexAction()
{
    Action callbackClosure = null;

    this.actionObjectMock
        .Setup(x => x.SimpleAction(It.IsAny<SomeArgs>()))
        .Callback((SomeArgs someArgs) =>
        {
            // this exception is never seen by tests
            // since it is "eaten" inside ComplexObject.ComplexAction()
            AssertArgumentsCorrect(someArgs);
            // workaround: make a closure and call from caller func
            callbackClosure = () =>
            {
                AssertArgumentsCorrect(someArgs);
            };
        })
        .Returns(someResponse);

    // it would be nice here to have an exception from assert
    var result = this.complexObject.ComplexAction(someRequest);

    // execute internals of callback here to get any exceptions
    callbackClosure();
}

also there is possible workaround with mocking exception logger, but it is not always desirable, because logging is not always awailable and may change without notification.

DmitryBryluk avatar Sep 06 '18 12:09 DmitryBryluk

// this exception is never seen by tests
// since it is "eaten" inside ComplexObject.ComplexAction()

is there an option to rethrow any exception from callback into caller function [...]?

No, not if there's something in-between that swallows all exceptions. That's one reason why unconditionally swallowing exceptions (even when you cannot actually handle them) is a pretty bad idea.

But you can catch the exception inside the callback, store it in a captured variable, and check that variable outside of your setup and re-throw the exception there.

stakx avatar Sep 06 '18 12:09 stakx

That's one reason why unconditionally swallowing exceptions (even when you cannot actually handle them) is a pretty bad idea.

imagine we can't manage ComplexObject in example, or this behaviour is desired: it parses exception and wraps into response message (and we can't override its return value).

But you can catch the exception inside the callback, store it in a captured variable, and check that variable outside of your setup and re-throw the exception there.

it could be a nice feature, just additional param instead of extra code, how to make feature request?

DmitryBryluk avatar Sep 06 '18 12:09 DmitryBryluk

it could be a nice feature

To be honest, I think that's outside the scope of Moq. Moq is concerned with mocking, not so much with helping people to "unswallow" exceptions. :-)

I don't think a mechanism along the lines of, "record all exceptions thrown during invocations, and re-throw them when I call mock.RethrowExceptions()" would be generally useful.

That's just my 2 cents, though.

stakx avatar Sep 06 '18 12:09 stakx

I thought Moq is concerned with testing ;)

record all exceptions thrown during invocations, and re-throw them when I call mock.RethrowExceptions()

rethrow just first exception, or give out a closure from setup

I don't think a mechanism along the lines of, "..." would be generally useful.

I have dozens of tests with these issue in several projects, like https://github.com/DigDes/SoapCore/blob/master/src/SoapCore.Tests/Serialization/XmlSerializationTests.cs

DmitryBryluk avatar Sep 06 '18 12:09 DmitryBryluk

You could easily factor that into a helper extension method of yours too

--

On Thu, Sep 6, 2018, 9:50 AM DmitryBryluk [email protected] wrote:

I thought Moq is concerned with testing ;)

record all exceptions thrown during invocations, and re-throw them when I call mock.RethrowExceptions()

rethrow just first exception, or give out a closure from setup

I don't think a mechanism along the lines of, "..." would be generally useful.

I have dozens of tests with these issue in several projects, like https://github.com/DigDes/SoapCore/blob/master/src/SoapCore.Tests/Serialization/XmlSerializationTests.cs

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/moq/moq4/issues/685#issuecomment-419080735, or mute the thread https://github.com/notifications/unsubscribe-auth/AAKW62MJRVLrOjQZ_lOrzyJ8ZVxRrmm0ks5uYRn7gaJpZM4Wc0BS .

--

-- /kzu from mobile

kzu avatar Sep 06 '18 21:09 kzu

One way (and perhaps the only one) that I can see this being useful in a more general manner than the scenario shown here would be if mocks logged all exceptions that get thrown during invocations, similar to how mocks already record all invocations. Thrown exceptions could then be queried at any later time through some mock.ThrownExceptions collection.

However, I believe the cost of implementing and maintaining such a feature, as well as the added runtime cost (mainly reduced runtime performance, since updating a thread-safe collection doesn't come for free), together with the fact that most folks will probably hardly (if ever) need this, brings me to the conclusion that we should not include this feature in the core library.

stakx avatar Sep 06 '18 21:09 stakx

ok, thanks. here is a little helper class to deal with this, may be someone will suggest better approach

using System;
using Shouldly;

namespace Tests.Helpers
{
    /// <summary>
    /// since assert exceptions may be eaten inside caller object
    /// and invisible by tests, we have to make closure in mock callback
    /// to execute this closure later in caller function,
    /// so the all exceptions will be visible by tests.
    /// </summary>
    public class CallbackClosure : IDisposable
    {
        private Action action;

        public void Init(Action action)
        {
            this.action.ShouldBeNull("action is already initialized");
            this.action = action;
        }

        public void Dispose()
        {
            this.action.ShouldNotBeNull("action should be initialized");
            this.action();
        }
    }
}

use it as (from example in first post):

public TestClass()
{
    this.actionObjectMock = new Mock<ActionObject>();
    this.complexObject = new ComplexObject(this.actionObjectMock.Object);
}

[Fact]
public void TestComplexAction()
{
    using (var callbackClosure = new CallbackClosure())
    {
        this.actionObjectMock
            .Setup(x => x.SimpleAction(It.IsAny<SomeArgs>()))
            .Callback((SomeArgs someArgs) =>
            {
                // actions that can't be placed into closure (and exceptions are swallowed)
                // ...
                callbackClosure.Init(() =>
                {
                    // actions that can be placed into closure and expose exceptions
                    AssertArgumentsCorrect(someArgs);
                });
            })
            .Returns(someResponse);

        var result = this.complexObject.ComplexAction(someRequest);
    }
    // closure will be called at Dispose, so we will never forget to call it
}

one more helper class:

using System;
using System.Runtime.ExceptionServices;

namespace Tests.Helpers
{
    /// <summary>
    /// convenient way to record and rethrow exceptions.
    /// it executes action immediately and records exception,
    /// so it is safe to modify variables after closure created.
    /// use it as:
    /// callbackClosure.Init(ExceptionRethrower.Create(() => { action }));
    /// or:
    /// ExceptionRethrower.Create(callbackClosure, () => { action }));
    /// </summary>
    public class ExceptionRethrower
    {
        private readonly ExceptionDispatchInfo capturedException;

        public ExceptionRethrower(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                // capture exception to rethrow with original stack trace
                this.capturedException = ExceptionDispatchInfo.Capture(ex);
            }
        }

        public void Rethrow()
            => this.capturedException?.Throw();

        public static Action Create(Action action)
            => new ExceptionRethrower(action).Rethrow;

        public static void Create(CallbackClosure callbackClosure, Action action)
            => callbackClosure.Init(Create(action));
    }
}

DmitryBryluk avatar Sep 07 '18 08:09 DmitryBryluk

@DmitryBryluk - I am going to close this. Please post again if there's anything else.

stakx avatar Sep 07 '18 09:09 stakx