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

NUnit2044 - improvement proposal - consider variables assigned outside of Assert call #762

Open
matode opened this issue Jun 14, 2024 · 3 comments

Comments

@matode
Copy link
Contributor

matode commented Jun 14, 2024

If you have code like this:

var actualValue = Foo.GetValue();
Assert.That(actualValue, Is.EqualTo(expectedValue).After(Timeout, PollInterval), "Error message");

Changing to

var actualValue = Foo.GetValue();
Assert.That(() => actualValue, Is.EqualTo(expectedValue).After(Timeout, PollInterval), "Error message");

seems to be useless. The variable actualValue will be set only once before the Assert.That call.

It should be e.g.

Assert.That(() => Foo.GetValue(), Is.EqualTo(expectedValue).After(Timeout, PollInterval), "Error message");

Can the analyzer be enhanced, so that it does not accept variables as actualValue param in the Assert call? And can the fixer be adapted accordingly?

@manfred-brands
Copy link
Member

I agree that creating a delegate for a variable doesn't make sense. It would make more sense to remove the After modifier if we can't move the assignment inside the Assert.

@matode
Copy link
Contributor Author

matode commented Jun 14, 2024

In most cases After is used for some reason. So removing it is not an option.

If moving the assignment inside Assert is too complicated, it can be proposed to move the assignment into some (local) function.

@manfred-brands
Copy link
Member

Actually, I have seen use cases where it does make sense:

bool wasCalled = false;
void Handler() => wasCalled = true;
instance.Event += Handler;
Assert.That(() => wasCalled, Is.EqualTo(expectedValue).After(Timeout, PollInterval), "Event wasn't called");

Finding the scope of what could modify the local variable is outside the scope of the analyzer.

I'm inclined to close this issue.

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

2 participants