Stubbing a method with multiple return values

This is how you can stub a method to return different values on each call.

TestPublishNewStandsLogResultIndex is the indexer that indicates which result is the next in line.

WhenCalled is the rhinoMocks way of accessing this predefined list.


using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FloorPlanning.Framework.Logging;
using FloorPlanning.Service.Controllers.ApiControllers.v1;
using Rhino.Mocks;

namespace Service.Tests.Handlers
    public class MyControllerTest
        private static int TestPublishNewStandsLogResultIndex;

        private static readonly List<LogEntry> TestPublishNewStandsLogResults = new List<LogEntry>
            new LogEntry
                Id = 32,
            new LogEntry
                Id = 55,

        private IOperationLogHandler operationLogHandler;

        public void Setup()
              operationLogHandler = MockRepository.GenerateMock<IOperationLogHandler>();

        public void PublishNewStandsSuccessful()
            operationLogHandler.Stub(m => m.GetLatestLogEntryForOperation(Operation.PublishStandUpdates))
                .WhenCalled(mi => mi.ReturnValue = TestPublishNewStandsLogResults[TestPublishNewStandsLogResultIndex++]);

            var controller = new PublishingController(operationLogHandler);

            var result = controller.Stands();

            //...asserts here


Differences between syntax of Nunit & MStest

Differences between syntax of Nunit & MStest

These are the main differences in terminology:

MSTest Attribute

NUnit Attribute


[TestMethod] [Test] Indentifies of an individual unit test
[TestClass] [TestFixture] Identifies of a group of unit tests, all Tests, and Initializations/Clean Ups must appear after this declaration
[ClassInitialize] [TestFixtureSetUp] Identifies a method which should be called a single time prior to executing any test in the Test Class/Test Fixture
[ClassCleanup] [TestFixtureTearDown] Identifies a method in to be called a single time following the execution of the last test in a TestClass/TestFixture
[TestInitialize] [SetUp] Identifies a method to be executed each time before a TestMethod/Test is executed
[TestCleanup] [TearDown] Identifies a method to be executed each time after a TestMethod/Test has executed
[AssemblyInitialize] N/A Identifies a method to be called a single time upon before running any tests in a Test Assembly
[AssemblyCleanUp] N/A Identifies a method to be called a single time upon after running all tests in a Test Assembly


NUnit and RhinoMocks testing template (Visual Studio)

NUnitTest visual studio template project

nunit template for VS2010

here is the template for nunit (from: )

download: TestClassLibrary or a test example project

copy to : C:\Users\pete\Documents\Visual Studio 2010\My Exported Templates

all i did was export it from file-export template – and this is what was rendered

it’s in visual c# > called: testclasslibrary



public class Class1
    public void test1()

Unit test an Exception

Testing an exception as follow:

public void TestCorrectErrorTypeAndMessage()
    var ex = Assert.Throws<Exception>(
                    , () =>
    Assert.AreEqual("error123", ex.Message);

public void DoThis()
    throw new Exception("error123");

Another real example:

public void MustHaveMetricsBeforeTakeSnapshot()
    var snapshotTaker = new SnapshotTaker();
        snapshotTaker.DataPoints = dataPoints;
        var ex = Assert.Throws<Exception>(() =>
    Assert.IsTrue(ex.Message.Contains("must provide"), "incorrect error message");

jQuery & jQuery.UI available test

The following code block:

    if (typeof jQuery != 'undefined') {
        // jQuery is loaded => print the version
    } else {
        alert('jQuery is NOT loaded');

    $(document).ready(function() {
        if (jQuery.ui) {
        } else {
            alert('jQuery.UI is NOT loaded!!');

will either print the JQuery version or inform you if no JQuery library is found.
also warn if jQueryUI is not loaded

Unit test protected methods using Rhino mocks

If your method is in a different assembly then you need to allow access to your own assembly (e.g MyAssembly) and e.g. Rhino mocks () or whatever you use for mocking

you can do so:

[assembly: InternalsVisibleTo("MyAssembly")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

then your unit test would look something like this:

public void TestMethod1()
    var txt = "testdata";
    var rawRequestProcessor = MockRepository.GenerateStub<RawRequestProcessor>();
    Assert.AreEqual(txt, rawRequestProcessor.RawInput);
    rawRequestProcessor.Expect(m => m.processInput());

example of the code being tested here:

public class RawRequestProcessor
    public void Process(string txt)
        RawInput = txt;

    private string _rawInput;
    public string RawInput {
        get { return _rawInput; }
            _rawInput = value;

    internal virtual void processInput()



Unit Testing Cross Assemblies with “internal” declarations

The steps to allow access to external assemblies mainly for testing purposes:

  1. Navigate to your tests assembly / project.
  2. double click on the properties folder.
  3. copy the full assembly name - e.g. Bitlink.Chess.OpeningExplorer.Tests
  4. go to your assembly that you want to test (the one which uses internal declarations)
    in my case: Bitlink.Chess.OpeningExplorer.Library
  5. expand the properties folder, locate and open AssemblyInfo.cs
  6. at the very bottom of this file, put a reference to your test assembly, e.g.:
    [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bitlink.Chess.OpeningExplorer.Tests")]

if you have signed your assemblies, you would need a further signature:

[assembly: InternalsVisibleTo("...Tests")] , PublicKey=……

for that you could extract the public key token of your keyfile over two steps

  1. extract the public key from the keyfile with
    sn –p <keyfile.snk> <keyfile.snk.PublicKey>
  2. show the public key token with
    sn -t <keyfile.snk.PublicKey>

or use the GetPublicKey utility that’s going around:  download GetPublicKey

[Resolved!] System.BadImageFormatException: The format of the file ‘xxx’ is invalid

I got the following error during unit testing.
System.BadImageFormatException: The format of the file ‘xxx’ is invalid

reason was that the project I tested was X86 but my testing application was “Any CPU”

ensure that all your projects compile to the same platform, for example:
double click on your “properties” folder
set all individual platforms targets (of all your projects) to e.g. x86

that should resolve it.

– any other issues / solutions, please post below!


watir send keys

<code> browser.send_keys("{ENTER}") </code>

To do the same thing in Watir-WebDriver, you do this:

<code> browser.send_keys :enter </code>

You can also do things like this:

<code>browser.element.send_keys [:control, 'a'], :backspace</code>

The full list of keys are available from here:

  • :null
  • :cancel
  • :help
  • :backspace
  • :tab
  • :clear
  • :return
  • :enter
  • :shift
  • :left_shift
  • :control
  • :left_control
  • :alt
  • :left_alt
  • :pause
  • :escape
  • :space
  • :page_up
  • :page_down
  • :end
  • :home
  • :left
  • :arrow_left
  • :up
  • :arrow_up
  • :right
  • :arrow_right
  • :down
  • :arrow_down
  • :insert
  • :delete
  • :semicolon
  • :equals
  • :numpad0
  • :numpad1
  • :numpad2
  • :numpad3
  • :numpad4
  • :numpad5
  • :numpad6
  • :numpad7
  • :numpad8
  • :numpad9
  • :multiply
  • :add
  • :separator
  • :subtract
  • :decimal
  • :divide
  • :f1
  • :f2
  • :f3
  • :f4
  • :f5
  • :f6
  • :f7
  • :f8
  • :f9
  • :f10
  • :f11
  • :f12
  • :meta
  • :command