How to mock an injected class using NSubstitute?

1.4k Views Asked by At

I am using StructureMap for my dependency injection. I have the following repository:

public class StaffRepository : NHibernateRepository<IStaff>, 
{
    public IEnumerable<IStaff> GetByStaffId(string staffId)
    {
        return Repository.Where(ab => ab.StaffId == staffId);
    }
}

I am writing a test to test a method in a controller (ReturnToWorkController):

Which has this repository injected:

public ReturnToWorkController(
            IStaffRepository staffRepository)
        {
            this.staffRepository = staffRepository;
        }

I am testing my controller (using SpecFlow) by calling the container and resolving it using StructureMap:

readonly ReturnToWorkController returnToWorkController;

public SicknessSteps(TestContext testContext)
{
        returnToWorkController = ApplicationContext.Resolve<ReturnToWorkController>();
}

then calling the method that I would like to test:

returnToWorkController.Approval("x");

I am using NSubstitute to mock my repository:

var staffRepository = Substitute.For<IStaffRepository>();
            staffRepository.GetByStaffId(currentUserStaffId)
                .Returns(ListStaff.Where(x => x.StaffId == currentUserStaffId));

My question is, how can I (or is it even possible) to mock the injected object within the controller? Would this be done in my IoC setup?

0

There are 0 best solutions below