Unit Testing with nUnit

10792282_sFirst, go to artofunittesting.com/ and watch the videos, then read the book: “The Art of Unit testning” (second edition)

Use NuGet to import nUnit into your project. Use code templates to work faster.

Follow these naming conventions:

  • Create a seperate project for the test classes – name it <yourprojectname>.UnitTests
  • Make a test class for each class you want to test – name them <ClassName>Tests
  • Each test method should be named like this:
    <UnitOfWorkName>_<ScenarioUnderTest><ExpectedBehaviour>

The test method is structured into three stages

  1. Arrange (setting up the objects)
  2. Act (call the method to test)
  3. Assert (check the result)

Notice the difference between unit test and integration test:

  • A unit test is small, fast and easy to make and maintain. Checks if an individuel piece of code works. Every time you run the unit you will get the same result – even if you run it after a year (no configuration is required, no dependencies to e.g. external data, the system time or random numbers)
  • Intregration test are slower and more compleks. Typically checks if the integration between systems works as intended (Checks if several units actually works together)

Notice: nUnit has a very strong feature called TestCase – use it whenever it makes sense.

Testing for error exceptions

 var ex = Assert.Throws<ArgumentException>(() => foo.DoSomething() );
 StringAssert.Contains("Actual exception message", ex.Message);

Test runnners

I use the test runner provided with ReSharper, but you can use the built-in runner in Visual Studio, TestDriven.net or the one provided with nUnit

Tips from Osherove

“Readability is one of the most important aspects when writing a test”

Best practice: Tests must run totally independent of each other

Source Control with GIT and BitBucket

gitSource Control: Trust me on this – you do need it! The best tool is GIT – and it’s free  :-) Add BitBucket (or GitHub) and your code will be backed-up and accessible from everywere.

Native GIT runs from a command prompt, so store your projects in a folder close to the root, e.g. C:\dev\projectname

Beware: To use GIT you must understand GIT – get the full story in this guide, or start with this tutorial

I use GIT on my own projects, making hourly commits and daily pushes to BitBucket. If I need to branch or merge code, I use the tools in BitBucket or GIT Extensions

FIrst-time installation and configuration

  1. Download and install GIT (Installation guide)
  2. Setup GIT – apply your username and email address by using these commands:
     $ git config --global user.name "John Doe"
     $ git config --global user.email johndoe@example.com
     

    or just manually update the .gitconfig file (in your local folder, e.g. C:\Users\$USER). My file looks like this

     [user]
     name = Jakob Majkilde
     email = jakob@majkilde.dk
     [http]
     proxy = http://80.254.148.90:8080
     [core]
     autocrlf = true
     excludesfile = c:/dev/.gitignore
     

    Notice: only the [user] is mandatory – other settings are optional

  3. Add a .gitignore file to automatically exclude files that you do not want in your repository (e.g. .exe files or log files). Read the documentation for more info. I have my ignore file in my developement folder and made it global

Starting a new project

  1. Open a command prompt, goto your project folder and type GIT init (this will create a hidden sub folder called .git)

Often used commands

  • Add files: GIT add -A
  • Commit: GIT commit -m “Type a message here”
  • Status: GIT status
  • Commit log: GIT Log
    git log --graph --pretty --oneline --abbrev-commit

Push to a remote repository (e.g.BitBucket)

  • Connect: git remote add origin https://majkilde@bitbucket.org/majkilde/<project name>.git (url can be copied from your bitbucket repository)
  • Push: git push -u origin master
  • Pull: git pull origin master 

Links

Log4net

12132866_sAll programs should be able to log. With log4net this is made easy. Start with this great tutorial.

Quick guide:

log4net has a lot of settings and features. This sample shows how to log to a simple text file with some default settings

1. Use NuGet to install log4net in your project

2. In the App.config file, add this section of code:


<?xml version="1.0"?>
<configuration>
 <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 </configSections>

<log4net>
 <!-- levels: ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
 <root>
 <level value="INFO" />
 <appender-ref ref="FileAppender" />
 </root>

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender, log4net" >
 <param name="File" value="Log.txt" />
 <param name="AppendToFile" value="false" />
 <param name="maximumFileSize" value="200KB" />
 <param name="maxSizeRollBackups" value="1" />

<layout type="log4net.Layout.PatternLayout, log4net">
 <conversionPattern
 value="%date{yyyy.MM.dd hh:mm:ss} %-5level [%thread] - %message%newline" />
 </layout>
 </appender>
 </log4net>

</configuration>

3. You need 3 lines of code

First, just below the using statements

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Then in every class, add this line

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Now you are ready to log

log.Info("Hello World");

Links

Recommended books

15561327_sHere are some books that every programmer should read:

And for the C# programmer

Code Snippets

14116418_s

You can use code snippets to type a short alias, and then expand it into a common programming construct. For example, the for code snippet creates an empty for loop

  • Follow this guide to create a Code Snippet in Visual Studio.
  • Snippets are even easier to create and more efficient, with Resharper Live Templates

I have included my favorite snippets:

  • nUnit test method
    
    [Test]
     public void $UnitOfWork$_$StateUnderTest$_$ExpectedBehavior$()
     {
        $END$
     }
    
    
  • Log4net code to be used in every class
    
    private static readonly log4net.ILog log =
     log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    
    

Visual Studio Shortcuts

15667664_sMy favorite shortcuts in Visual Studio

  • Shift+Alt+Enter: Maximize the code view
  • Alt+Mouse select: mark a box of text
  • Ctrl+X: Delete a line

Editor commands

  • Ctrl E+D: Format Document
  • Ctrl E+C: Comment selection or Ctrl E+U for Uncomment a selection (With ReSharper this is changed to Ctrl K+C and Ctrl K+U)