不知道我在单元测试中做错了什么

时间:2015-05-24 02:01:20

标签: c# unit-testing

我的LoginSystem有一个单元测试,它失败了,我不知道为什么,在我看来我认为我的代码是正确的,它似乎在过去几周工作,我只是通过单元测试发现了这个错误。

public bool matchCheck(string Username, string Password)
        {
            //create a new bool and set it to false.
            bool returnvar = false;

            //for each basemember in the list of members.
            foreach (BaseMember bm in hillracing.Members)
            {
                //if the username is equal to a list item username AND the password is also equal.
                if (Username == bm.userName && Password == bm.passWord)
                {
                    //they exist within the same object, so return true.
                    returnvar = true;
                }
                else
                {
                    throw new Exception(" Did not match!");
                }
            }

            //return this bool, true or false.
            return returnvar;
        }

有人能告诉我为什么我的异常总是被抛出?感谢。

3 个答案:

答案 0 :(得分:2)

您将一个用户名和密码与一整套用户名和密码进行比较。根据定义,整个集合中只有一个项目应评估为true,其余项目应评估为false。在您的情况下,您在第一次评估false时会抛出异常。

答案 1 :(得分:0)

在旁注中,评论如下:

//创建一个新的bool并将其设置为false。

bool returnvar = false;

应该避免,因为代码会自行说明。无用的注释不会为代码添加任何值,而是产生负面影响。

答案 2 :(得分:0)

如果您希望改进例程,那么考虑在找到匹配时返回true,如果它到达循环结束,返回false或抛出异常。我个人的偏好是避免抛出异常,除非它实际上是例外。

相关问题