在编写单元测试时,我们总是说我们需要确保代码始终与外部依赖关系隔离。 Moq之下已被用来提供一个模拟对象,而不是一个有效的流利的nhibernate会话工厂。单元测试 - 从外部依赖关系的隔离
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));
}
}
实际执行情况如下所示。测试运行良好。但是如果没有设置抛出argumentnullexception的期望,save方法实际上会返回NullReferenceException。重点是:不是单元测试掩盖了实际结果。虽然要求是从单元测试的角度来实现的,但它在实施时并未实现。
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;
}
}
然后,如果最终我们需要编写集成测试,那么通过使用模拟框架进行隔离的单元测试的目的是什么? – arjun
你可以在不嘲笑ISessionFactory的情况下嘲笑版本库;例如:只是测试逻辑,假装项目被保存在存储库中;这就是集成测试中要测试的内容。请参阅更新。 – henginy