Hello Mr. Hasanuzzaman,
Reading through your test, it appears that mock the dependency of BaseRepository<T>, which is a DbContext, but do not arrange all of its methods that the system under test depends on. Whenever you create a mock, you should carefully choose its behavior. In your code you create a recursive loose mock (that's the default behavior of Mock.Create<T>()) - this means that all method calls to the mock will behave like stubs or will return stubs recursively by default. This means, for example, that DbSet = DbContext.Set<T>(); will set DbSet to a stub - it will not set it to _mockDataContext.EmployeeSkill, unless explicitly arranged to do so. This also means that DbSet.Add(entity) will also behave like a stub - in other words it will do nothing (unless explicitly arranged).
When testing without
mocks, usually you assert the side effects created by the dependencies of the system under test. This is the same pattern I see in your own tests. When testing with
mocks, you should assert the mocks directly. For example, in your code, you test that the BaseRepository.Add method works, by asserting its side effects - namely, that the number of items in the collection, that Add works on, is now 2. However, the test doesn't work because the collection is a stub, not a real collection - calling its Add method simply does nothing. Instead, you should simply assert that the Add method was called at all - if it was called, then, obviously, the code under test behaves correctly. Thus, your test will look like this:
var employeeSkill = GetEmployeeSkill();
Mock.Assert(() => _mockDataContext.Set<EmployeeSkill>().Add(employeeSkill), Occurs.Once());
In the above method I call the _repository.Add() method and then assert that the .Add method of the underlying DbContext table was called exactly once with the same argument as the one passed to _repository.Add(). This example illustrates the basic test pattern when working with mocks - you don't assert side effects, you assert the mocks directly.
For your second test, you must arrange the respective Set<T> method, instead of the property wrapper. So, your arrange statement should look like this:
Mock.Arrange(() => _mockDataContext.Set<EmployeeSkill>()).ReturnsCollection(GetEmployeeSkills());
This is necessary, because .Set<T> is the method on the mock that BaseRepository uses. It does not use the .EmployeeSkill property directly, so there is no meaning in setting it.
For an introduction to mocking with JustMock I recommend the excellent 30 Days of TDD
I hope that my explanation has been helpful. If you require further assistance during your trial, don't hesitate to write to us again. We would be more than happy to assist you in any way we can.
Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums
, or our JustTrace