söndag 19 maj 2019

One way to handle DateTime.Now when unit testing C# code

Hide DateTime.Now behind ITimeProvider?

To make code unit testable there is often a need to break dependencies between classes. This is normally done by hiding concrete implementations behind interfaces and injecting those interfaces  into the class that you want to test.

What if your code is dependent on the static DateTime.Now? Should you hide that behind an interface called ITimeProvider and suddenly have to pass that interface around?

In his book "The Art of Unit Testing", Roy Osherove suggests that you don't and that you use a solution like this class instead:

 public class SystemTime  
 {  
   private static DateTime? _date;  
   
   public static void Set(DateTime custom)  
     => _date = custom; 
   
   public static void Reset()  
     => _date = null;  
   
   public static DateTime Now  
     => _date ?? DateTime.Now;  
 }  

If you create such a class, then you can replace all the calls to DateTime.Now in your code to SystemTime.Now.

And in your unit tests you can use SystemTime.Set() to set what date should be returned from SystemTime.Now. After each test run, make sure to call SystemTime.Reset(). That call is preferably put in a teardown method, like [TestCleanup] if you're using MSTest or [TearDown] in NUnit.



fredag 10 maj 2019

Convert breakpoints to tracepoints when debugging multi-threaded apps in Visual Studio

Breaking the code execution on a breakpoint when debugging a multi-threaded application might change the execution flow of the different threads so much that you get a totally different scenario than you will have in production.

This problem can be remedied by converting breakpoints to tracepoints. A tracepoint can write text to the Output window and continue execution without stopping.

Set a tracepoint by first setting a breakpoint, right click it and select "Actions".

The message to be logged can contain predefined variables like
$CALLER - Name of the function calling the current function
$FUNCTION - Name of the current function
$TID - ID of the current thread

You can also get the value of a variable by using curly braces, like this: {variable_name}

When a breakpoint has been changed to a tracepoint the red bullet is changed to a diamond.



One call to the method in the image above results in this text being logged:

In MineSweeper.Program.TryParseDirection(string, out MineSweeper.Direction), called with directionStr = "S"