vendredi 10 juillet 2015

Moq setup does not return value while told

I have this in my test scenario:

var dbConnection = new Mock<IDbConnection>();
dbConnection.Setup(x => x.SearchFor<User>("users", y => y.Password =="12345" 
   && y.Username == "tester")).Returns(new List<User>{
       new User{
          Username = "tester",
           Password = "12345"
       }}.AsQueryable());

var users = new Users.Users(dbConnection.Object);
var user = users.Get("tester", "12345");

When looking at the Get method:

public User Get(string username, string password){
    var total = _dbConnection.SearchFor<User>("users", y => 
        y.Password == password && 
        y.Username == username).Single();
    return total;
}

It should work according by most of the samples I found on the internet, but it always gives me:

System.InvalidOperationException: Sequence contains no elements

When I change my Get method to this:

public User Get(string username, string password){
    var total = _dbConnection.SearchFor<User>("users", y => 
        y.Password == "12345" && 
        y.Username == "tester").Single();
    return total;
}

It magicaly works, but the get method is in a business layer and like we all know... to set a username and password hardcoded is never good.

So the real question is: How can I get the setup for moq work properly? What am I doing wrong??

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire