A wild regex appears to save the day
Today I noticed that all Assert.Equal()
in our unit tests had inverted parameters. Meaning that we had Assert.Equal(actual, expected)
instead of having Assert.Equal(expected, actual)
. The result does not change when the test passes, but it can lead to mistakes or misunderstandings when Assert.Equal()
returns false.
Changing the order of the parameters is simple but it can be both annoying and time consuming if we have a lot of method calls.
What to do?
Since Visual Studio allows Find/Replace using regular expressions, we can do it easily. First, we will need to enable the regex mode in the Find/Replace:
Then we prepare a regex like the one below and place it on Find:
\((.*?)(, )(.*?)\);
This regex finds everything what is between the first parentheses and the semicolon, which allows you to have some method calls as parameters like expectedPerson.GetFullName()
, for example. Also, it separates the result in 3 groups - first parameter ($1
), coma and space ($2
), second parameter ($3
) - which we will have in the Replace like this:
($3, $1);
As mentioned previously, we had 3 groups. We could include the group $2
but ut it's not necessary in this case as we can "hard code" the comma and space for better understanding.
Here is how the Find/Replace is going to look like with our regex and replacements:
And here is how the selection looks in the code:
Important: Don't forget to change the Find/Replace scope to Selection in case you want to invert the parameters of a method otherwise you will have unintended consequences.
You can check this regex in the Regex101.com website if you want to play around before using it.