vendredi 1 avril 2016

What is the right way to unit-test a function that calls another public function on the same object?

While I am aware of this question/answers (Unit testing a method that calls another method), still not sure what is best approach to unit-test a method that calls another public method on the same class?

I made a sample code (it can be seen here too: http://ift.tt/21X9JEl )

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();
}

So the question is how to write a unit test that only tests the logic inside MyService.GetEntity(int)? (while GetEntity internally calls GetAllEntities() but I am not interested to test latter one).

Aucun commentaire:

Enregistrer un commentaire