[英]How to do the Assert phase of a private method whose return type is Void?
[英]How to user Assert for methods with return type void in MSTest
我的C#應用程序中有一個類似於下面的方法。
public async Task SampleMethod()
{
try
{
//some code
await AnotherMethod();
// some code
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message.ToString());
}
}
現在,我正在嘗試使用MStest為上述方法編寫一個單元測試用例。 我寫了一些如下。
[TestMethod]
public async Task SampleMethodTest()
{
ClassName cn = new ClassName();
await cn.SampleMethod();
}
現在我如何知道測試用例是否成功。 我如何在這里使用Assert?
非常感謝您的幫助。
如果直接測試AnotherMethod,您將看到它是否成功。 當它拋出異常時,測試將失敗。 SampleMethod僅實現try catch,並調用可以直接測試的AnotherMethod()。
[TestMethod]
public async Task SampleMethodTest()
{
ClassName cn = new ClassName();
await cn.AnotherMethod();
}
如果該測試拋出異常,則該測試將失敗。 當該方法不引發異常時,它是成功的。
如果您的方法更改了對象的狀態,則可以驗證對象的狀態是否符合預期。 如果不是,則可以使用Mock(帶有Moq之類的框架)來驗證與其他對象的協作。 請注意,您可能需要將AnotherMethod提取到另一個類,以便可以模擬和驗證調用。
還要注意,您應該嘗試設計軟件,以便可以在大多數UnitTest中使用Outputverification和Stateverification。 使用模擬進行通信驗證可能會導致難以維護的錯誤判斷和單元測試。
根據我在其他答案中的評論,我嘗試向您展示如何獲取控制台輸出。 您可以從控制台讀取所有文本,您必須將StringWriter()設置到控制台:
[TestMethod]
public async Task SampleMethodTest()
{
using (StringWriter stringWriter = new StringWriter())
{
Console.SetOut(stringWriter);
ClassName cn = new ClassName();
await cn.SampleMethod();
string consoleOutput = stringWriter.ToString();
Assert.IsFalse(consoleOutput.Contains("Exception"));
}
}
我希望這行得通。 我沒有使用UnitTest嘗試過,僅通過控制台程序嘗試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.