在单元测试中检查重复的电子邮件和用户名

时间:2013-05-15 18:31:16

标签: c# unit-testing asp.net-membership

我必须在此单元测试中检查重复的电子邮件和用户名。在与另一位开发人员交谈时,他说我应该在嵌套的try catch中检查重复的电子邮件和用户名。我不确定我是否正确理解他,但这就是我所拥有的。另一位开发人员现在不可用,所以我无法要求验证。我认为这种格式是不正确的。有什么建议吗?

        try
        {

            AsaMembershipProvider prov = this.GetMembershipProvider();


            MembershipCreateStatus status;
            MembershipUser user = prov.CreateUser("UserX", "12345", "UserX@abc.com", "", "", true, null, out status);


            user = prov.GetUser("UserX", false);


            var isAuthenticated = prov.ValidateUser(user.UserName, "12345");
            Assert.IsTrue(isAuthenticated);
            Assert.AreEqual(user.UserName, "UserX");
            Assert.AreEqual(user.Email, "userx@abc.com");

            try
            {

                prov.DeleteUser("UserX", true);

                user = prov.GetUser("UserX", false);

                Assert.AreEqual(null, user);
                user = prov.GetUser("UserX", false);


                Assert.AreEqual(status, MembershipCreateStatus.Success);
            }
            catch (Exception ex)
            {
                LogMessage(ex);
                Assert.Fail(ex.Message);
            }


            prov.DeleteUser("UserX", true);

            user = prov.GetUser("UserX", false);

            Assert.AreEqual(null, user);


        }
        catch (Exception ex)
        {
            LogMessage(ex);
            Assert.Fail(ex.Message);
        }

    }

1 个答案:

答案 0 :(得分:0)

将try块中的代码移至Assert.Throws<T>

的调用
Assert.Throws<Exception>(() => {
    // attempt to create a duplicate user.
}, "Exception thrown when creating duplicate user.");

Exception更改为您希望在创建副本时抛出的确切异常类型。