Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to return value from another substitute #217

Closed
psmolinsky opened this issue Dec 30, 2015 · 4 comments
Closed

Unable to return value from another substitute #217

psmolinsky opened this issue Dec 30, 2015 · 4 comments

Comments

@psmolinsky
Copy link

When I configure a substitute to return a value which is obtained from another substitute, it does not work. For example:

public interface IFoo
{
   string Name { get; }
}

var foo1 = Substitute.For<IFoo>();
var foo2 = Substitute.For<IFoo>();

foo1.Name.Returns("Foobar");
foo2.Name.Returns(foo1.Name);

Console.WriteLine("Foo1: '{0}'", foo1.Name);
Console.WriteLine("Foo2: '{0}'", foo2.Name);

Output is:

Foo1: 'Foobar'
Foo2: ''

However slightly different setup works, but looks very weird:

foo1.Name.Returns("Foobar");
var name = foo1.Name;
foo2.Name.Returns(name);
@alexandrnikitin
Copy link
Member

Hi Peter. Thanks for the issue. We have a similar one with properties #56. That happens because Returns is an extension method and it applies its value to the last call. Something like this happens:

arg1 = call foo2.Name
arg2 = call foo1.Name // the last call is to foo1
call Returns(arg1, arg2)

@dtchepak
Copy link
Member

Hi @psmolinsky,

You could also try this:

foo1.Name.Returns("Foobar");
foo2.Name.Returns(x => foo1.Name);

The lambda function defers the call so the problem @alexandrnikitin mentioned doesn't occur. (This can cause other problems later; another call to foo2.Name.Returns(...) will end up setting foo1.Name I think, but often you can get away with it without problems.)

Or if the value of foo1.Name is not going to change, a clearer alternative to your second code snippet is:

var name = "Foobar";
foo1.Name.Returns(name);
foo2.Name.Returns(name);

@psmolinsky
Copy link
Author

Hi guys, thanks for suggestions and explanation. It's definitely good enough for me. Although I think it would be nice to fix it.

@dtchepak
Copy link
Member

dtchepak commented Oct 7, 2017

Closing as part of a general cleanup of issues. Please re-open if any action is required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants