Archive for the ‘UnitTest’ Category.

.Net Core, run async methods in a loop

Here is a Unittest running async method which needs to show how async can benefit when long running methods are run. It should complete in about same amount of seconds as the longest delay that was set randomly during the execution of the test.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using System.Diagnostics;

namespace Some.test
{
  public class TestAsyncTasks
  {
    // Randomizer
    Random _rnd = new Random();

    [Fact]
    /// <summary>
    /// Run fake tasks with random delay async
    /// </summary>
    public async Task RunRandomTasksAsync()
    {
      var series = Enumerable.Range(1, 5).ToList();
      var tasks = new List<Task<Tuple<int, bool>>>();
      foreach (var i in series)
      {
        Debug.WriteLine(“Starting Process=” + i);
        tasks.Add(DoWorkAsync(i));
      }

      // Loop to process the tasks one at a time until none remain
      while (tasks.Count > 0)
      {
        // Get the first task that completes
        var thetask = await Task.WhenAny(tasks);

        // Remove the selected task from the list only process it more than once.
        tasks.Remove(thetask);

        // Await the completed task
        Tuple<int, bool> tupl = await thetask;
        Debug.WriteLine(“Process=” + tupl.Item1 + ” ended”);
      }
    }

    /// <summary>
    /// Complete a fake task using random delay
    /// </summary>
    public async Task<Tuple<int, bool>> DoWorkAsync(int i)
    {
      int delay = _rnd.Next(25);
      Debug.WriteLine(“working.. process=” + i + “, delay=” + delay);
      await Task.Delay(1000 * delay);
      return Tuple.Create(i, true);
    }
  }
}

UnitTest MsSql database using Slacker, SlackerRunner

Our open source MsSql UnitTest framework Slacker and SlackerRunner was featured on Microsoft Channel 9. Now it’s easier than ever to UnitTest your database and add it into your CI,CD build pipeline.

Watch Eric Kang from Microsoft explain in detail what you need and how it works.

TFS 2015, Xunit transform to Trx

It turns out I was wrong in my last post about transforming nUnit tests to Trx ( Ms Test ) format for display in TFS 2015. It fails short as the nUnit format that xUnit spits out does not have any console or standard out traces. Therefor when you want to view more information about your tests or error traces on failures non are available. I went down the road to use the nUnit format because TFS was supposed to take it and display it in TFS without tranforming to Trx but that does not work. So the solution is to use the xUnit Xml V2 format by passing the -xml switch to xUnit. Then convert the xml to Trx using your Xslt transform. Mine is here on GitHub if you want a copy.

DNX .Net WebApi Integration testing

I needed to compare some gRPC round trip numbers to plain .Net WebApi. So the question became how to test WepApi round trips from UnitTest harness.

It’s actually pretty simple if you are using the newer DNX libraries. I’m using the TestHost library to get things done.

From project.json

“System.Net.Http”: “4.0.1-beta-23516”,
“Microsoft.AspNet.TestHost”: “1.0.0-rc1-final”,

The UnitTest itself

[Fact]
    public async void PingTheServerRepeat()
    {
      // Setup client & server
      TestServer server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());
      HttpClient client = server.CreateClient();

      // Make a request and check response
      var getResponse = await client.GetAsync(“/api/values/5”);
      var response = await getResponse.Content.ReadAsStringAsync();
      Logger.Log(“web api, response=” + response);

      // Hit the webapi, repeatedly
      Stopwatch watch = Stopwatch.StartNew();
      for (int i = 0; i < Util.Repeat; i++)
      {
        getResponse = await client.GetAsync(“/api/values/” + i);
        response = await getResponse.Content.ReadAsStringAsync();
      }
      watch.Stop();
      Logger.Log($“WepApi, round trips={Util.Repeat}, Execution time, millisec={watch.ElapsedMilliseconds}, average roundtrip=” + ((double)watch.ElapsedMilliseconds / Util.Repeat));
      Logger.Log(“web api, response=” + response);

      // Done, release resources
      server.Dispose();
      client.Dispose();
    }

TFS 2015, Xunit, Nunit, transform to Trx

As TFS vNext currently doesn’t have NoShadowCopy option ( should be coming with the new DNX / 2016 ). I had to modify my new TFS build definition to use xUnit runner to run my tests and then have it output the result file in the optional xunit xml format ( -nunit option ). However true to form TFS 2015 doesn’t understand the Nunit xml format even though they have that as one of their options on the UnitTest results upload vNext task. The next part was to figure out how to transform the Nunit xml to TRX in order for TFS to be able to show the results on the dashboard. Using nxslt3 to transform and NUnitToMSTest.xlst transformation seems to be the way to go. However NUnitToMSTest.xlst doesn’t transform it correctly, at least not to the liking of VS2012, VS2015 or TFS 2015. So I had to modify the xlst slightly and then it will load in VS and the TFS dashboard. Below is the new version of NUnitToMSTest.xlst.

New version
NUnitToMSTest.xslt

msTest Initialization UnitTest Framework error – No types found implementing

I started getting the following error when running specific UnitTests on the server, and only on the server. Running the tests from Visual Studio both using msTest and TestDriven was fine. But obviously something was missing. The good part about using different runners to run tests is that you often find niche cases that you would have otherwise missed. I was able to duplicate the behavior using msTest from the command line on the development machine. Then I noticed that when msTest runs it creates a whole new directory for each run ( based on timestamp ) in order to run the tests in isolation. I started to realize my problem as the files needed for the test need to be copied to the new directory. As I was using reflection to load some of the dlls msTest would have no instructions that I needed those dlls to be copied over as well.

Initialization method Framework.Conventions.UnitTests.ConventionAdapterExtensionsTests.Initialize threw exception. Framework.FrameworkUsageException: Framework.FrameworkUsageException: No types found implementing IConventionAdapterProvider.

The trick is to declare the needed dlls as deployment items for your UnitTests test class and you are in business. In my case I needed these three dlls.

[DeploymentItem(“Framework.Compiler.dll”)]
[DeploymentItem(“Framework.Conventions.Compiler.dll”)]
[DeploymentItem(“Framework.Logging.dll”)]
[TestClass]
public class ConventionAdapterExtensionsTests
{