Thursday, April 28, 2005

Tasc Unit Testing Pattern

Often when unit testing you need a concrete class that is a stub for an abstract class you are testing. However, instead of creating a class strictly for the stub purpose you can use your test class and thus have less artifacts to maintain. The class is a [T]est [A]nd [S]tub [C]lass.

Consider an abstract class that generates an id on first access if it has not previously been set:

public abstract class DomainBase
{
private Guid _id;
public Guid Id
{
get
{
if (_id==Guid.Empty)
{
_id=Guid.NewGuid();
}
return _id;
}
set { _id = value }
}
}

The test then becomes:

[TestFixture]
public class DomainBaseTasc : DomainBase
{
[Test]
public void EnsureIdIsGenerated()
{
DomainBaseTasc tasc = new DomainBaseTasc();
Assert.IsTrue(tasc.Id!=Guid.Empty);
}

[Test]
public void EnsureIdIsOnlyGeneratedOnFirstAccess()
{
DomainBaseTasc tasc = new DomainBaseTasc();
Assert.IsTrue(tasc.Id==tasc.Id);
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.