unit testing接口存储库的目的是什么

我是一个unit testingICustomerRepository接口,用于检索Customer类型的对象。

  • 作为一个unit testing我通过以这种方式测试ICustomerRepository获得了什么价值?
  • 在什么条件下,下面的测试会失败?
  • 对于这种性质的测试,建议我做的测试应该失败吗? 即当我知道我只在存储库中放置了5时,查找id 4

我可能遗漏了一些明显的东西,但似乎实现ICustomerRepository的类的集成测试将更有价值。

 [TestClass] public class CustomerTests : TestClassBase { private Customer SetUpCustomerForRepository() { return new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" }, new Login { LoginCustId = 5, LoginName = "tdude2" } } }; } [TestMethod] public void CanGetCustomerById() { // arrange var customer = SetUpCustomerForRepository(); var repository = Stub(); // act repository.Stub(rep => rep.GetById(5)).Return(customer); // assert Assert.AreEqual(customer, repository.GetById(5)); } } 

测试基类

 public class TestClassBase { protected T Stub() where T : class { return MockRepository.GenerateStub(); } } 

ICustomerRepository和IRepository

 public interface ICustomerRepository : IRepository { IList FindCustomers(string q); Customer GetCustomerByDifID(string difId); Customer GetCustomerByLogin(string loginName); } public interface IRepository { void Save(T entity); void Save(List entity); bool Save(T entity, out string message); void Delete(T entity); T GetById(int id); ICollection FindAll(); } 

测试规则#1:

在编写测试之前,要知道测试的目的是什么以及测试的内容。 如果你不知道它certificate了什么,那就没用了:)

正如其他海报所说的那样,你正在对一个接口进行存根,然后调用存根 – 这并不能certificate你的生产代码是否有效。

什么是存根?

存根用于提供固定值以驱动被测试类的某些方面。 例如,假设您的CustomerService具有ICustomerRepository类型的实例。 如果您希望在存储库为空时看到CustomerService可以正常处理错误情况,那么您将存根ICustomerRepositoryGetCustomerById方法以返回任何/ null /抛出exception,然后确保CustomerService方法执行正确的操作(例如,返回客户未找到的结果)。

即存根只是一个协作者,可以帮助您达到感兴趣的特定条件/行为。 我们正在测试CustomerService ,而存根的ICustomerRepository只是帮助我们实现目标。

你不是第一个问这个问题的人:)。 我通常建议开发人员首先手动推出他们的测试双打 。 它有助于理解所有交互以及框架实际为您做的事情。

我可能会遗漏一些东西,但似乎你的测试的每一个方面都被嘲笑了?

一般来说,您只会模拟不是测试核心的对象。 在这种情况下,您可以使用此存储库作为函数的源,您希望对存储库执行某些操作以检索客户#5并对其执行操作。

例如,您可以模拟客户存储库,以便可以调用validation用户登录的方法。 您将使用模拟存储库来防止您的unit testing依赖于真实的数据源,而不是测试您的模拟存储库。

根据定义,接口只是契约,因此没有可测试的代码。 您希望针对接口的具体实现编写unit testing,因为这是实际执行代码所在的位置。

如果没有具体的接口实现,并且你只是在嘲笑具体的实现,那么你的unit testing只是基于模拟。 这并不是很有价值。

你的测试对我没用。 您正在测试预编程的存根是否返回您提供的值,您没有测试任何实际代码。

按照dcp的回复。 接口是方法的声明。 您应该测试这些的实现。