views:

27

answers:

1

I'm using NHibernate for data access. I'm working on writing some tests for my data access layer and have a scenario where I'm selecting records within a specific date range.

In test, I generate test data by just selecting random dates within a range and then I try to select records with dates within a subset o that range. For instance, I generate records with dates between yesterday and tomorrow, then I select only records that have a date of today.

The problem is that these dates are usually generated by the DB -- they are set to generated="insert" basically. Is there a way to set up NHibernate such that it uses the DB-generated a date when one isn't supplied by the user?

If not, anyone have a strategy for mitigating this during testing?

A: 

Initialize the DateTime property on your entity to DateTime.Now when it is constructed. Give it a protected setter, and in your test code implement a derived type which exposes a method to set it.

eg

public class RealEntity
{
    public virtual int Id { get; private set;}
    ...
    public virtual DateTime Created { get; protected set; }
}

[TestFixture]
public class SomeTest
{
    ...

    public class Testable : RealEntity
    {
        public void SetCreatedDate(DateTime date)
        {
            Created = date;
        }
    }
}
mattk
I find exposing private/protected stuff dubious. The way you suggest you couple the test with internal structure of the class being tested. Basically you test `Testable` rather then `RealEntity` thus defeating the whole idea of unit testing.
Ihor Kaharlichenko
To say it "defeats the whole idea of unit testing" is extreme. The option I proposed is a workaround for a common problem encountered when working with nhibernate, or anything else that sets properties with non-public setters using a proxy class (or reflection). Subclassing the class under test as I propose emulates what nhibernate does with dynamic proxy so the instance can be put in a state as if it were hydrated by nhibernate, and leaves all other behaviour unchanged. It is not ideal and I am keen to hear alternatives, but it is workable.
mattk