1

I am using JustMock and I am having difficulty having JustMock work with Entity Framework and mocking the database activity - specifically a fake insert

I want to do a fake insert and then return the fake inserted entity. I want to test that the password is hashed before insert (handled by the BLL).

UserBLL

 public UserBLL(MyDatabaseEntities context)
        : base(context)
 {            
 }

 public void Create(string email, string password)
 {      
    //check and make sure that the email does not already exist
    User user = GetUser(email);
    if (user != null)
       throw new Exception("Email account already exists");

    string salt = GetSalt();
    var hashedPassword = HashPassword(password, salt);

    var newUser = new User()
    {
       EmailAddress = email,
       Password = hashedPassword            
    };

    context.Users.Add(newUser);
    context.SaveChanges();
}

Here are my tests...

    //This works
    [Test]
    [ExpectedException(ExpectedMessage = "Email account already exists")]
    public void Create_NoDupeEmails()
    {
        List<User> fakeUsers = new List<User>();
        fakeUsers.Add(new User { EmailAddress = "peter@email.com", FirstName = "Peter", LastName = "Griffin" });
        fakeUsers.Add(new User { EmailAddress = "lois@email.com", FirstName = "Lois", LastName = "Griffin" });

        //arrange
        var context = Mock.Create<MyDatabaseEntities>();
        Mock.Arrange(() => context.Users).ReturnsCollection(fakeUsers);

        //act
        var bll = new UserBLL(context);
        bll.Create("peter@email.com", "password");

        //Assert
        //handled by the expected exception
    }

Failing test

 [Test]
  public void Create_PasswordHashed()
 {      
   var context = Mock.Create<MyDatabaseEntities>();    

   //arrange
   Mock.Arrange(() => context.SaveChanges()).MustBeCalled();

   var bll = new UserBLL(context);
   bll.Create("test@email.com", "password");

   User user = bll.GetUser("test@email.com");

   //user is null?
   Assert.IsTrue(user != null);    //it fails here
   Assert.IsTrue(user.Password != "password");
 }

What am I doing wrong?

Nick
  • 234
  • 2
  • 11

1 Answers1

1

So I figured it out after looking at some samples across the web. The BLL remains the same, but here is the test

Once failing - now passing test

 [Test]
    public void Create_PasswordHashed()
    {
        //arrange
        var context = Mock.Create<MyDatabaseEntities>();

        var users = new List<User>();
        Mock.Arrange(() => context.Users.Add(Arg.IsAny<User>()))
            .DoInstead((User u) => users.Add(u));   //this will add the "user u" to the list of "users"

        var bll = new UserBLL(context);

        bll.Create("test@email.com", "password");


        Assert.IsTrue(users.Count == 1);
        Assert.IsTrue(!string.IsNullOrWhiteSpace(users[0].Password));
        Assert.IsTrue(users[0].Password != "password");
    }
Nick
  • 234
  • 2
  • 11