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

Access invocation arguments when using Throws/ThrowsAsync during Setup #1048

Closed
mcdevmc opened this issue Aug 16, 2020 · 1 comment
Closed
Milestone

Comments

@mcdevmc
Copy link

mcdevmc commented Aug 16, 2020

When defining the setup of a method call, I am able to access the invocation arguments when defining the return value, as shown in the sample from the QuickStart guide:

// access invocation arguments when returning a value
mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>()))
		.Returns((string s) => s.ToLower());

However, I don't seem to be able to do the same when setting up a method with Throws or ThrowsAsync, for example something like:

// unable to access invocation arguments when throwing a value (this is will not build)
mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>()))
		.Throws((string s) => new Exception($"Tried to DoSomethingStringy with {s.ToLower()}"));

// or, a case that seems particularly useful is setting properties on custom exception
mock.Setup(x => x.FindByIdAsync(It.IsAny<int>()))
		.ThrowsAsync((int id) => new IdNotFoundException(id, "Can't find the given id"));

I can work around this by using Callback to throw an exception instead:

mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>()))
		.Callback((string s) => throw new Exception($"Tried to DoSomethingStringy with {s.ToLower()}"));

but it would be much clearer and more consistent if I could use the Throws/ThrowsAsync syntax instead

@stakx
Copy link
Contributor

stakx commented Jul 29, 2021

Support for argument access has been added to Throws in #1191 (thanks again, @adam-knights!).

Regarding ThrowsAsync, let's wait with adding support there for now. That method might very well be marked obsolete (see https://github.com/moq/moq/issues/53#issuecomment-755221874), so there is no point in adding dozens of method overloads as long as we're not sure whether they'll stay around long-term.

@stakx stakx closed this as completed Jul 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants