Visual Studio/Resharper: Changing the order of arguments
We've recently run into some places in our tests where the expectation and actual values passed into NUnit's 'Assert.AreEqual' are the wrong way round, therefore meaning that the error messages we get when tests fail are somewhat confusing!
Assert.AreEqual(theActualValue, "the expectation");
We can change the arguments around using Resharper by using the key combination 'Ctrl-Alt-Shift-ArrowKey' but you can only do this one line at a time which was a bit annoying as there were about 20 to change.
I got a bit bored of doing this after a while so I thought I'd look into whether it would be possible to do this with a 'Find & Replace'.
After a bit of trial and error this is what I've ended up with:
- Select all the areas of code that you want to change and press 'Ctrl-H'
-
In the find box type:
\({.*}, {\".*\"} -
And in the replace box type:
(\2, \1
The '{}' define a matching group of which we define two in this case and then switch them around. Visual Studio's regex seems a bit different than the one I'm used to – the reference list for the syntax is available on MSDN.
It's not too complicated and I'm sure there are edge cases where it wouldn't work but for the little case I had it did the job reasonably well.
This will change the order of all parameters where the second one is a quoted string. Be careful when using replace all.
For example, it will also change the order of:
DoSomething("parameter 1″, "parameter 2″, "parameter 3″);
Andy Palmer
23 Jun 09 at 8:24 pm
Yeh good point!
I was only applying it to places which had 2 arguments and in all the cases the second argument was a string so for that case it worked out ok.
I'm sure it could be tightened up to make sure it doesn't change stuff it's not meant to – I'm never sure with regular expressions how much time should be spent making it deal with unusual cases as compared to just ensuring you only use it on strings which you know are of a certain format/style.
Mark Needham
23 Jun 09 at 8:31 pm
Oh, and it would also change this:
DoSomething(param1, param2, "Do something") to
DoSomething("Do something", param1, param2)
Does:
\({:a+}, {:q}
do what you need?
Andy Palmer
23 Jun 09 at 8:31 pm
Nice, didn't know about 'Ctrl-Alt-Shift-ArrowKey.
How about:
1. Write method TempAssert(actual, expected)
2. Replace all Assert.AreEqual with TempAssert
3. Swap TempAssert's parameters
4. Replace all TempAssert with Assert.AreEqual (or use my new friend, Inline Method)
Tim Robinson
24 Jun 09 at 8:12 am
What I tend to do these days is use the NUnit.Framework.SyntaxHelpers to make the asserts easier to read and to avoid the issue you refer too.
Assert.AreEqual(theActualValue, "the expectation");
Becomes:
Assert.That(theActualValue, Is.EqualTo("the expectation"));
Josh
24 Jun 09 at 10:17 am
That last bit from Josh looks a bit HamBreadish?
DCam
26 Jun 09 at 6:53 pm