测试超出执行超时时间

我的main.cs代码:

public string Generate(int length) { char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray(); string password = string.Empty; Random random = new Random(); for (int i = 0; i < length; i++) { int x = random.Next(1, chars.Length); if (!password.Contains(chars.GetValue(x).ToString())) password += chars.GetValue(x); else i--; } return password; } 

我已经制作了测试代码

 [TestMethod] [Timeout(1000)] public void RenderingPasswordShouldHaveMaximumSize() { var amountOfCharacters = Int32.MaxValue; var generator = new PasswordGenerator(); var target = generator.Generate(amountOfCharacters); Assert.Fail("This method should throw an exception if you try to create a password with too many characters"); } 

但它给了我以下错误:

消息:测试’RenderingPasswordShouldHaveMaximumSize’超出了执行超时期限

有人可以帮我弄这个吗? 我的密码最大大小需要为74。

我刚刚注意到你真的希望你的测试花费很长时间,忽略关于Int32.MaxValue的部分。

你的循环有点奇怪,你为了尝试利用所有字母而减少迭代器,但这可能会导致问题。 它不是花费太长时间的情况,而是它没有真正生成密码。

我会像这样修复你的版本

 static string Generate(int length) { // also, seed your random so you don't get the same password Random random = new Random((int)DateTime.Now.Ticks); char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray(); string password = string.Empty; for (int i = 0; i < chars.Length; i++) { int x = random.Next(0, chars.Length); if (!password.Contains(chars.GetValue(x).ToString())) password += chars.GetValue(x); else i--; } if (length < password.Length) password = password.Substring(0, length); return password; } 

我测试了这个并且它有效:

测试代码:

 Debug.WriteLine(Generate(5)); Thread.Sleep(50); Debug.WriteLine(Generate(10)); Thread.Sleep(50); Debug.WriteLine(Generate(20)); Thread.Sleep(50); Debug.WriteLine(Generate(30)); Thread.Sleep(50); Debug.WriteLine(Generate(40)); Thread.Sleep(50); Debug.WriteLine(Generate(60)); Thread.Sleep(50); 

结果:

 SDxF0 i8ZLhm1gxn @0Ldn7I&1:Kg2x3SYE;m U?5uO%N4hkpq1*y;9SRVaer^Eij:bT nvL;E3#D1MQgTicSdojHOwz:VFk2x&94a*PZ@X80 cSm39n:%1sL*lk2B?yVDTPZCA0vGb@udjeW5KoUw6qRNxY^pazH$JXiQ;tFg 

另外,请记住,您为密码添加字符的方式,您正在使用它以便它使用char[]中的所有字符,但没有重复。 这意味着密码的最大长度等于char[]的长度。

我会推荐这样的东西:

 static string Generate(int length) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int x = random.Next(33, 123); sb.Append((char)x); } return sb.ToString(); } 

这给出了相同的结果,但也可以处理更长的长度,例如200:

 t5[5l WoEZG;8^9< 6(4Q*Y7k>`?ohte6F^pe DVb\5l^JMKc`q&[#$U4Kq^\OW`JrRi #iQSq0\WRoDe<]k36nOhNOb-#"Zt!cK8iaR.I>VF 1<%^"B)6bZhWEiazmfmO7Vv*Rw]TbKV+GRJUc%k23Lq/HC.I6Eha6!5V@v-& jOnV_`(Cf$I\kFr/%%/loG"bx9lV1E?`[A"y1)pF5tA".x?**(E/>kzCN-XGnL2B`c!JEtxw0cXu'zTztcM*z0CkBYK%LIRcbz 

怎么样只是添加这个:

 if (length > chars.Length) { throw new ArgumentException("Password too long", length); } 

在测试中,您可以检查是否按预期抛出此Exception

除非您传递的数字小于74否则您的代码将永远不会完成。

根据您的代码,如果随机选择的字符已经在密码中,您只需再次迭代(减少i )。

你有没有想过一旦你使用了chars所有角色会发生什么?