How to use Ninject.MockingKernel?
I'm trying to use Ninject.MockingKernel.Moq. I've 2 problems:
- I've to register all the types I want to mock. If I don't do that, the parameterless constructor of my class is called and that's not the purpose of an automocker
- It seems that even if the mock is called, the verification failed. Look at the following sample
Sample Code:
//Arrange
var kernel = new Ninject.MockingKernel.Moq.MoqMockingKernel();
kernel.Bind<ClassUnderTest>().ToSelf();
kernel.Bind<ILogger>().ToMock();
kernel.GetBindings(typeof(ILogger));
//Act
var sut = kernel.Get<ClassUnderTest>();
sut.DoSomething();//Logger.Log is called inside that method
//Assert
var mock = kernel.GetMock<ILogger>();
mock.Verify(x => x.Log(It.IsAny<string>()), Times.Exactly(1开发者_Python百科));
For self bindable types such as non-abstract classes an instance of the class is returned by default. The intention behind that is to make the most common use case easy, where a resolve of a class is the object under test and all dependencies are defined as interfaces.
Using classes as a dependency is uncommon as it only allows mocking of virtual methods. As said above this uncommon scenario is more complicated to make the common one as easy as possible.
Interfaces on the other hand don't need any binding.
If you want to mock classes you have to define
// note the scope so that you can access it later again
kernel.Bind<Foo>().ToMock().InSingletonScope();
var mock = kernel.GetMock<Foo>()
精彩评论