While writing unit test, we always say that we need to ensure that code is always isolated from external dependencies. Below Moq has been used to provide a mocked object instead of a valid fluent nhibernate Session Factory.
public class and_saving_a_invalid_item_type :
when_working_with_the_item_type_repository
{
private Exception _result;
protected override void Establish_context()
{
base.Establish_context();
_sessionFactory = new Mock<ISessionFactory>();
_session = new Mock<ISession>();
_sessionFactory.Setup(sf => sf.OpenSession()).Returns(_session.Object);
_itemTypeRepository = new ItemTypeRepository(_sessionFactory.Object);
_session.Setup(s => s.Save(null)).Throws(new ArgumentNullException());
}
protected override void Because_of()
{
try
{
_itemTypeRepository.Save(null);
}
catch (Exception ex)
{
_result = ex;
}
}
[Test]
public void then_an_argument_null_exception_should_be_raised()
{
_result.ShouldBeInstanceOfType(typeof(ArgumentNullException));
}
}
The actual implementation is shown below. The test runs fine. But without the expectation set to throw argumentnullexception , the save method actually return NullReferenceException. The point is: isn't the unit test obscuring the actual result. Though the requirement is fulfilled from unit testing point of view , it is not fulfilled actually while implemented.
public class ItemTypeRepository : IItemTypeRepository
{
public int Save(ItemType itemType)
{
int id;
using (var session = _sessionFactory.OpenSession())
{
id = (int) session.Save(itemType);
session.Flush();
}
return id;
}
}