Jekyll2021-04-24T00:57:28+00:00https://alteridem.net/feed.xmlAlteridemProven software engineer and architect with a passion for building high performance agile teams and empowering them to deliver customer value through software and technology.Rob ProuseContinuous Delivery for Azure Web Apps2018-05-07T13:25:11+00:002018-05-07T13:25:11+00:00https://alteridem.net/2018/05/07/continuous-delivery-for-azure-web-apps<p>My talk on Continuous Integration (CI) and Continuous Delivery (CD) to <a href="https://azure.microsoft.com/en-ca/services/app-service/web/" target="_blank" rel="noopener">Azure Web Apps</a> that I gave at the <a href="https://global.azurebootcamp.net/" target="_blank" rel="noopener">Global Azure Bootcamp 2018</a>. The talk begins with Right-Click Publish from Visual Studio to an Azure Web App. It then demonstrates automatically deploying updates to the master branch of a <a href="https://github.com/" target="_blank" rel="noopener">GitHub</a> repository. The talk then concludes with by setting up a full build and release CI/CD pipeline using <a href="https://www.visualstudio.com/team-services/" target="_blank" rel="noopener">Visual Studio Team Services</a> (VSTS).</p>
<p><iframe src="https://www.youtube.com/embed/EersuZ5-Gac?rel=0" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>
<p>Slides from this presentation are <a href="https://github.com/wragmeetup/GlobalAzureBootcamp2018/tree/master/04%20%E2%80%93%20Continuous%20Delivery%20for%20Azure%20Web%20Apps">available on GitHub</a>.</p>Rob ProuseMy talk on Continuous Integration (CI) and Continuous Delivery (CD) to Azure Web Apps that I gave at the Global Azure Bootcamp 2018. The talk begins with Right-Click Publish from Visual Studio to an Azure Web App. It then demonstrates automatically deploying updates to the master branch of a GitHub repository. The talk then concludes with by setting up a full build and release CI/CD pipeline using Visual Studio Team Services (VSTS). Slides from this presentation are available on GitHub.Testing .NET Core with NUnit in Visual Studio 20172017-05-04T21:21:51+00:002017-05-04T21:21:51+00:00https://alteridem.net/2017/05/04/test-net-core-nunit-vs2017<p>The switch from the <strong>project.json</strong> format to the new <strong>csproj </strong>based format for .NET Core and .NET Standard projects also changed the API for test adapters. Because of this, NUnit's <a href="https://github.com/nunit/dotnet-test-nunit">dotnet-test-nunit adapter</a> stopped working and we had to update our existing <a href="https://github.com/nunit/nunit3-vs-adapter">Visual Studio test adapter</a> to support .NET Core. Last night I released the <a href="https://www.nuget.org/packages/NUnit3TestAdapter/3.8.0-alpha1">first alpha release of the test adapter to NuGet</a> enabling testing of .NET Core and .NET Standard projects using Visual Studio 2017, Visual Studio Code, TFS Build, and, the dotnet test CLI command.</p>
<p><!--more--></p>
<h2>Creating a Test Project</h2>
<p>The following instructions are for Visual Studio, but the principles apply to all development environments.</p>
<p>In the solution that you want to test, <strong>Add | New Project...</strong> and add a <strong>Visual C# | .NET Core | Class Library (.NET Core)</strong>.</p>
<p><img src="/assets/img/2017/05/Add-.NET-Core-Class-Library.png" alt="Add .NET Core Class Library" width="656" height="421" align="center" /></p>
<p>I am testing a .NET Standard library, but I am using a .NET Core class library for testing. Testing requires a platform to test on, so your test assembly must target a specific platform. I selected .NET Core, but I could also target .NET 4.5 or even multi-target the test assembly. Be aware that multi-targeted test projects are barely supported by Visual Studio and your results may vary. Hopefully we will see improvements in the tooling soon.</p>
<h2>Adding NuGet References</h2>
<p>First, you will want to add a project reference to the project you are testing, then add NuGet references to the test framework <strong>NUnit</strong> 3.6.1, to the test runner <strong>NUnit3TestAdapter</strong> 3.8.0-alpha1 and to the test SDK <strong>Microsoft.NET.Test.Sdk</strong> 15.0.0. Add the references either using the <strong>Manage NuGet Packages...</strong> user interface, or by editing the project file.</p>
<p><img src="/assets/img/2017/05/Add-NuGet-References-to-Test-Project.png" alt="Add NuGet References to Test Project" width="790" height="429" align="center" /></p>
<p>Your csproj file should end up looking similar to this. Notice how much cleaner the new format is.</p>
<pre><code class="xml"><project Sdk="Microsoft.NET.Sdk">
<propertygroup>
<targetframework>netcoreapp1.1</targetframework>
</propertygroup>
<itemgroup>
<packagereference Include="Microsoft.NET.Test.Sdk" Version="15.0.0"></packagereference>
<packagereference Include="NUnit" Version="3.6.1"></packagereference>
<packagereference Include="NUnit3TestAdapter" Version="3.8.0-alpha1"></packagereference>
</itemgroup>
<itemgroup>
<projectreference Include="..\NetStandardLibrary\NetStandardLibrary.csproj"></projectreference>
</itemgroup>
<itemgroup>
<service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}"></service>
</itemgroup>
</project>
</code></pre>
<p>From here, <a href="/2016/10/03/nunit-unit-tests/">write your unit tests</a> as you would for any project.</p>
<h2>Running Tests in Visual Studio</h2>
<p>Running tests in Visual Studio hasn't changed. See my previous post on <a href="/2016/10/20/nunit-visual-studio-adapter/">running NUnit tests in Visual Studio</a> if you have questions.</p>
<p><img src="/assets/img/2017/05/Running-Unit-Tests.png" alt="Running Unit Tests in Visual Studio" width="259" height="291" align="center" /></p>
<p>A few things to note,</p>
<ul>
<li>If you multi-target your tests, only one target will run in Visual Studio, I believe the first</li>
<li>Code Coverage is not supported for .NET Core yet, that will be available in a future update to Visual Studio</li>
<li>Live Unit Testing is also not available for .NET Core yet</li>
</ul>
<h2>Running Tests from the Command Line</h2>
<p>Adding the <a href="https://www.nuget.org/packages/NUnit3TestAdapter/3.8.0-alpha1">NUnit 3 Test Adapter</a> to your project will also allow you to use the <strong>dotnet test</strong> CLI. Here is an example run with the unit tests targeting both .NET 4.5 and .NET Core 1.1.</p>
<pre><code class="nohighlight">C:\src\Spikes\NetStandardLibrary
λ dotnet test .\NetStandardLibrary.Tests\NetStandardLibrary.Tests.csproj
Build started, please wait...
Build completed.
Test run for C:\src\Spikes\NetStandardLibrary\NetStandardLibrary.Tests\bin\Debug\net45\NetStandardLibrary.Tests.dll(.NETFramework,Version=v4.5)
Microsoft (R) Test Execution Command Line Tool Version 15.0.0.0
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
NUnit Adapter 3.8.0.0: Test execution started
Running all tests in C:\src\Spikes\NetStandardLibrary\NetStandardLibrary.Tests\bin\Debug\net45\NetStandardLibrary.Tests.dll
NUnit3TestExecutor converted 18 of 18 NUnit test cases
NUnit Adapter 3.8.0.0: Test execution complete
Total tests: 18. Passed: 18. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 0.9096 Seconds
Test run for C:\src\Spikes\NetStandardLibrary\NetStandardLibrary.Tests\bin\Debug\netcoreapp1.1\NetStandardLibrary.Tests.dll(.NETCoreApp,Version=v1.1)
Microsoft (R) Test Execution Command Line Tool Version 15.0.0.0
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
NUnit Adapter 3.8.0.0: Test execution started
Running all tests in C:\src\Spikes\NetStandardLibrary\NetStandardLibrary.Tests\bin\Debug\netcoreapp1.1\NetStandardLibrary.Tests.dll
NUnit3TestExecutor converted 18 of 18 NUnit test cases
NUnit Adapter 3.8.0.0: Test execution complete
Total tests: 18. Passed: 18. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.1661 Seconds
</code></pre>
<p>The tests run for both targets and that you get the output from the <strong>dotnet test</strong> command, not the normal coloured NUnit output that you would get from the NUnit Console. Hopefully we will be releasing an updated console runner in the near future.</p>Rob ProuseThe switch from the project.json format to the new csproj based format for .NET Core and .NET Standard projects also changed the API for test adapters. Because of this, NUnit's dotnet-test-nunit adapter stopped working and we had to update our existing Visual Studio test adapter to support .NET Core. Last night I released the first alpha release of the test adapter to NuGet enabling testing of .NET Core and .NET Standard projects using Visual Studio 2017, Visual Studio Code, TFS Build, and, the dotnet test CLI command. Creating a Test Project The following instructions are for Visual Studio, but the principles apply to all development environments. In the solution that you want to test, Add | New Project... and add a Visual C# | .NET Core | Class Library (.NET Core). I am testing a .NET Standard library, but I am using a .NET Core class library for testing. Testing requires a platform to test on, so your test assembly must target a specific platform. I selected .NET Core, but I could also target .NET 4.5 or even multi-target the test assembly. Be aware that multi-targeted test projects are barely supported by Visual Studio and your results may vary. Hopefully we will see improvements in the tooling soon. Adding NuGet References First, you will want to add a project reference to the project you are testing, then add NuGet references to the test framework NUnit 3.6.1, to the test runner NUnit3TestAdapter 3.8.0-alpha1 and to the test SDK Microsoft.NET.Test.Sdk 15.0.0. Add the references either using the Manage NuGet Packages... user interface, or by editing the project file. Your csproj file should end up looking similar to this. Notice how much cleaner the new format is. <project Sdk="Microsoft.NET.Sdk">Installing Google Play (GApps) on Visual Studio Android Emulators (2017 version)2017-02-02T15:27:09+00:002017-02-02T15:27:09+00:00https://alteridem.net/2017/02/02/installing-google-play-gapps-visual-studio-android-emulators<p>The <a href="https://www.visualstudio.com/en-us/features/msft-android-emulator-vs.aspx">Visual Studio Emulator for Android</a> does not ship with <a href="https://developers.google.com/android/guides/overview">Google Play Services</a>, so if you want to use those services, like Google Maps, you must install them.</p>
<p>Back in 2015, <a href="/2015/10/28/installing-google-play-services-gapps-on-visual-studio-android-emulators/">I outlined the installation steps</a>, but those steps no longer work and the process is now much easier.</p>
<p><!--more--></p>
<h2>Download GApps</h2>
<p>The best place to download GApps is from <a href="http://www.teamandroid.com/gapps/">Team Android</a>. Do not download from <a href="http://opengapps.org/" target="_blank">Open GApps</a>, they will not install. Some versions from <a href="http://www.teamandroid.com/gapps/">Team Android</a> also do not install. I had to find an alternate version of GApps that installs and runs on Android 6.0. This requires an extra install, so see the instructions at the end.</p>
<p>The GApps versions I have found to work are,</p>
<table>
<tbody>
<tr>
<th>API</th>
<th>Android Ver</th>
<th></th>
<th>Notes</th>
</tr>
<tr>
<td>23</td>
<td>6.0 Marshmallow</td>
<td>[<a href="https://www.androidfilehost.com/?fid=96042739161891406">Part 1</a>] [<a href="https://www.androidfilehost.com/?fid=24052804347835438">Part 2</a>]</td>
<td>See notes below</td>
</tr>
<tr>
<td>22</td>
<td>5.1.1 Lollipop</td>
<td>[<a href="http://www.devfiles.co/download/fAgtiEoX/gapps-lp-20150314.zip">Download</a>]</td>
<td> Play Store crashes occasionally</td>
</tr>
<tr>
<td>21</td>
<td>5.0 Lollipop</td>
<td>[<a href="http://www.devfiles.co/download/R5AHj6Pz/gapps-lp-20141109-signed.zip">Download</a>]</td>
<td> Google+ crashes</td>
</tr>
<tr>
<td>19</td>
<td>4.4 KitKat</td>
<td>[<a href="http://www.devfiles.co/download/7m2VdVjQ/gapps-kk-20140105-signed.zip">Download</a>] [<a href="https://www.mediafire.com/?qmd7z9x5ndsb54k">Mirror</a>]</td>
<td></td>
</tr>
<tr>
<td>17</td>
<td>4.2 JellyBean</td>
<td>[<a href="http://www.devfiles.co/download/nzmXh3xF/gapps-jb-20130812-signed.zip">Download</a>]</td>
<td> Google+ crashes</td>
</tr>
</tbody>
</table>
<h2>Install Genymotion ARM Translation</h2>
<p>The Visual Studio emulators are x86 whereas most Android devices are ARM based. I find that many apps work as is, but for those that don't you should download and install <a href="https://www.dropbox.com/s/tdye2pobix70gqw/%5BTechBae.com%5DGenymotion-ARM-Translation_v1.1.zip?dl=0">Genymotion ARM Translation</a> which provides ARM to x86 translations.</p>
<p>Download the <a href="https://www.dropbox.com/s/tdye2pobix70gqw/%5BTechBae.com%5DGenymotion-ARM-Translation_v1.1.zip?dl=0">ARM Translation ZIP</a>, then drag it onto your running emulator. When the dialog opens, select <strong>Install and shut down</strong>.</p>
<p><img class="aligncenter size-full wp-image-751" src="/assets/img/2017/02/2017-02-02-11_44_27-Visual-Studio-Emulator-for-Android.png" alt="" width="426" height="179" /></p>
<p>Once it finishes installing, shut down and restart the emulator.</p>
<h2>Installing GApps</h2>
<p>Installing GApps the same way by dragging the correct ZIP file and drop it on the running emulator. When the dialog opens, select <strong>Install and shut down</strong>.</p>
<p><img class="aligncenter size-full wp-image-752" src="/assets/img/2017/02/Install-GApps.png" alt="" width="426" height="179" /></p>
<p>When you are prompted, shutdown the emulator and then restart it.</p>
<h2>Configuring GApps</h2>
<p>Once the emulator restarts, open Google Play and sign in with your account. Once you are signed in, go to <strong>My Apps</strong> and update all installed apps. Once the various Google apps update, you will likely get notifications that you must <strong>update Google Play Services</strong>. Click on one of them to update.</p>
<p><img class="aligncenter size-medium wp-image-754" src="/assets/img/2017/02/Update-Google-Play-Service-275x300.png" alt="" width="275" height="300" /></p>
<p>On several versions of Android, Google+ will crash repeatedly. Dismiss the crash dialogs and try to update it using Google Play. If this does not work, go into App Settings and disable it.</p>
<h2>Installing on Android 6.0</h2>
<p>The version of GApps from Team Android crashed on Android 6.0, but I figured out a workaround based on <a href="https://z3ntu.github.io/2015/12/10/play-services-with-genymotion.html">z3ntu's post</a>.</p>
<ol>
<li>Download and install the <a href="https://www.dropbox.com/s/tdye2pobix70gqw/%5BTechBae.com%5DGenymotion-ARM-Translation_v1.1.zip?dl=0">Genymotion ARM Translation</a> then restart the emulator</li>
<li>Download and install <a href="https://www.androidfilehost.com/?fid=96042739161891406">gapps-L-4-21-15.zip</a></li>
<li>After rebooting, go to Google Play and sign in. Dismiss any crashes</li>
<li>Download and install <a href="https://www.androidfilehost.com/?fid=24052804347835438">benzo-gapps-M-20151011-signed-chroma-r3.zip</a></li>
<li>After rebooting, go to Google Play and update all installed apps</li>
</ol>Rob ProuseThe Visual Studio Emulator for Android does not ship with Google Play Services, so if you want to use those services, like Google Maps, you must install them. Back in 2015, I outlined the installation steps, but those steps no longer work and the process is now much easier. Download GApps The best place to download GApps is from Team Android. Do not download from Open GApps, they will not install. Some versions from Team Android also do not install. I had to find an alternate version of GApps that installs and runs on Android 6.0. This requires an extra install, so see the instructions at the end. The GApps versions I have found to work are, API Android Ver Notes 23 6.0 Marshmallow [Part 1] [Part 2] See notes below 22 5.1.1 Lollipop [Download] Play Store crashes occasionally 21 5.0 Lollipop [Download] Google+ crashes 19 4.4 KitKat [Download] [Mirror] 17 4.2 JellyBean [Download] Google+ crashes Install Genymotion ARM Translation The Visual Studio emulators are x86 whereas most Android devices are ARM based. I find that many apps work as is, but for those that don't you should download and install Genymotion ARM Translation which provides ARM to x86 translations. Download the ARM Translation ZIP, then drag it onto your running emulator. When the dialog opens, select Install and shut down. Once it finishes installing, shut down and restart the emulator. Installing GApps Installing GApps the same way by dragging the correct ZIP file and drop it on the running emulator. When the dialog opens, select Install and shut down. When you are prompted, shutdown the emulator and then restart it. Configuring GApps Once the emulator restarts, open Google Play and sign in with your account. Once you are signed in, go to My Apps and update all installed apps. Once the various Google apps update, you will likely get notifications that you must update Google Play Services. Click on one of them to update. On several versions of Android, Google+ will crash repeatedly. Dismiss the crash dialogs and try to update it using Google Play. If this does not work, go into App Settings and disable it. Installing on Android 6.0 The version of GApps from Team Android crashed on Android 6.0, but I figured out a workaround based on z3ntu's post. Download and install the Genymotion ARM Translation then restart the emulator Download and install gapps-L-4-21-15.zip After rebooting, go to Google Play and sign in. Dismiss any crashes Download and install benzo-gapps-M-20151011-signed-chroma-r3.zip After rebooting, go to Google Play and update all installed appsUnit Test Non-Public Methods and Classes2017-01-09T11:52:44+00:002017-01-09T11:52:44+00:00https://alteridem.net/2017/01/09/unit-test-non-public-methods<p>You often want to unit test non-public methods and classes in .NET, but you don't want to make them public. The most common solution is to make the methods and classes <strong>internal</strong> and access them from your unit test project using the <a href="https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx">InternalsVisibleTo</a> attribute.</p>
<p><!--more--></p>
<h2>Unsigned Assemblies</h2>
<p>If your assemblies are unsigned, edit <strong>AssemblyInfo.cs</strong> in the project you are unit testing and add the following attribute,</p>
<pre><code class="csharp">[assembly: InternalsVisibleTo("MyAssembly.Tests")]
</code></pre>
<p>Remember to add the attribute to your main project and use the name of your test project. Once you do this, you can access internal classes and methods from your test project.</p>
<h2>Signed Assemblies</h2>
<p>If your assemblies are signed, you must sign your test assembly and include the <strong>full</strong> public key in the <a href="https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx">InternalsVisibleTo</a> attribute.</p>
<p>To do this, use the <a href="https://msdn.microsoft.com/en-us/library/k5b5tt23.aspx" target="_blank">Strong Name Tool (sn.exe)</a> to extract the public key from your test assembly.</p>
<ol>
<li>Open a Visual Studio command prompt</li>
<li>CD to the bin directory where your test assembly was built</li>
<li>Run the command <strong>sn -Tp MyAssembly.Tests</strong></li>
</ol>
<p>Running this command will produce the following output,</p>
<pre><code>Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.0
Copyright (c) Microsoft Corporation. All rights reserved.
Public key (hash algorithm: sha1):
0024000004800000940000000602000000240000525341310004000001000100750098646d1c04
c2a041faaf801521a769535de9a04cd3b4dedccbf73d1a6456bf4fe58814510e84983c72d0460b
8ba85c52a9cacdc4a0786af54e90cb7a81eb2049ecfe6b2c5e20a18fe4b9bff009ada232e980d2
20b3c9586c9c5ee29c29aee8853db7bb90cf5a4c704f5244e1a1085c43060085350329021ec902
47e70eb2
Public key token is a5778f560690a058
</code></pre>
<p>Copy the full public key and add it to the <a href="https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx">InternalsVisibleTo</a> attribute in <strong>AssemblyInfo.cs</strong></p>
<pre><code class="csharp">[assembly: InternalsVisibleTo("MyAssembly.Tests, PublicKey=" +
"0024000004800000940000000602000000240000525341310004000001000100750098646d1c04" +
"c2a041faaf801521a769535de9a04cd3b4dedccbf73d1a6456bf4fe58814510e84983c72d0460b" +
"8ba85c52a9cacdc4a0786af54e90cb7a81eb2049ecfe6b2c5e20a18fe4b9bff009ada232e980d2" +
"20b3c9586c9c5ee29c29aee8853db7bb90cf5a4c704f5244e1a1085c43060085350329021ec902" +
"47e70eb2")]
</code></pre>Rob ProuseYou often want to unit test non-public methods and classes in .NET, but you don't want to make them public. The most common solution is to make the methods and classes internal and access them from your unit test project using the InternalsVisibleTo attribute. Unsigned Assemblies If your assemblies are unsigned, edit AssemblyInfo.cs in the project you are unit testing and add the following attribute, [assembly: InternalsVisibleTo("MyAssembly.Tests")] Remember to add the attribute to your main project and use the name of your test project. Once you do this, you can access internal classes and methods from your test project. Signed Assemblies If your assemblies are signed, you must sign your test assembly and include the full public key in the InternalsVisibleTo attribute. To do this, use the Strong Name Tool (sn.exe) to extract the public key from your test assembly. Open a Visual Studio command prompt CD to the bin directory where your test assembly was built Run the command sn -Tp MyAssembly.Tests Running this command will produce the following output, Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.0 Copyright (c) Microsoft Corporation. All rights reserved.CoderCamp Hamilton S16E122016-11-17T16:54:11+00:002016-11-17T16:54:11+00:00https://alteridem.net/2016/11/17/codercamp-hamilton-s16e12<p>The next <a href="http://www.codercamphamilton.com/Events/2016/12/14/CoderCamp-S16E12">CoderCamp Hamilton</a> session will be December 14th at 6:30pm upstairs at the Pheasant Plucker, 20 Augusta Street, Hamilton.<!--more--></p>
<p>Rob Porter (<a href="https://twitter.com/rgeraldporter">@rgeraldporter</a>) from <a href="http://weeverapps.com/">Weaver Apps</a> will be speaking about coding and digital solutions to naturalist problems, touching upon improvements on collecting species data in the field, making historical sets of Hamilton species data going
back decades more available, all using some functional <a href="https://www.javascript.com/">JavaScript</a> & <a href="https://nodejs.org/en/">Node.js</a> code and maybe even some <a href="https://www.r-project.org/">R</a>.</p>
<p>Nathan Jervis (<a href="https://twitter.com/mirhagk">@mirhagk</a>) will talk about Visual Studio Team Services (aka Visual Studio Online, aka Team Foundation Server) and how it can be the central location for all the parts of development that aren't in your editor (source control hosting, issue management, product planning, continuous builds, releases, testing). How it can work with whatever tools you have, mixing and matching the right tools for the right job.</p>
<p><a href="https://twitter.com/rprouse">Rob Prouse</a> and <a href="https://twitter.com/bpoetz">Bryan Poetz</a> will lead a discussion about the future format of CoderCamp. Bring your ideas about what types of presentations you would like to see and thoughts on changes we can make to the format.</p>
<p>Please <a href="mailto:codercamphamilton@gmail.com">contact us</a> if you are interested in giving a talk.</p>Rob ProuseThe next CoderCamp Hamilton session will be December 14th at 6:30pm upstairs at the Pheasant Plucker, 20 Augusta Street, Hamilton.Debugging Visual Studio Extensions2016-11-11T09:34:31+00:002016-11-11T09:34:31+00:00https://alteridem.net/2016/11/11/debugging-visual-studio-extensions<p>Writing Visual Studio Extensions has gotten much easier with recent versions of Visual Studio, but figuring out how to debug them can be hard. When you debug an extension, you run it in an instance of Visual Studio using a separate set of settings called an experimental hive. When you launch this from Visual Studio, it takes care of installing your extension and the debugger is attached to Visual Studio itself.</p>
<p><!--more--></p>
<p>The usual recommendation is to edit the project's Properties and enter the information in the Debug Tab. This works, but that information is not saved in the project file, so you need to do it whenever you get a clean copy of the source. I prefer saving the information in the project file itself.</p>
<h2>Editing the Visual Studio Extension Project File</h2>
<p>Unload the extension project in Visual Studio by right clicking on it and selecting <strong>Unload Project</strong>. Next, edit the project by right clicking and selecting <strong>Edit MyExtension.csproj</strong>.</p>
<p>Add the following XML after the first <strong></PropertyGroup></strong> end tag in the project.</p>
<pre><code class="xml"><propertygroup>
<!-- Common debugging support -->
<startaction>Program</startaction>
<startprogram>$(DevEnvDir)\devenv.exe</startprogram>
<startarguments>/rootsuffix Exp</startarguments>
</propertygroup>
</code></pre>
<p><strong>Please note</strong>, the XML above should be PascalCase, in other words, <strong>propertygroup</strong> should be <strong>PropertyGroup</strong>. Wordpress keeps converting the code to lowercase. If anyone knows how to fix that, please let me know in the comments.</p>
<p>This runs the current version of Visual Studio using the <strong>/rootsuffix Exp</strong> command line. If you save the file and reload it, you will now see the options in the Debug Tab of the project's Properties.</p>
<p><img class="aligncenter size-full wp-image-703" src="/assets/img/2016/11/2016-11-11-06_29_56-GitHubExtension-Microsoft-Visual-Studio.png" alt="Debugging a Visual Studio Extension" width="656" height="265" /></p>
<p>If you see something different, delete your <strong>.csproj.user</strong> file and don't change the values here otherwise they will be saved in the .csproj.user file. If you want to make changes, you must hand edit the file.</p>Rob ProuseWriting Visual Studio Extensions has gotten much easier with recent versions of Visual Studio, but figuring out how to debug them can be hard. When you debug an extension, you run it in an instance of Visual Studio using a separate set of settings called an experimental hive. When you launch this from Visual Studio, it takes care of installing your extension and the debugger is attached to Visual Studio itself. The usual recommendation is to edit the project's Properties and enter the information in the Debug Tab. This works, but that information is not saved in the project file, so you need to do it whenever you get a clean copy of the source. I prefer saving the information in the project file itself. Editing the Visual Studio Extension Project File Unload the extension project in Visual Studio by right clicking on it and selecting Unload Project. Next, edit the project by right clicking and selecting Edit MyExtension.csproj. Add the following XML after the first </PropertyGroup> end tag in the project. <pre><code class="xml"><propertygroup> <!-- Common debugging support --> <startaction>Program</startaction> <startprogram>$(DevEnvDir)\devenv.exe</startprogram> <startarguments>/rootsuffix Exp</startarguments> </propertygroup> Please note, the XML above should be PascalCase, in other words, propertygroup should be PropertyGroup. Wordpress keeps converting the code to lowercase. If anyone knows how to fix that, please let me know in the comments. This runs the current version of Visual Studio using the /rootsuffix Exp command line. If you save the file and reload it, you will now see the options in the Debug Tab of the project's Properties. If you see something different, delete your .csproj.user file and don't change the values here otherwise they will be saved in the .csproj.user file. If you want to make changes, you must hand edit the file.NUnit Console Runner NuGet Packages2016-11-08T01:52:13+00:002016-11-08T01:52:13+00:00https://alteridem.net/2016/11/08/nunit-console-nuget-packages<p>There are three different versions of the NUnit Console runner on <a href="https://www.nuget.org/packages?q=nunit+console+runner" target="top">NuGet</a>. This can be confusing for new users who don't know which one to pick. The NUnit team has tried to make it easier to pick by changing the titles and descriptions, but Visual Studio shows the package name. Extensions add to the confusion, thus this guide.<a id="more"></a><a id="more-691"></a></p>
<p><!-- more --></p>
<h2 id="nunit.consolerunner">NUnit.ConsoleRunner</h2>
<p>The <a href="https://www.nuget.org/packages/NUnit.ConsoleRunner/">NUnit.ConsoleRunner</a> package contains just the NUnit 3 console runner without any extensions. Because it doesn't have extensions, it cannot run NUnit 2 tests, it cannot export NUnit 2 XML results and it cannot report test progress to TeamCity.</p>
<p>If you need any of functionality that is not shipped with NUnit.ConsoleRunner, you just need to install the NuGet packages for the extensions you need (see below) or to make it easy, install the <a href="https://www.nuget.org/packages/NUnit.Console/">NUnit.Console</a> package. Any installed extensions are automatically found by NUnit.</p>
<p>After you install this package, the console runner will be in <code>packages\NUnit.ConsoleRunner.3.5.0\tools\nunit3-console.exe</code>.</p>
<h2 id="nunit.console">NUnit.Console</h2>
<p>The <a href="https://www.nuget.org/packages/NUnit.Console/">NUnit.Console</a> package is a meta-package that includes the <a href="https://www.nuget.org/packages/NUnit.ConsoleRunner/">NUnit.ConsoleRunner</a> package and commonly used extensions. A common cause of confusion is that after you download this extension, it doesn't have any files in it. You will find the console runner in the <a href="https://www.nuget.org/packages/NUnit.ConsoleRunner/">NUnit.ConsoleRunner</a> package. As I said, this is a meta-package, it is just a list of NuGet dependencies.</p>
<h2 id="nunit.runners">NUnit.Runners</h2>
<p><strong>Do not use this package</strong> <a href="https://www.nuget.org/packages/NUnit.Runners/">This package</a> has the most downloads because it is the original NUnit 2 package. This package is equivalent to the <a href="https://www.nuget.org/packages/NUnit.Console/">NUnit.Console</a> package in that it includes the console and common extensions.</p>
<p>This package is <strong>deprecated</strong> and should no longer be used. Switch to the <a href="https://www.nuget.org/packages/NUnit.Console/">NUnit.Console</a> package. The NUnit Console package is deprecated because it used to contain both the console and GUI runners. It was decided to split each out into it's own package.</p>
<h2 id="extensions">Extensions</h2>
<p>Rather than ship with functionality that you may not use, NUnit allows you to add extensions. Out of the box, NUnit can run NUnit 3 tests and produce NUnit 3 test results. If you need more, install an extension.</p>
<p>The most common extensions ship with the <a href="https://www.nuget.org/packages/NUnit.Console/">NUnit.Console</a> package and are,</p>
<ul>
<li><a href="https://www.nuget.org/packages/NUnit.Extension.NUnitProjectLoader/">NUnit.Extension.NUnitProjectLoader</a> - Loads the NUnit project file format</li>
<li><a href="https://www.nuget.org/packages/NUnit.Extension.VSProjectLoader/">NUnit.Extension.VSProjectLoader </a> - Loads Visual Studio projects and solutions</li>
<li><a href="https://www.nuget.org/packages/NUnit.Extension.NUnitV2ResultWriter/">NUnit.Extension.NUnitV2ResultWriter</a> - Writes test results in the NUnit 2 legacy format</li>
<li><a href="https://www.nuget.org/packages/NUnit.Extension.NUnitV2Driver/">NUnit.Extension.NUnitV2Driver</a> - Runs tests written with the NUnit 2.x framework</li>
<li><a href="https://www.nuget.org/packages/NUnit.Extension.TeamCityEventListener/">NUnit.Extension.TeamCityEventListener</a> - Reports test progress and results to TeamCity</li>
</ul>
<h2 id="which-package">Which Package?</h2>
<p>Use the <a href="https://www.nuget.org/packages/NUnit.ConsoleRunner/">NUnit.ConsoleRunner</a> package and add any extensions that you need. The fewer extensions that you have, the quicker NUnit will start up and run your projects.</p>
<p>If you don't want to think about it, install the <a href="https://www.nuget.org/packages/NUnit.Console/">NUnit.Console</a> package.</p>Rob ProuseThere are three different NUnit console runner NuGet packages. Knowing the difference and selecting the right one for your project can be confusing at first.Running Tests with the NUnit Visual Studio Adapter2016-10-20T21:29:06+00:002016-10-20T21:29:06+00:00https://alteridem.net/2016/10/20/nunit-visual-studio-adapter<p>Most .NET developers write code using Visual Studio, so it is convenient to be able to run and debug your NUnit tests from within Visual Studio. There are commercial products like <a href="http://testdriven.net/">TestDriven.NET</a>, <a href="http://www.ncrunch.net/">NCrunch</a> and <a href="https://www.jetbrains.com/resharper/">Resharper</a> that can run your tests, but the NUnit Visual Studio Adapter is free and works in all current editions of Visual Studio.<!--more--></p>
<h2>Installing the NUnit Visual Studio Adapter</h2>
<h3>Visual Studio Extension</h3>
<p>The easiest way to install the NUnit Visual Studio Adapter is as an extension. This has the advantage that it is always available and it will automatically update to the latest versions as they are released. The disadvantage is that every person on your team will need to install it.</p>
<p>To install, you can <a href="https://visualstudiogallery.msdn.microsoft.com/0da0f6bd-9bb6-4ae3-87a8-537788622f2d">download the extension</a> from the Visual Studio Gallery and double click the VSIX file to install it in all supported versions of Visual Studio.</p>
<p>The second option is to go to the <strong>Tools | Extensions and Updates</strong> menu in Visual Studio. From here, click on <strong>Online</strong> and search for <strong>nunit adapter</strong>. You are looking for the <strong>NUnit 3 Test Adapter</strong> and install it.</p>
<p><img class="aligncenter wp-image-666 size-full" src="/assets/img/2016/10/2016-10-20-20_46_50-Extensions-and-Updates.png" alt="Install NUnit Visual Studio Adapter as an Extension" width="795" height="453" /></p>
<p>Notice there is an <strong>NUnit Test Adapter</strong> available too. That is the original adapter for running older NUnit 2 tests. If you have older tests, it is fine to install both NUnit test adapters side-by-side.</p>
<h3>NuGet Package</h3>
<p>The other option for installing the NUnit Visual Studio Adapter is as a NuGet package. This has the advantage that it becomes part of your solution and every developer will get it, but you must add it to every solution that needs it.</p>
<p>To install, right click on your test project in Visual Studio and click on <strong>Manage NuGet Packages...</strong></p>
<p>Click on the <strong>Browse</strong> tab and search for <strong>nunit adapter</strong>. You are looking for <strong>NUnit3TestAdapter</strong>. Click it and install. Like the extension, there is also <strong>NUnitTestAdapter</strong> for running NUnit 2 tests.</p>
<p><img class="aligncenter wp-image-669 size-full" src="/assets/img/2016/10/2016-10-20-20_58_38-IntroToNUnit-NuGet_-IntroToNUnit.Tests_.png" alt="Install NUnit Visual Studio Adapter as NuGet Package" width="781" height="476" /></p>
<p>Note that you only have to install the adapter in one test project and it will be available for the entire solution.</p>
<h2>Running Tests using the Test Explorer Window</h2>
<p>You will usually run your tests using the <strong>Test Explorer Window</strong>. To open it, click the <strong>Test | Windows | Test Explorer</strong> menu.</p>
<h3>Running Tests</h3>
<p>After you build your solution, Visual Studio will populate the <strong>Test Explorer Window</strong>. If you don't see any tests, check the output window for errors. To run tests, simply click the <strong>Run All</strong> button in the upper left. You will see your tests run as the progress bar updates and your tests turn green.</p>
<p><img class="aligncenter size-full wp-image-672" src="/assets/img/2016/10/2016-10-20-21_14_02-IntroToNUnit-Microsoft-Visual-Studio.png" alt="Run all tests from the Test Explorer Window" width="380" height="404" /></p>
<p>The <strong>Run...</strong> menu allows you to run failed tests, tests that have not been run before, etc. Right clicking on individual tests or groups of tests and clicking <strong>Run Selected Tests</strong> will run those tests.</p>
<p><strong>Debugging Tests</strong></p>
<p>Tests can be debugged from the <strong>Test Explorer Window</strong>. Add your breakpoints into your code and right click on individual tests or groups of tests, then click <strong>Debug Selected Tests</strong>.</p>
<p>Debugging and running tests is often easiest from the source code you are working on. We'll cover that next.</p>
<h2>Running Tests from within the Source Code Editor</h2>
<p>The easiest way to run or debug tests from within the source code editor is to use the key bindings.</p>
<ul>
<li><strong>Ctrl R, A</strong> - Run All Tests</li>
<li><strong>Ctrl R, Ctrl A</strong> - Debug All Tests</li>
<li><strong>Ctrl R, T</strong> - Run the tests at your cursor</li>
<li><strong>Ctrl R, Ctrl T</strong> - Debug the tests at your cursor</li>
</ul>
<p>Running the tests where your cursor is can be very useful since it runs the tests you are currently working on. When the cursor is in a method, it will run that method, if it is in a class, it will run all tests in the class.</p>
<p>Visual Studio has trouble with multiple tests created using the <a href="/2016/10/17/nunit-testcase-attribute/">TestCase </a>attribute or other data attributes. Using the key-bindings while in these methods will run all tests in the class.</p>
<h3>Code Lens</h3>
<p>If your version of Visual Studio includes Code Lens, your tests will also have a small icon on the left of the code lens that indicates if the test passed, failed, was ignored or hasn't been run. Clicking that icon brings up information on the last test run and allows you to run or debug the test.</p>
<p><img class="aligncenter size-full wp-image-675" src="/assets/img/2016/10/2016-10-20-22_00_43-IntroToNUnit-Microsoft-Visual-Studio.png" alt="Code Lens for Unit Tests" width="722" height="218" /></p>
<h2>Other Features</h2>
<h3>Grouping Tests</h3>
<p>By default, Visual Studio groups tests in the <strong>Test Explorer Window</strong> by their outcome; pass, fail, etc. You can also group by <strong>Class, Duration, Traits</strong> or <strong>Project</strong>. To group your tests, either right-click on a group and select <strong>Group By</strong> or use the dropdown at the top left of the window.</p>
<p><img class="aligncenter size-full wp-image-678" src="/assets/img/2016/10/2016-10-20-22_10_44-IntroToNUnit-Microsoft-Visual-Studio.png" alt="Grouping Unit Tests" width="232" height="200" /></p>
<p>The <strong>Traits</strong> group maps to <a href="https://github.com/nunit/docs/wiki/Category-Attribute">NUnit's </a>Category Attribute which allows you to group your tests based on the categories you assign them.</p>
<h3>Running x86 or x64 Tests</h3>
<p>If your tests are compiled x86 or x64 instead of AnyCpu, you must set the processor architecture to run your tests under. To do so, click on <strong>Test | Test Settings | Default Processor Architecture</strong> menu and select X86 or X64.</p>
<h3>Playlists</h3>
<p>If you have a group of tests that you are always running, you should create a playlist for them. To do so, select the tests that you want to include in the <strong>Test Explorer Window</strong>, then right click and select <strong>Add to Playlist | New Playlist.</strong> Once you do so, you can filter the tests that are displayed and run but selecting the playlist from the dropdown at the top right.</p>
<p><img class="aligncenter size-full wp-image-680" src="/assets/img/2016/10/2016-10-20-22_23_50-IntroToNUnit-Microsoft-Visual-Studio.png" alt="Test Playlists" width="340" height="208" /></p>Rob ProuseMost .NET developers write code using Visual Studio, so it is convenient to be able to run and debug your NUnit tests from within Visual Studio. There are commercial products like TestDriven.NET, NCrunch and Resharper that can run your tests, but the NUnit Visual Studio Adapter is free and works in all current editions of Visual Studio. Installing the NUnit Visual Studio Adapter Visual Studio Extension The easiest way to install the NUnit Visual Studio Adapter is as an extension. This has the advantage that it is always available and it will automatically update to the latest versions as they are released. The disadvantage is that every person on your team will need to install it. To install, you can download the extension from the Visual Studio Gallery and double click the VSIX file to install it in all supported versions of Visual Studio. The second option is to go to the Tools | Extensions and Updates menu in Visual Studio. From here, click on Online and search for nunit adapter. You are looking for the NUnit 3 Test Adapter and install it. Notice there is an NUnit Test Adapter available too. That is the original adapter for running older NUnit 2 tests. If you have older tests, it is fine to install both NUnit test adapters side-by-side. NuGet Package The other option for installing the NUnit Visual Studio Adapter is as a NuGet package. This has the advantage that it becomes part of your solution and every developer will get it, but you must add it to every solution that needs it. To install, right click on your test project in Visual Studio and click on Manage NuGet Packages... Click on the Browse tab and search for nunit adapter. You are looking for NUnit3TestAdapter. Click it and install. Like the extension, there is also NUnitTestAdapter for running NUnit 2 tests. Note that you only have to install the adapter in one test project and it will be available for the entire solution. Running Tests using the Test Explorer Window You will usually run your tests using the Test Explorer Window. To open it, click the Test | Windows | Test Explorer menu. Running Tests After you build your solution, Visual Studio will populate the Test Explorer Window. If you don't see any tests, check the output window for errors. To run tests, simply click the Run All button in the upper left. You will see your tests run as the progress bar updates and your tests turn green. The Run... menu allows you to run failed tests, tests that have not been run before, etc. Right clicking on individual tests or groups of tests and clicking Run Selected Tests will run those tests. Debugging Tests Tests can be debugged from the Test Explorer Window. Add your breakpoints into your code and right click on individual tests or groups of tests, then click Debug Selected Tests. Debugging and running tests is often easiest from the source code you are working on. We'll cover that next. Running Tests from within the Source Code Editor The easiest way to run or debug tests from within the source code editor is to use the key bindings. Ctrl R, A - Run All Tests Ctrl R, Ctrl A - Debug All Tests Ctrl R, T - Run the tests at your cursor Ctrl R, Ctrl T - Debug the tests at your cursor Running the tests where your cursor is can be very useful since it runs the tests you are currently working on. When the cursor is in a method, it will run that method, if it is in a class, it will run all tests in the class. Visual Studio has trouble with multiple tests created using the TestCase attribute or other data attributes. Using the key-bindings while in these methods will run all tests in the class. Code Lens If your version of Visual Studio includes Code Lens, your tests will also have a small icon on the left of the code lens that indicates if the test passed, failed, was ignored or hasn't been run. Clicking that icon brings up information on the last test run and allows you to run or debug the test. Other Features Grouping Tests By default, Visual Studio groups tests in the Test Explorer Window by their outcome; pass, fail, etc. You can also group by Class, Duration, Traits or Project. To group your tests, either right-click on a group and select Group By or use the dropdown at the top left of the window. The Traits group maps to NUnit's Category Attribute which allows you to group your tests based on the categories you assign them. Running x86 or x64 Tests If your tests are compiled x86 or x64 instead of AnyCpu, you must set the processor architecture to run your tests under. To do so, click on Test | Test Settings | Default Processor Architecture menu and select X86 or X64. Playlists If you have a group of tests that you are always running, you should create a playlist for them. To do so, select the tests that you want to include in the Test Explorer Window, then right click and select Add to Playlist | New Playlist. Once you do so, you can filter the tests that are displayed and run but selecting the playlist from the dropdown at the top right.Using NUnit’s TestCase Attribute2016-10-17T04:36:58+00:002016-10-17T04:36:58+00:00https://alteridem.net/2016/10/17/nunit-testcase-attribute<p>In the last post, we setup an <a href="/2016/10/03/nunit-unit-tests/">NUnit test project and ran it in Visual Studio</a>. In this post we are going to expand on that code to add more unit tests using the NUnit TestCase attribute.</p>
<p>Looking back at the <a href="/2016/10/03/nunit-unit-tests/">last post</a>, we are testing a method that converts an enum value to a friendly string by splitting the enum name at capitals. In that post, we only tested with one enum value. In this post, we will test with multiple enum values to ensure that the method handles every type of input. We will then remove code duplication by using the <strong>[TestCase]</strong> attribute to run one test many times with different data.<!--more--></p>
<p>As always, the source code for <a href="https://github.com/rprouse/IntroToNUnit">this tutorial is on GitHub</a>.</p>
<h2>Testing Edge Cases</h2>
<p>When testing a method, it is important that we test as many variations of input as possible. In the <a href="/2016/10/03/nunit-unit-tests/">last post</a>, we only tested that an enum with multiple words could be converted to a sentence - we tested that the enum value <strong>UnitTesting</strong> would convert to the string <strong>"Unit Testing"</strong>, but we should also test that it works with a single word, multiple words starting with a lowercase letter and invalid values.</p>
<p>To do this, one approach is to add tests for each scenario like this,</p>
<pre class="lang-cs"><code>[Test]
public void CanConvertEnumIntoMultipleWords()
{
// Arrange/Act
var actual = TestTypes.UnitTesting.ToFriendlyString();
// Assert
Assert.That(actual, Is.Not.Null.And.EqualTo("Unit Testing"));
}
[Test]
public void CanConvertEnumIntoMultipleWordsWithFirstWordStartingWithLowerCase()
{
// Arrange/Act
var actual = TestTypes.integrationTesting.ToFriendlyString();
// Assert
Assert.That(actual, Is.Not.Null.And.EqualTo("Integration Testing"));
}
[Test]
public void CanConvertEnumSingleWord()
{
// Arrange/Act
var actual = TestTypes.Testing.ToFriendlyString();
// Assert
Assert.That(actual, Is.Not.Null.And.EqualTo("Testing"));
}
[Test]
public void CanConvertEnumSingleLowercaseWord()
{
// Arrange/Act
var actual = TestTypes.none.ToFriendlyString();
// Assert
Assert.That(actual, Is.Not.Null.And.EqualTo("None"));
}
</code></pre>
<p>Adding these tests revealed a bug in the implementation of the method where it doesn't work if the first word starts with a lowercase letter which required a change to the Regex in that method. It should also capitalize each word. This is why we need to test as many possibilities as possible.</p>
<h2>Using the TestCase Attribute</h2>
<p>Each of our test methods has nearly identical code, we convert an enum to a string value, then we check if the string is correct. If we could pass the enum and the expected string into the function, then we could reduce the tests down to one method.</p>
<p>For situations like this, NUnit has the <a href="https://github.com/nunit/docs/wiki/TestCase-Attribute">[TestCase] attribute</a>. You can apply the <strong>[TestCase]</strong> attribute multiple times to a method and it will create a new test for every instance passing the parameters from the TestCase attribute into the test method. Using this, we can reduce the four tests to one that looks like this,</p>
<pre class="lang-cs"><code>[TestCase(TestTypes.none, "None")]
[TestCase(TestTypes.Testing, "Testing")]
[TestCase(TestTypes.UnitTesting, "Unit Testing")]
[TestCase(TestTypes.integrationTesting, "Integration Testing")]
public void CanConvertEnumIntoFriendlyString(TestTypes value, string expected)
{
// Arrange/Act
var actual = value.ToFriendlyString();
// Assert
Assert.That(actual, Is.Not.Null.And.EqualTo(expected));
}
</code></pre>
<p>This simplifies our code and makes it easy to add new test cases. For example, if we want to see if our method handles single character enums, we could just add two new TestCases's</p>
<pre class="lang-cs"><code>[TestCase(TestTypes.a, "A")]
[TestCase(TestTypes.B, "B")]
</code></pre>
<p>We could also test for invalid values,</p>
<pre class="lang-cs"><code>[TestCase((TestTypes)10, "")]
</code></pre>
<h2>Other Parameters for TestCase</h2>
<h3>ExpectedResult</h3>
<p>One of the more popular properties on the TestCase attribute is ExpectedResult. When this is used, the return value of the test method is checked for equality with the <strong>ExpectedResult</strong>. This can reduce code because you do not have to assert equality, it is done automatically.</p>
<p>Converting the method that tests the parsing of the enums would reduce it to this,</p>
<pre class="lang-cs"><code>[TestCase((TestTypes)10, ExpectedResult = "")]
[TestCase(TestTypes.a, ExpectedResult = "A")]
[TestCase(TestTypes.B, ExpectedResult = "B")]
[TestCase(TestTypes.none, ExpectedResult = "None")]
[TestCase(TestTypes.Testing, ExpectedResult = "Testing")]
[TestCase(TestTypes.UnitTesting, ExpectedResult = "Unit Testing")]
[TestCase(TestTypes.integrationTesting, ExpectedResult = "Integration Testing")]
public string CanConvertEnumIntoFriendlyString(TestTypes value)
{
return value.ToFriendlyString();
}
</code></pre>
<h3>Common Parameters</h3>
<p>The <strong>[TestCase]</strong> attribute supports many other parameters that can modify your tests or add information to them. Some of the more common are,</p>
<ul>
<li><strong>Author</strong> identifies the author of the test</li>
<li><strong>Category</strong> provides a comma-delimited list of categories for this test</li>
<li><strong>Description</strong> sets the description property of the test</li>
<li><strong>TestName</strong> sets a test name instead of using the default generated name</li>
<li><strong>TestOf</strong> specifies the Type that this test is testing</li>
<li><strong>Explicit</strong> when set to true, the test can only be run explicitly. Use Reason to explain why</li>
<li><strong>Ignore</strong> causes the test to not be run and specifies the reason</li>
</ul>
<p>There are a few other parameters that you can use, see the <a href="https://github.com/nunit/docs/wiki/TestCase-Attribute">[TestCase] attribute documentation</a> for more information.</p>Rob ProuseIn the last post, we setup an NUnit test project and ran it in Visual Studio. In this post we are going to expand on that code to add more unit tests using the NUnit TestCase attribute. Looking back at the last post, we are testing a method that converts an enum value to a friendly string by splitting the enum name at capitals. In that post, we only tested with one enum value. In this post, we will test with multiple enum values to ensure that the method handles every type of input. We will then remove code duplication by using the [TestCase] attribute to run one test many times with different data. As always, the source code for this tutorial is on GitHub. Testing Edge Cases When testing a method, it is important that we test as many variations of input as possible. In the last post, we only tested that an enum with multiple words could be converted to a sentence - we tested that the enum value UnitTesting would convert to the string "Unit Testing", but we should also test that it works with a single word, multiple words starting with a lowercase letter and invalid values. To do this, one approach is to add tests for each scenario like this, [Test] public void CanConvertEnumIntoMultipleWords() { // Arrange/Act var actual = TestTypes.UnitTesting.ToFriendlyString();Introduction to Unit Tests with NUnit2016-10-03T16:31:08+00:002016-10-03T16:31:08+00:00https://alteridem.net/2016/10/03/nunit-unit-tests<p>You have a new project and you want to add unit tests, where do you start? This tutorial walks you through adding an <a href="http://nunit.org/">NUnit</a> test project, writing your first tests and running them in Visual Studio.</p>
<p>This walk-through assumes you already have a project that you want to test. I am starting here with a project that contains a simple class that contains an extension method that converts an enum value to a friendly string by splitting the enum name at capitals. For example, System.Windows.Forms.Keys.BrowserBack would become "Browser Back".<!--more--></p>
<p>The source code for <a href="https://github.com/rprouse/IntroToNUnit">this tutorial is on GitHub</a>.</p>
<h2>Add a Unit Test Project</h2>
<p>It is best practice to keep your unit tests separate from your production code, so we will add a new project that contains our tests. It is also common to name your test project the same as the project it is testing and appending <strong>.Tests</strong>. My main project is <strong>IntroToNUnit</strong>, so I will add <strong>IntroToNUnit.Tests</strong>.</p>
<ol>
<li>Right click on your solution in Visual Studio</li>
<li>Click on <strong>Add | New project...</strong></li>
<li>Click on <strong>Visual C# | Windows</strong> and click on <strong>Class Library.</strong></li>
<li>Enter the name of your test project and click <strong>OK</strong>.</li>
</ol>
<p><img class="aligncenter wp-image-634 size-full" src="/assets/img/2016/10/2016-10-03-16_23_21-Add-New-Project.png" alt="Add new unit test project" width="795" height="497" /></p>
<h2>Add a Reference to NUnit</h2>
<p>Before you can write unit tests, you need to add a reference to a test framework, in this case NUnit.</p>
<ol>
<li>Right click on your unit test project</li>
<li>Click on <strong>Manage NuGet packages...</strong></li>
<li>Click on <strong>Browse</strong></li>
<li>Select <strong>NUnit</strong> and click the <strong>Install</strong> button. At the time of this writing, NUnit is number three in the list. If that changes, use the search bar to find it.</li>
</ol>
<p><img class="aligncenter wp-image-636 size-full" src="/assets/img/2016/10/2016-10-03-16_31_47-IntroToNUnit-Microsoft-Visual-Studio.png" alt="Add reference to NUnit" width="792" height="414" /></p>
<h2>Add a Reference to Your Project</h2>
<p>In order to test the code in your main project, you need to add a reference to it in your test project.</p>
<ol>
<li>Right click on your test project</li>
<li>Click on <strong>Add | Reference...</strong></li>
<li>Select <strong>Projects | Solution</strong></li>
<li>Add a checkmark on your main project.</li>
<li>Click <strong>OK</strong>.</li>
</ol>
<p><img class="aligncenter size-full wp-image-638" src="/assets/img/2016/10/2016-10-03-16_38_46-Reference-Manager-IntroToNUnit.Tests_.png" alt="Add Project Reference" width="686" height="343" /></p>
<h2>Write Unit Tests</h2>
<p>Another common convention is to name the test class the same as the class being tested with Tests appended. The class I want to test is called <strong>EnumToStringConverter.cs</strong>, so I rename <strong>Class1.cs</strong> to <strong>EnumToStringConverterTests.cs</strong>.</p>
<p>To this class, I add the <strong>[TestFixture]</strong> attribute. You also need to add the <strong>using NUnit.Framework</strong>. My first test is going to make sure that the converter splits multiple words correctly, so I add a test enum and the first unit test. Add this point, my code looks like this.</p>
<pre><code class="csharp">using NUnit.Framework;
namespace IntroToNUnit.Tests
{
public enum TestTypes
{
None,
UnitTesting,
IntegrationTesting,
FlyByTheSeatOfYourPantsTesting
}
[TestFixture]
public class EnumToStringConverterTests
{
[Test]
public void CanConvertEnumIntoMultipleWords()
{
}
}
}
</code></pre>
<p>Notice that my test method is public and returns void and that it has a <strong>[Test]</strong> attribute to identify it as a test. You can have more complicated test methods which I will cover in future posts.</p>
<h2>Arrange, Act, Assert</h2>
<p>Now it is time to write the first unit test. The most common structure is known as <a href="http://c2.com/cgi/wiki?ArrangeActAssert">Arrange, Act, Assert</a>. What this means is that you group the code in your test method into setting up for the test (Arrange), then you perform the action that you want to test (Act), then you check the results (Assert). Sometimes you will find that the arrange and act steps are combined for simpler tests as in this case. That is fine.</p>
<pre><code class="csharp">[Test]
public void CanConvertEnumIntoMultipleWords()
{
// Arrange/Act
var actual = TestTypes.UnitTesting.ToFriendlyString();
// Assert
Assert.That(actual, Is.EqualTo("Unit Testing"));
}
</code></pre>
<p>In this test, I have executed the code that I want to test, then I asserted what I expected the value to be. The <strong>Assert</strong> class is provided by NUnit and allows check many conditions in your tests. In this case I am only checking that the string returned is equal to what I expected. I will cover more types of NUnit Asserts in a later post.</p>
<p>NUnit has two assert syntaxes. In the example code, I used the <a href="http://Constraint Model">Constraint Model</a> or sometimes the Fluent Syntax. It is called the fluent syntax because it reads very much like English and because you can continue to append extra conditions. For example, I could have also checked for null with,</p>
<pre><code class="csharp">Assert.That(actual, Is.Not.Null.And.EqualTo("Unit Testing"));</code></pre>
<p>NUnit also has a <a href="https://github.com/nunit/docs/wiki/Classic-Model">classic model/syntax</a> that you are likely to see in other tutorials. The above Assert could also be written as,</p>
<pre><code class="csharp">Assert.NotNull(actual);
Assert.AreEqual("Unit Testing", actual);
</code></pre>
<p>Some people prefer the classic syntax, but I recommend that you use the fluent syntax. New features in NUnit are always added to the fluent syntax and only rarely get added to the classic syntax.</p>
<h2>Run the Unit Tests in Visual Studio</h2>
<p>To run your unit tests in Visual Studio, you first need to install the <a href="https://visualstudiogallery.msdn.microsoft.com/0da0f6bd-9bb6-4ae3-87a8-537788622f2d">NUnit 3 Test Adapter</a>. To do so,</p>
<ol>
<li>In the main menu, click <strong>Tools | Extensions and Updates...</strong></li>
<li>Click on <strong>Online | Visual Studio Gallery</strong>,</li>
<li>Search for <strong>NUnit</strong> and install <strong>NUnit 3 Test Adapter</strong></li>
<li>After you install, click the button at the bottom to <strong>Restart</strong> Visual Studio</li>
</ol>
<p><img class="aligncenter size-full wp-image-643" src="/assets/img/2016/10/2016-10-03-17_18_57-Extensions-and-Updates.png" alt="Add NUnit Visual Studio Adapter" width="782" height="325" /></p>
<p>Back in Visual Studio with your solution open, you need to open the <strong>Test Explorer Window</strong>. To do this, in the main menu, click <strong>Test | Windows | Test Explorer</strong>.</p>
<p>The window that opens will list your unit tests and allow you to run or debug them. Click <strong>Run All</strong> to run your tests. Successful tests will go green and failed tests will be red. You can see the results of any test by clicking on it and viewing the results at the bottom of the window. In a future post, I will cover other ways to run your tests and how to use the Test Adapter in Visual Studio in more detail.</p>
<p><img class="aligncenter size-full wp-image-645" src="/assets/img/2016/10/2016-10-03-17_30_21-IntroToNUnit.png" alt="Test Explorer" width="655" height="233" /></p>
<p>Congratulations, you have your first unit test.</p>Rob ProuseYou have a new project and you want to add unit tests, where do you start? This tutorial walks you through adding an NUnit test project, writing your first tests and running them in Visual Studio. This walk-through assumes you already have a project that you want to test. I am starting here with a project that contains a simple class that contains an extension method that converts an enum value to a friendly string by splitting the enum name at capitals. For example, System.Windows.Forms.Keys.BrowserBack would become "Browser Back". The source code for this tutorial is on GitHub. Add a Unit Test Project It is best practice to keep your unit tests separate from your production code, so we will add a new project that contains our tests. It is also common to name your test project the same as the project it is testing and appending .Tests. My main project is IntroToNUnit, so I will add IntroToNUnit.Tests. Right click on your solution in Visual Studio Click on Add | New project... Click on Visual C# | Windows and click on Class Library. Enter the name of your test project and click OK. Add a Reference to NUnit Before you can write unit tests, you need to add a reference to a test framework, in this case NUnit. Right click on your unit test project Click on Manage NuGet packages... Click on Browse Select NUnit and click the Install button. At the time of this writing, NUnit is number three in the list. If that changes, use the search bar to find it. Add a Reference to Your Project In order to test the code in your main project, you need to add a reference to it in your test project. Right click on your test project Click on Add | Reference... Select Projects | Solution Add a checkmark on your main project. Click OK. Write Unit Tests Another common convention is to name the test class the same as the class being tested with Tests appended. The class I want to test is called EnumToStringConverter.cs, so I rename Class1.cs to EnumToStringConverterTests.cs. To this class, I add the [TestFixture] attribute. You also need to add the using NUnit.Framework. My first test is going to make sure that the converter splits multiple words correctly, so I add a test enum and the first unit test. Add this point, my code looks like this. using NUnit.Framework;