lexeme
lexeme

Reputation: 2973

Dependency injection and test doubles

I'm new to using dependency injection. For example I've got such a sample service:

public class ValidationService<T> where T : Entity<T>
{
    private IRepository<T> repository;
    private IValidator<T>  validator;

    public ValidationService(IRepository<T> repository, IValidator<T> validator)
    {
        this.repository = repository;
        this.validator  = validator;
    }

    public String ValidationMessage 
    { 
        get;
        private set;
    }

    public Boolean TryValidate(Guid Id)
    {
        try 
        {
            var item = repository.Get(Id);

            if(null != item)
            {
                this.Validator.ValidateAndThrow(entity);
                return true;
            }
            this.ValidationMessage = String.Format("item {0} doesn't exist in the repository", Id);
        }
        catch(ValidationException ex)
        {
            this.ValidationMessage = ex.Message;
        }
        return false;
    }
}

Can I use testing doubles (mocks or fakes) for repository & validator and use the same service with DI inside UI project (ASP.NET MVC)?

Thanks!

EDIT

The code's successfully running and in the output I have true.

public class Entity<T> where T : Entity<T>
{
    public Boolean GotInstantiated { get { return true; } }         
}
public class Service<T> where T : Entity<T>
{
    public Boolean GetInstantiated(T entity)
    {
        return entity.GotInstantiated;
    }
}
public class Dunce : Entity<Dunce>
{       
}

class Program
{
    public static void Main(String[] args)
    {
        var instance = new Dunce();
        var service  = new Service<Dunce>();

        Console.Write(service.GetInstantiated(instance) + Environment.NewLine);
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

Upvotes: 0

Views: 310

Answers (1)

Myles McDonnell
Myles McDonnell

Reputation: 13335

Yes, absolutely. Have your unit tests instantiate the service with mocks, have your application pass your real implementation.

example (using MOQ):

public class Entity<T> where T : Entity<T>{}

public class MyEntity : Entity<MyEntity>{}

...

var mockValidator = new Mock<IValidator<MyEntity>>();
var mockRepository = new Mock<IRepository<MyEntity>>();

var id = Guid.NewGuid();
var entity = new MyEntity();

mockRepository.Setup(r => r.Get(id)).Returns(entity);
mockValidator.Setup(v => v.ValidateAndThrow(entity));

Assert.IsTrue(new ValidationService<MyEntity>(mockRepository.Object, mockValidator.Object).TryValidate(id));

mockRepository.VerifyAll();
mockValidator.VerifyAll();

Upvotes: 1

Related Questions