Reputation: 3583
This is method i want to test:
void Update(User user)
{
if (_userQuery.IsNameExist(user.Guid, (int) user.UserId, user.Name))
UpdateUser(user);
}
Below test class with method Update_Test()
which should test above one.
[TestFixture]
class ModifyuserServiceTest
{
private IModifyUserService ModifyUserService { get; set; }
private Mock<IUserQuery> UserQuery { get; set; }
private Mock<IUserRepository> UserRepository { get; set; }
[SetUp]
public void SetUp()
{
userQuery = new Mock<IUserQuery>();
UserRepository = new Mock<IUserRepository>();
ModifyUserService = new ModifyUserService(userQuery.Object, UserRepository.Object);
}
[Test]
public void Update_Test()
{
userQuery.Setup(uow => uow.IsNameExist(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>()))
.Returns(true);
ModifyuserService.Update(new User());
UserRepository.Verify(uow => uow.Add(It.IsAny<User>()), Times.Once);
}
}
For whatever reason i get error:
System.InvalidOperationException : Nullable object must have a value.
When i debug test method it raises error on this line in tested method:
if (_userQuery.IsNameExist(user.Guid, (int) user.UserId, user.Name))
When i look into arguments values there are: 0, null, null
which seems to be funny as in my test method i specified in userQuery.Setup
:
It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>()
I even tried like this:
userQuery.Setup(uow => uow.IsNameExist(999, 33, "whatever"))
nevertheless again same error occurs and values there shows : 0, null, null
What is wrong here?
Update:
public bool IsNameExist(int guid, int userId, string name)
{
Parameters = new List<IDbDataParameter>
{
Context.CreateParameter("@Guid", guid, DbType.Int64),
Context.CreateParameter("@userId", userId, DbType.Int64),
Context.CreateParameter("@Name", name, DbType.String)
};
var count = (int)Context.GetScalarValue($"SELECT count(*) FROM {UserTable} WHERE userId=@userId And Guid=@Guid And Name=@Name", CommandType.Text,
Parameters.ToArray(), null);
return count > 0;
}
Upvotes: 1
Views: 310
Reputation: 247581
I just ran a test
int? x = null;
int y = (int)x; //System.InvalidOperationException: 'Nullable object must have a value.'
and it fails with the same error message in your test
This has nothing to do with the MOQ Setup.
Your method under test is trying to cast null
to int
, causing a run-time error.
That implies that the UserId
passed to the method under test is null.
You need to set a value for the user id so the test can be exercised to completion.
//...
var user = new User() {
UserId = 0
};
ModifyuserService.Update(user);
//...
Upvotes: 1