Archive for the ‘C#’ Category.
October 15, 2018, 18:07
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);
}
}
}
June 23, 2017, 09:54
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.
June 15, 2017, 16:15
I needed to add Nlog tracing that must be configurable from the config file. Finding a simple sample took a me a while. Therefor I’m putting the needed pieces here.
App.config
<?xml version=“1.0” encoding=“utf-8” ?>
<configuration>
<configSections>
<section name=“nlog” type=“NLog.Config.ConfigSectionHandler, NLog”/>
</configSections>
<nlog xmlns=“http://www.nlog-project.org/schemas/NLog.xsd”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
autoReload=“true”
throwExceptions=“false”>
<variable name=“appName” value=“sample” />
<targets async=“true”>
<target xsi:type=“File”
name=“default”
fileName=“sample.log”
keepFileOpen=“false”
DeleteOldFileOnStartup=“true”
/>
</targets>
<rules>
<logger name=“*” writeTo=“default” minlevel=“Info” />
</rules>
</nlog>
</configuration>
And then in code, you can just do the following.
using NLog;
Logger logger = LogManager.GetLogger(“mylogger”);
logger.Log(LogLevel.Debug, “Hellow world”);
May 1, 2017, 12:28
Things have changed a bit since the DNX .Net WebApi Integration testing post that I wrote about a year ago. This post will show updated code for .Net Core 1.1, I’m using the TestHost library as before.
I’m using these Nuget packages
xunit 2.3.0-beta1-build3642
Microsoft.AspNet.TestHost 1.1.1
Here is the UnitTest itself
using System;
using System.
Diagnostics;
using System.
Net.
Http;
using Microsoft.
AspNetCore.
TestHost;
using Microsoft.
AspNetCore.
Hosting;
using Xunit;
using DevOps.
Notes.
Core.
Util;
namespace DevOps.Notes.Web.Spec
{
public class ValuseControllerTest
{
[Fact]
public async void PingTheServerRepeat()
{
// Setup client & server
TestServer server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
HttpClient client = server.CreateClient();
// Make a request and check response
var getResponse = await client.GetAsync(“api/values/”);
var response = await getResponse.Content.ReadAsStringAsync();
TraceLog.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();
TraceLog.Log($“WepApi, round trips ={Util.Repeat}, Execution time, millisec={watch.ElapsedMilliseconds}, average roundtrip=” + ((double)watch.ElapsedMilliseconds / Util.Repeat));
TraceLog.Log(“web api, response=” + response);
// Done, release resources
server.Dispose();
client.Dispose();
}
}
}
November 13, 2015, 17:25
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
August 14, 2015, 10:57
A lot has changed since my last post using Selenium to test web pages. Then you had to install a few things both on the client, browser and server. Today it has been simplified a lot. All you need really is the webdriver and you are in business. You can use the webdriver on your development machine and the server machine as well to run the Selenium tests. In my case I’m using the Ghost-PhanthomJS webdriver as I need to do headless testing ( no GUI ). Since it’s a lot harder to run tests automatically on the server if there is need for GUI, it will complicate things a lot, has to do with security restrictions etc.
Lets take a look at what is needed.
Create a new C# project in VS
Install xUnit Package Manger Console in VS using nuget.
Note I’m specifically using 1.9.2 and 2.0 as I know these two work on the build machine, I had trouble with other version combinations.
PM> Install-Package xunit -Version 1.9.2
Install xUnit VS Runner
PM>Install-Package xunit.runner.visualstudio -Version 2.0.0
Install the Chrome webdriver and libraries
PM> Install-Package WebDriver.ChromeDriver
Install the PhantomJS headless driver and libraries
PM> Install-Package PhantomJS
Then we write the test that will run after the build does the web deployment to the local server. The sample below just loads google.com and checks for the title, then shuts down.
//
using
System;
//
using Xunit;
//
using OpenQA.
Selenium;
using OpenQA.
Selenium.
Support.
UI;
using OpenQA.
Selenium.
PhantomJS;
namespace IntegrationTesting
{
public class HelloIntegration
{
// Proofs that google can be pulled up in the browser and has the right title
[Fact]
public void GoogleCheckTitle()
{
// Init
IWebDriver driver = new PhantomJSDriver();
// Test
driver.Navigate().GoToUrl(“http://www.google.com”);
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
var title = driver.Title;
// Proof
Assert.Equal( “Google”, title);
// Close down
driver.Quit();
}
}
}
If you are using TFS you also need to point your build agent to the xUnit runner, in my case I just check it in as part of the project and set it like that.
Path to custom test adapters
$(Build.SourcesDirectory)\TestWebSite\xunit_runner\
That’s all you need, then you can write your own tests to test specific functionality tailored to your needs. Selenium is pretty powerful for Integration testing.