Shortcut keys for running tests in Visual Studio
One of my most used shortcuts in Visual Studio is CTRL+R,T to debug the current test method from the code and CTRL+R,A to execute all tests. Here’s the help topic: How to: Run Selected Tests
To run tests from your test code file, by using the keyboard
1. In Visual Studio, open the source-code file that contains your test methods.
2. Click to define the testing scope: Place the cursor in a test method, in a test class, or outside the scope of a test class.
3. You can use the following keyboard shortcuts to run tests based on that scope.
CTRL + R, then press T This runs the tests in the current scope. That is, it runs the current test method, all the tests in the current test class, or all the tests in the namespace, respectively.
CTRL + R, then press C This runs all the tests in the current test class.
CTRL + R, then press N This runs all tests in the current namespace.
To run tests from source code files in your solution, by using the keyboard
1. In Visual Studio, open a source code file anywhere in your solution.
2. You can use the following keyboard shortcuts to run tests from that file.
Ctrl + R, then press A Runs all the tests in all test projects.
Ctrl + R, then press D Runs all tests that were run in the last test run.
Ctrl + R, then press F Runs all tests in the last test run that did not pass.
How to isolate Directory.Exists in unit testing using disposable pattern
Earlier i wrote a blog post about isolating DateTime.Now with disposable pattern. Here is a little more advance example for the static method Directory.Exists.
So here is the simple example of product code that we want to test
public void ProcessFiles(string path) { if (!DirectoryIsolator.Exists(path)) { throw new ArgumentException("Path doesn't exist"); } } |
This first test method is simple setting the return value to false before calling the product code
[TestMethod()] [ExpectedException(typeof(ArgumentException))] public void Class1_ProcessFiles_SettingReturnValueFalse() { using (DirectoryIsolator.ExistsIs(false)) { Class1 target = new Class1(); string path = @"C:\windows"; target.ProcessFiles(path); } } |
How to isolate DateTime.Now in unit testing
When writing unit tests for codes that is using DateTime.Now you will find yourself in a situation where you can’t automate functionality that are dependent on the time since the time is changing constantly. You are also not able to test for example that your codes work correctly for leap year or change of year, etc.
How would you test correctness of bellow simple example?
public bool IsIt2012 { get { return (DatemTime.Now.Year == 2012); } } |
The solution is to introduce a “wrapper” for DateTime.
public bool IsIt2012 { get { return (DatemTimeIsolator.Now.Year == 2012); } } |