0

enter code hereI have a method that logs errors when an exception is thrown within that method. The method is non-static inside a singleton.

    public object MethodA()
    {
        try
        {
            //code
                             SomeObj.Print(); //updated
        }
        catch (Exception ex)
        {
            log.Error(ex);
        }
    }

The unit test code below throws NullreferenceException:

                    var fakeLogger = A.Fake<ILog>();

        MySingleton.Instance.Initialize(fakeLogger);

        A.CallTo(() => MySingleton.Instance.MethodA()
            .Invokes((x) => { throw new Exception(); });
               //.Throws(new Exception()); --even this doesnt work
        A.CallTo(() => fakeLogger.Error(A<object>.Ignored)).MustHaveHappened();


Stack trace:
at FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyInterceptionValidator.GetReasonForWhyMethodCanNotBeIntercepted(MethodInfo method)
at FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyInterceptionValidator.MethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget, String& failReason)
at FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.MethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget, String& failReason)
at FakeItEasy.Creation.ProxyGeneratorSelector.MethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget, String& failReason)
at FakeItEasy.Configuration.DefaultInterceptionAsserter.AssertThatMethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget)
at FakeItEasy.Configuration.FakeConfigurationManager.AssertThatMemberCanBeIntercepted(LambdaExpression callSpecification)
at FakeItEasy.Configuration.FakeConfigurationManager.CallTo(Expression`1 callSpecification)
at FakeItEasy.A.CallTo(Expression`1 callSpecification)

Solution: I had to make my non-fake method throw an exception and this is how I did.

var fakeLogger = A.Fake<ILog>();
var someObject = A.Fake<SomeObject>();
MySingleton.Instance.Initialize(fakeLogger);
A.CallTo(() => someObject.Print()).Throws(new Exception()); //key
MySingleton.Instance.MethodA();
A.CallTo(() => fakeLogger.Error(A<object>.Ignored)).MustHaveHappened();
Chuck Conway
  • 16,287
  • 11
  • 58
  • 101
Tech Xie
  • 927
  • 4
  • 12
  • 24

2 Answers2

3

MySingleton.Instance doesn't point to your fake, you have faked an ILog, not a MySingleton, you can only configure methods on your fake.

For example:

A.CallTo(() => fakeLogger.MethodA()).Throws(new Exception());

You have to figure out some other way to raise an exception inside your try catch-block.

Patrik Hägne
  • 16,751
  • 5
  • 52
  • 60
2

Try this:

A.CallTo(() => MySingleton.Instance.MethodA()).Throws(new Exception());
MySingleton.Instance.MethodA();
A.CallTo(() => fakeLogger.Error(A<object>.Ignored)).MustHaveHappened();
Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212