Monday, October 15, 2018

A ghetto way to unit test async void methods in C#!

Well, maybe something is "coming back" in the form of an Action which gets handed in the method signature. Maybe this Action updates the UI. I've written lots of things like that and I am doing more of it lately, so how can I test it? I can make the Action set a variable that exists in my unit test, but when I go to make an Assert against that variable it's not going to be set as I expect because everything I want to test is happening on a different thread at a different time. What can I do? Upstream of the assert I could have something like so:

Thread.Sleep(1000);

 
 

This should let us hang out until the other thread is finished, but this is also pretty ghetto. It might be better to call out to something like so to do the same thing less thuggishly.

using System;
namespace MyStuff.Code.Tests.Utilities
{
   public static class Wait
   {
      public static void OneSecond()
      {
         DateTime aSecondAgo = DateTime.Now;
         while (aSecondAgo.AddMilliseconds(1000) > DateTime.Now) { }
      }
   }
}

No comments:

Post a Comment