About Me

Tuesday, February 22, 2011

How to make Moq object to return different values on each invocation

Today I stacked with the issue how to make Moq function to return different values when its calling by testing unit.

Let's see on example:
[Test]
public void Value_should_be_assigned_on_property_value()
{
///Arrange
...
DrugAgreement agreement = new DrugAgreement();

agreementsManager.Setup(f => f.Create()).Returns(agreement);

///Action
testingUnit.AssignPropertyOnNewlyCreatedObject("propertyValue");

///Assert
Assert.AreEqual("propertyValue", agreement.TestingProperty);
}

The code above expecting that the testing unit will create new instance of the object by calling Create, and change its TestingProperty value to propertyValue

Now, let's implement the code for it:
public DrugAgreement AssignPropertyOnNewlyCreatedObject(string newValue) {
    var obj = manager.Create();
    obj.TestingProperty = newValue;
    return obj;
}

The code above will work as expected.
Now imagine that we mistakenly called Create for the second time after the property was set:
public DrugAgreement AssignPropertyOnNewlyCreatedObject(string newValue) {
    var obj = manager.Create();
    obj.TestingProperty = newValue;
    obj = manager.Create();
    return obj;
}

For the first look, the test above should fail, but it is not!
The test says that TestingProperty is equal to propertyValue, but the object is different. We called Create for the second time and expecting that manager is stateless and don't remember previously returned instance.
The answer is simple - our mock manager returns the same instance of object every time when Create is calling.

So, how to test this ?
How to make sure that Create method is stateless and always returns different objects?

Here is the corrected test:

[Test]
public void Value_should_be_assigned_on_property_value()
{
    ///Arrange
    ...
    DrugAgreement agreement = new DrugAgreement();

    agreementsManager.Setup(f => f.Create()).Returns(agreement).Callback(()=> agreement = new DrugAgreement());

    ///Action
    testingUnit.AssignPropertyOnNewlyCreatedObject("propertyValue");

    ///Assert
    Assert.AreEqual("propertyValue", agreement.TestingProperty);
}

If we test our code now it will fail as it should.
As you can see, the difference in the test is in calling Callback function by moq manager . That function instantiates new instance of DrugAgreement class after each call.

In this case our manager is really stateless and always return different instances

Wednesday, February 16, 2011

Dynamic windows service name

Today i had to install few instances of the same windows service.
Of course they should be named differently.

I found that the name should be set to the ServiceName property of service installer.
This means, that i need to pass a name of the service when I installing it.

I found few solutions, but the most usefull for me, is when the installing is asking me for exact name before it installs the service.
Here is the code that should be placed into the service installer codebehind file (in my case it is ProjectInstaller.cs):
[RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

  private void BeforeInstallEventHandler(object sender, InstallEventArgs e)
  {

   // Add steps to perform any actions before the install process.

   Console.WriteLine("BeforeInstallEventHandler Called");

   Console.WriteLine("Enter the name you would like this service installed as:");

   serviceInstaller.ServiceName = Console.ReadLine();

   PersistServiceName(serviceInstaller.ServiceName);

   Console.WriteLine("Attempting to install service as: " + serviceInstaller.ServiceName);

  }

  private void BeforeUninstallEventHandler(object sender, InstallEventArgs e)
        {

            Console.WriteLine("BeforeUninstallEventHandler Called");

            serviceInstaller.ServiceName = RetrieveServiceName();

            // Add steps to perform any actions before the Uninstall process.

            Console.WriteLine("Code for BeforeUninstallEventHandler");

        }

  /// 
  /// Storing name of the service to the 
  /// config file, for using duing uninstall
  /// process
  /// 
        private void PersistServiceName(string serviceName)
        {

            TextWriter tw = new StreamWriter("Service.config", false);      

            tw.WriteLine(serviceName);

            tw.Close();

        }

  /// 
  /// Getting stored service name from
  /// the file during uninstall process
  /// 
  /// 
        private string RetrieveServiceName()
        {

            string serviceName;


            TextReader tr = new StreamReader("Service.config");

            serviceName = tr.ReadLine();

            tr.Close();

            Console.WriteLine("ServiceName" + serviceName);

            return serviceName;      
        }
    }

Project installer has few events. The code above is using two of them - BeforeInstallEventHandler and BeforeUninstallEventHandler. First one is using to ask the user the service name and store it to the config file.
The second one is using during uninstallation process to retrieve service name from the file and pass it to uninstall process.
Thus, don't forget to open ProjectInstaller.cs designer and assign its BeforeInstall and BeforeUninstall events with appropriate handlers (BeforeInstallEventHandler and BeforeUninstallEventHandler)

Thursday, January 20, 2011

WatiN UI testing of autocomplete textbox created with jquery.autocomplete

While writing UI tests for one web project, I were faced with the trouble.
There is a textbox on the page where user can type first letters and the system shows all possible values that can be selected by the user.
On the client side it was created with jquery.autocomplete:


I'm using WatiN library for writing UI tests and the regular approach, that I tried to use was not working.
Below is the code that emulates inserting of character 'a' then waits for autocomplete textbox appears and select first item:

IE _ie = new IE("URL-of-the-page-with-autocompleter");

//Typing letter 'a' and emulates keyboard
_ie.TextField("VendorName").TypeText("a");
_ie.TextField("VendorName").KeyDown();

//Wait while autocomplete making AJAX call
//and open the results
_ie.Div(f => !string.IsNullOrEmpty(f.ClassName) 
    && f.ClassName == "ac_results").WaitUntilExists(6);

//Selecting first item
_ie.Div(f => !string.IsNullOrEmpty(f.ClassName) 
    && f.ClassName == "ac_results")
    .ElementsWithTag("ul")
    .FirstOrDefault()
    .Click();

_ie.WaitForComplete();
The second line of code is important. KeyDown method for the textfield should be called to make autocompleter show search results.

Tuesday, January 11, 2011

How to create a single-instance windows application in .NET

Today I found really good and simple way how to create single-instance windows application in .NET.
By meaning single-instance i mean the application that can't be launched twice at the same time.

The way is using Mutex object that is in System.Threading namespace:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace SingleToneApplication
{
 static class Program
 {
  private const string APP_ID = "f87f4871-fc32-4032-82f6-ba3b3026faa4";
  /// 
  /// The main entry point for the application.
  /// 
  [STAThread]
  static void Main()
  {
            bool isItFirstInstance;
   
   using (Mutex m = new Mutex(true, APP_ID, out isItFirstInstance)) 
   {
    if (!isItFirstInstance) {
     MessageBox.Show("There is already an instance running!");
     return;
    }

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());

   }

  }
 }
}

As you may see, the code creating new Mutex object and pass APP_ID parameter.
The APP_ID is just a string that may contain any text. The main rule is that the text must be unique. I decided to use GUID for it.

As said on Microsoft site : "Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex." Since each application is using separate thread, we may use this way.

isItFirstInstance property is initializing by the constructor. Returned value indicates that the Mutex with specified unique name was created or not. So, if the returned value is false, then the mutex was already created in another application.
Then we may use this flag to decide, do we need to run the application or exit.

Wednesday, December 29, 2010

Why abstract method can't be private

Not so far ago I had to use abstract class for one business implementation.
I quickly typed the construction of abstract class and then found that the intelisense mark some code as invalid:
My first question was "Why?!".
Why abstract method can't be private ?

Here is the answer that came into my brain in the next second:

Abstract clause means that the method should be overriden in the classes that are inheriting from the base class.
In this case, each inheritor from Foo class should implement Method1, Method2 and Method3
Inheritor, can see only public and protected members of the base class. 
So, there is no way to implement Method3 because it marked as private.

No need to remember all the rules about all that OOP tricks in .NET, its only need to use your brain and ask "Why?" at the right moment. There is always logical explanation for it.

Monday, December 13, 2010

"Could not load file or assembly 'Castle.Core, Version=1.0.3.0 ...' or one of its dependencies...." issue

Today I got this error during configuring IoC container based on Windsor library.

We are working as team on this project, and when i got this error, i started to think that somebody mistakenly changed the version of the library.
After review, i found that all libraries has correct version. We are already using version 2.5.1.0 of that library and there are no places in the project's code or configuration files where it may referense to the old version of Core library.
I had to spend an hour to realize that the problem is not with version of the library but with components configuration.

We had to use forwarded types and some namespaces was specified wrong.
So, I've just changed a namespace for IReportRepository and IUserRepository to the correct one and it started working properly

Wednesday, December 1, 2010

How to write unit test for DateTime.Now

Yesterday I tried to use test driven development (TDD) to create logic for the application I'm working on.

One of requirements was to make the module to set the date when the object was modified.
The object has a property UpdatedOn and i needed to write a test that checks setting of DateTime.Now value for it.

The problem is, regular solution like the one below, will not work:


Assert.AreEqual(DateTime.Now, someObject.UpdatedOn);

The reason of why that example will always failed, is because the result of execution of DateTime.Now in Assert and DateTime.Now in business logic will be always different.
There will be few miliseconds between them and the test will always failed.

Here is what i used instead:


Assert.That(someObject.UpdatedOn, Is.EqualTo(DateTime.Now).Within(1).Seconds);