【发布时间】:2016-04-01 18:47:03
【问题描述】:
虽然我知道这个问题/答案 (Unit testing a method that calls another method),但仍然不确定对在同一类上调用另一个公共方法的方法进行单元测试的最佳方法是什么?
我做了一个示例代码(也可以在这里看到:dotnetfiddle.net/I07RMg)
public class MyEntity
{
public int ID { get; set;}
public string Title { get; set;}
}
public interface IMyService
{
MyEntity GetEntity(int entityId);
IEnumerable<MyEntity> GetAllEntities();
}
public sealed class MyService : IMyService
{
IRepository _repository;
public MyService(IRepository repository)
{
_repository = repository;
}
public MyEntity GetEntity(int entityId)
{
var entities = GetAllEntities();
var entity = entities.SingleOrDefault(e => e.ID == entityId);
if (entity == null)
{
entity = new MyEntity { ID = -1, Title = "New Entity" };
}
return entity;
}
public IEnumerable<MyEntity> GetAllEntities()
{
var entities = _repository.Get();
//Some rules and logics here, like:
entities = entities.Where(e => !string.IsNullOrEmpty(e.Title));
return entities; // To broke the test: return new List<MyEntity>();
}
}
public interface IRepository : IDisposable
{
IEnumerable<MyEntity> Get();
}
所以问题是如何编写一个只测试MyService.GetEntity(int)内部逻辑的单元测试? (虽然GetEntity 内部调用GetAllEntities() 但我没有兴趣测试后者)。
【问题讨论】:
标签: c# unit-testing design-patterns