1

I have a call as such:

_session.Setup(session => session.SaveOrUpdate(It.IsAny<Foo>()))

I want to retrieve a copy of whatever instance of Foo is passed into SaveOrUpdate when the test is run for validation. How can I get a copy of that exact Foo into my test?

I tried to use .Callback, but maybe that is not the way to do this? Or maybe I'm doing it wrong... not sure, but I could use some assistance trying to figure out if this is possible and how to do this please.

Foo foo;

_session.Setup(session => session.SaveOrUpdate(It.IsAny<Foo>()))
        .Callback<Foo>(fooInstanceBeingSaved => foo = fooInstanceBeingSaved as Foo);

In this scenario, foo is always returned null, even though the real foo in the service layer is populated.

EDIT: This is not a duplicate of said duplicate because this question differs in that SaveOrUpdate returns void. In the reportedly duplicate articles, those methods return something other than void. As such, I need to get the variable out of a method where "Returns" is not a valid option - which is the solution in the other articles.

John S.
  • 1,937
  • 2
  • 18
  • 28
  • 2
    It looks OK. Are you certain that `foo` is null because the callback isn't being called? Or is it because `as` is returning `null`? Can you put a breakpoint in the callback lambda to check? – Chris Mantle Jun 17 '14 at 22:25
  • Yes, foo is coming back null. Even if I leave it as an object without any casting/"as". – John S. Jun 18 '14 at 16:39

1 Answers1

3

Channeling some psychic powers here...

It looks like you may be using NHibernate, which if so that means SaveOrUpdate has this signature:

void SaveOrUpdate(object obj);

So, in order to get your Foo object you need to specify object as the type parameter, e.g.:

_session.Setup(session => session.SaveOrUpdate(It.IsAny<object>()))
        .Callback<object>(objectBeingSaved => foo = objectBeingSaved as Foo);
Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88