[英]Don't know what I'm doing wrong in my Unit Test
I have a Unit Test for my LoginSystem, and it's failing and I have no idea why, In my opinion I think my code is correct, it seemed to be working for the past couple of weeks and I only found this error through 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;
}
Can someone tell me why my exception is always thrown? 有人可以告诉我为什么总是抛出我的异常吗? thanks.
谢谢。
You're comparing ONE username and password to an entire collection of usernames and passwords. 您正在将一个用户名和密码与整个用户名和密码集合进行比较。 By definition, only one item in the entire collection should evaluate to
true
and the rest should evaluate as false
. 根据定义,整个集合中只有一项应评估为
true
,其余应评估为false
。 In your case, you're throwing an exception the very first time one evaluates to false
. 在您的情况下,您第一次将异常评估为
false
时引发了异常。
On a side note, comments like this one: 附带说明一下,这样的注释:
//create a new bool and set it to false. //创建一个新的布尔并将其设置为false。
bool returnvar = false; bool returnvar = false;
Should be avoided since the code talks for itself. 应避免使用,因为代码本身就是自言自语。 Useless comments dont add any value to the code but rather have a negative effect.
无用的注释不会给代码增加任何价值,但是会带来负面影响。
If you are looking to improve the routine, then consider returning true when a match is found, if it gets to the end of the loop, return false or throw an exception. 如果要改进例程,请考虑在找到匹配项时返回true,如果到达循环末尾,则返回false或引发异常。 My personal preference is to avoid throwing exceptions unless it is actually an exception.
我个人的喜好是避免引发异常,除非它实际上是异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.