I have just started using Rhino mocks and I am having difficulty doing that.
Here is my function which I am trying to test.
public bool IsUserExists(string emailAddress)
{
return _repository.IsUserExists(emailAddress);
}
Here is my test which I wrote and currently failing when the actual call is made
[TestClass]
public class UserServiceTest
{
private MockRepository _mockRepository;
private IUserRepository _userRepository;
private IUserService _userService;
public UserServiceTest()
{
_mockRepository = new MockRepository();
_userRepository = MockRepository.GenerateMock<IUserRepository>();
_userAccntService = new UserAccntService();
}
[TestMethod]
public void Should_return_true_IfUserWithEmailExists()
{
var emailaddress = "noreply@abc.com";
_userRepository.Stub(x => x.IsUserExists(emailaddress)).Return(true);
bool ifUserExists = _userAccntService.IsUserAcctExists(emailaddress); // throws!
Assert.AreEqual(ifUserExists,true);
}
}
We are currently using EF for making repository calls.
And when I am trying to test this method it is failing when the function call is made in actual.
I am getting entitycommandexecution error in the call to _userAccntService.IsUserAcctExists.
The fact that you’re getting an entity framework error means that
_repositoryis pointing to an actual instance of an EF object, while_userRepositoryis a mock. Make sure that your_userAccntService‘s repository instance is pointing to exactly_userRepository.In other words, in your test setup method, when you construct
_userRepository, make sure that’s what gets passed into your_userAccntServiceconstructor.So, looking at your updated code:
_userAccntServiceis never passed_userRepository, so how can it be expected to use it when you callIsUserAcctExists()? This repository dependency needs to be injected into your_userAccntServiceinstance. Something like: