Reputation: 3882
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 = "[email protected]";
_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
.
Upvotes: 2
Views: 86
Reputation: 83366
The fact that you're getting an entity framework error means that _repository
is pointing to an actual instance of an EF object, while _userRepository
is 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 _userAccntService
constructor.
So, looking at your updated code:
public UserServiceTest() {
_mockRepository = new MockRepository();
_userRepository = MockRepository.GenerateMock<IUserRepository>();
_userAccntService = new UserAccntService();
}
_userAccntService
is never passed _userRepository
, so how can it be expected to use it when you call IsUserAcctExists()
? This repository dependency needs to be injected into your _userAccntService
instance. Something like:
public UserServiceTest() {
_mockRepository = new MockRepository();
_userRepository = MockRepository.GenerateMock<IUserRepository>();
_userAccntService = new UserAccntService(_userRepository);
}
Upvotes: 3