JustMock与BLL

时间:2014-05-05 22:27:12

标签: unit-testing telerik nunit justmock telerik-testing-tools

我正在使用JustMock,我很难让JustMock使用Entity Framework并模拟数据库活动 - 特别是假插入

我想做一个假插入,然后返回假插入实体。我想在插入之前测试密码是否经过哈希处理(由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();
}

以下是我的测试......

    //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
    }

测试失败

 [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");
 }

我做错了什么?

1 个答案:

答案 0 :(得分:1)

所以我在浏览网页上的一些样本后想出来了。 BLL保持不变,但这是测试

一旦失败 - 现在通过测试

 [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");
    }