We are Trying to integrate Nunit testing within our web application. here we are using Nsubstitute as a mocking framework. The project architecture goes as below:
Public class BaseService : Glass.Mapper.Sc.SitecoreContext
{
public BaseService(){}
}
Public class DerivedService : BaseService
{
IGenericRepository<Item> _genericRepository;
public DerivedService ( IGenericRepository<Item> _repository)
{
_genericRepository= _repository;
}
public string DoSomethig(){}
}
Now to test the DoSomething() method of my DerivedService class i am creating the substitue of my repository and faking its response. which should let me test my service code.
[Test]
public void TestDoSomethigMethod()
{
var repository = Substitute.For<IGenericRepository<Item>>();
DerivedService tempService = new DerivedService(repository);
// Throws an exception of type System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary. at base service constructor.
var response = tempService.DoSomething();
}
When i try to invoke the instance of derived service it throws me the exception at baseService constructor saying (The given key was not present in the dictionary) we are using windsor castle for dependency injection & the Base Class inherits from Glass Mapper sitecore context class. Please let me know if anyone faced any such problem or have a solution for this.
edit: code for test case updated as suggested by Pavel & Marcio.
NSubstitute
will proxy public
and virtual
methods/properties only. You should either substitute interfaces or make sure the classes you substitute expose public virtual
methods. As far as I can tell, yours are not virtual
and while NSubstitute
can create the object, it can't effectively proxy/mock anything on it.
Also, if your constructor is not parameter-less make sure you are providing a substitute (or a real instance) for every argument when substituting.
More details here: http://nsubstitute.github.io/help/creating-a-substitute/