0

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?

ViqMontana
  • 5,090
  • 3
  • 19
  • 54
  • Provide a [mcve] that can be used to reproduce the problem. Right now the question is still incomplete. – Nkosi Aug 11 '17 at 14:48
  • Is there a reason you need to use the container for the test? I realise it is probably a simplified example, but if possible maybe directly create the class under test and substitute for the dependencies you need: `var sub = Substitute.For(); returnToWorkController = new ReturnToWorkController(sub); /* configure sub */` – David Tchepak Aug 12 '17 at 13:00
  • 1
    can you create the subsitute like so: `var staffRepositoryInstance = Substitute.For();` and then register that instance in structure map: `ApplicationContext.Register(staffRepositoryInstance);` That way it will inject your controller with a stubbed dependency, without you having to do awkward DI manually – MattjeS Aug 14 '17 at 16:08

0 Answers0