Vlad's blog

In programming veritas

Posts Tagged ‘TDD

Creating unit tests with Rhino.Mocks

leave a comment »

When you write unit tests you often need to create stubs for classes, interfaces and methods used in method which is tested. This task is tedious because you usually have to write a lot of code. One way how to automate this process is use isolation framework. One of the most popular isolation frameworks in .Net is Rhino Mocks.
For the sake of demonstration suppose we develop a system for collecting telemetry data from remote analogue devices. A device is represented by the following class.

public class Analog
{
    public string Name { get; set; }
    public double Value { get; set; }
    public double LowLimit { get; set; }
    public double HiLimit { get; set; }
}

LowLimit and HiLimit properties define low and high alarm limit respectively. If current value is greater or equal to HiLimit the High alarm will be generated. Similarly, if value is less or equal to LowLimit a system will generate the Low alarm. Alarm is represented by the following class.

public class Alarm
{
    public string AnalogName { get; set; }
    public string Description { get; set; }
}

Data Access Layer defined by the following interfaces.

public interface IAnalogDao
{
    Analog Find(string name);
    void SaveChanges(Analog a);
}

public interface IAlarmDao
{
    void AddAlarm(Alarm alarm);
}

public interface IAlarmFactory
{
    Alarm CreateAnalogHiAlarm(string name, double value);
    Alarm CreateAnalogLowAlarm(string name, double value);
}

Our goal is to implement AnalogProcessor class that is responsible for alarms generation.

public class AnalogProcessor
{
    private IAlarmDao _alarmDao;
    private IAlarmFactory _alarmFactory;
    private IAnalogDao _analogDao;

    public AnalogProcessor(IAlarmDao alarmDao, IAlarmFactory alarmFactory, IAnalogDao analogDao)
    {
        _alarmDao = alarmDao;
        _analogDao = analogDao;
        _alarmFactory = alarmFactory;
    }

    public void Process(string name, double value)
    {
        Analog a = _analogDao.Find(name);

        if (a != null)
        {
            if (value >= a.HiLimit)
            {
                Alarm alarm = _alarmFactory.CreateAnalogHiAlarm(a.Name, value);
                _alarmDao.AddAlarm(alarm);
            }
            if (value <= a.LowLimit)
            {
                Alarm alarm = _alarmFactory.CreateAnalogLowAlarm(a.Name, value);
                _alarmDao.AddAlarm(alarm);
            }

            a.Value = value;
            _analogDao.SaveChanges(a);
        }
    }
}

Read the rest of this entry »

Written by vsukhachev

September 19, 2011 at 8:09 am

Posted in Development

Tagged with ,