0

I would like to check a property of a structure passed to a faked interface:

JobSpec passedJobSpec = null;
A.CallTo(() => fakeInvoker.Create(A<JobSpec>._))
            .Invokes((JobSpec jobSpec) => passedJobSpec = jobSpec);
Assert.NotNull(passedJobSpec.Property1);

But I get a NullReferenceException on accessing passedJobSpec.Property1. I tried a few other variations but no luck so far. Appreciate if someone could help.

hagh
  • 507
  • 5
  • 13

2 Answers2

2

A.CallTo will mock the behaviour for fakeInvoker.Create, but a call to fakeInvoker.Create still needs to be made.

Given that we have the following definitions below:

public interface IInvoker
{
    void Create(JobSpec jobSpec);
}

public class JobSpec
{
    public string Property1 { get; set; }
}

Our test case would look something like:

var fakeInvoker = A.Fake<IInvoker>();
JobSpec passedJobSpec = null;
A.CallTo(() => fakeInvoker.Create(A<JobSpec>._))
    .Invokes((JobSpec jobSpec) => passedJobSpec = jobSpec);

// Make this call to fire off the behaviour
fakeInvoker.Create(new JobSpec{Property1 = "Hello world"});

Assert.NotNull(passedJobSpec.Property1);
Hayden
  • 2,902
  • 2
  • 15
  • 29
  • I had that call as part of the logic I was testing, but I realized my test doesn't get there because of a minor test setup issue somewhere else. So, yes, this works. Thanks. – hagh Aug 07 '21 at 03:37
0

Some other good examples are provided here: https://www.alexjamesbrown.com/blog/development/asserting-multiple-properties-argument-fakeiteasy/

var fakeInvoker = A.Fake<IInvoker>();
JobSpec passedJobSpec = null;
    .Invokes(p => passedJobSpec = p.GetArgument<JobSpec>(0));

This is especially useful when the interface has multiple arguments.

hagh
  • 507
  • 5
  • 13