1

I want to verify that the method I test calls a service multiple times with different arguments. The service method has a required and a optional argument:

public void Foo(object o1, object[] o2 = null);

I am expecting Foo to get called 2 times, once without and once with the optional parameter. The optional parameter should match a criteria. To test this I am using MustHaveHappenedOnceExactly from FakeItEasy:

A.CallTo(() => testee.Method(A<object>.That.IsNotNull(), A<object[]>.That.IsNull()))
.MustHaveHappenedOnceExactly().Then(
A.CallTo(() => testee.Method(A<object>.That.IsNotNull(), A<object[]>.That.Matches(p => p.Length == 2)))
.MustHaveHappenedOnceExactly());

What I do get is the following exception:

FakeItEasy.UserCallbackException: Argument matcher <p => (p.Length> == 2)> threw an exception. See inner exception for details. ---> System.NullReferenceException: Object reference not set to an instance of an object.

I assume that MustHaveHappenedOnceExactly checks all calls on Foo with the defined matches and thereby the second match throws an exception when Foo is called without Parameter. How can I avoid that exception and still test that Foo got called once with a specific argument?

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
user2900970
  • 751
  • 1
  • 5
  • 24

1 Answers1

1

Refactor the matcher to cater for the null i.e. .Matches(p => p != null && p.Length == 2)

A.CallTo(() => testee.Method(
                    A<object>.That.IsNotNull(),
                    A<object[]>.That.IsNull()
                )
).MustHaveHappenedOnceExactly()
.Then(A.CallTo(() => testee.Method(
                        A<object>.That.IsNotNull(), 
                        A<object[]>.That.Matches(p => p != null && p.Length == 2) //<--
                    )
              ).MustHaveHappenedOnceExactly()
);
Nkosi
  • 235,767
  • 35
  • 427
  • 472