Last night, as I was about to stop work to spend some time with the family, I noticed this tweet:
Image may be NSFW.
Clik here to view.
And I thought: You can do this in CodeRush. Easily. CodeRush has a remarkably flexible shortcut-binding system that can associate a sophisticated context (that must be satisfied) with any key binding. So it’s relatively simple to bind F5 to a command to run the test when the caret is inside a test method. You just need a context that tells the key-binding engine whether you’re in a test method or not.
CodeRush ships about 200 different contexts, that can do anything from tell you whether you are inside a property’s getter to whether the active project references a particular assembly. Contexts are used in shortcut bindings as well as other editor features.
After seeing the tweet, I checked to see if we already shipped a context that was satisfied when the caret was inside a test method. We did not.
This morning I noticed more discussion about this feature, including a suggestion to use another shortcut (which increases user burden and cognitive load – lots of good reasons NOT to do this), followed by this tweet from Caleb Jenkins:
Image may be NSFW.
Clik here to view.
Time to get to work.
Here’s how I built the feature, in about three minutes:
- CodeRush | New Plug-in.
- Dropped a ContextProvider control onto the design surface.
- Named it “Editor\Code\InTestMethod”.
- Double-clicked the ContextSatisfied event. Added this code:
private void ctxInTestMethod_ContextSatisfied(ContextSatisfiedEventArgs ea) { Method activeMethod = CodeRush.Source.ActiveMethod; if (activeMethod != null&& activeMethod.Attributes != null) foreach (DevExpress.CodeRush.StructuralParser.Attribute attribute in activeMethod.Attributes) if (attribute.Name != null&& attribute.Name.StartsWith("Test")) { ea.Satisfied = true; return; } }
- Pressed F5 to run (to test my plug-in).
- In the new instance of VS, added the following CodeRush shortcut binding:
Image may be NSFW.
Clik here to view.
And that’s it.
Now I can press F5 inside a test method and only that method test is run. If I press F5 outside of a test method, the startup project runs.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
