[英]Unit testing multiple asserts
我正在嘗試使用MSTest對C#中的方法進行單元測試。 我正在測試ChangePasswordAsync方法強制密碼復雜性。 我的問題是我想用一系列參數測試這個方法。 目前我有一個單元測試,有多個斷言來測試不同的參數,這是一個合理的解決方案嗎?
我知道當我使用其他單元測試框架時,已經有方法來測試具有不同參數的方法。 我可以在方法上使用一個屬性來實現這個目的嗎? 我的示例單元測試如下:
/// <summary>
/// Ensures that a password must meet the password complexity of a digit and an alphanumeric, 8 digits long and one
/// special character.
/// </summary>
[TestMethod]
public void TestPasswordComplexity()
{
var result = _UserManager.ChangePasswordAsync(_TestUser.Id, "Password123!", "1!").Result; //Changes the password.
Assert.IsFalse(result.Succeeded);
result = _UserManager.ChangePasswordAsync(_TestUser.Id, "Password123!", "123456789").Result; //Changes the password.
Assert.IsFalse(result.Succeeded);
result = _UserManager.ChangePasswordAsync(_TestUser.Id, "Password123!", "123456789!").Result; //Changes the password.
Assert.IsFalse(result.Succeeded);
result = _UserManager.ChangePasswordAsync(_TestUser.Id, "Password123!", "abcdefghijk").Result; //Changes the password.
Assert.IsFalse(result.Succeeded);
result = _UserManager.ChangePasswordAsync(_TestUser.Id, "Password123!", "abcdefghijK1!").Result; //Changes the password.
Assert.IsTrue(result.Succeeded);
}
或者你會把每個人分成單獨的單元測試嗎?
您可以添加數據行注釋。
[TestMethod]
[DataRow ("1!")
[DataRow ("123456789")
[DataRow ("123456789!")
...
public void TestPasswordComplexity(string pass)
{
var result = _UserManager.ChangePasswordAsync(_TestUser.Id, "Password123!", pass).Result; //Changes the password.
Assert.IsFalse(result.Succeeded);
}
它將使用pass
參數傳遞每個數據行來運行測試方法。
為第五個Assert.IsTrue(result.Succeeded)
案例創建一個單獨的方法
為每個測試編寫一個單獨的單元測試方法,其含義為全名。 因此,當測試失敗后,您很容易發現問題所在。
您必須區分不同的測試和不同的測試參數。 你的一些斷言會失敗,因為密碼由於某種原因變弱,有些應該通過。
對於您確實需要不同參數的情況,可以使用DataSource
(請參閱http://msdn.microsoft.com/en-us/library/ms182527.aspx ),您可以在其中添加外部源作為excel文件輸入。
例如,您可以使用excel源測試傳遞密碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.