2017-11-03 12 views
-4

セッションキーなしでアカウントの詳細を表示しようとすると、私のコードをユニットテストしてみようとしていますが、例外がスローされます。単体テストはtry-catchの中のステートメントを実行し、例外が発生することを知っているにもかかわらず、Assertがfalseであるにもかかわらずテストを成功としてリストします。アサーションには同様の機能がありますが、必ずしもそうではありません。問題の原因は何でしょうか?アサートメソッドがTry-Catchステートメントに到達していません

オリジナル機能

/// <summary> 
/// Displays the account details to the user 
/// </summary> 
/// <returns>HttpResponseMessage deserialized into AccountResponses object</returns> 
public async Task<AccountResponse> Details() 
{ 
    HttpClient client = new HttpClient(); 
    client.DefaultRequestHeaders.Add("X-Session-Key", sessionKey); 

    try 
    { 
     HttpResponseMessage response = await client.GetAsync(_baseUrl + "/Account/Details"); 
     response.EnsureSuccessStatusCode(); 
     string details = await response.Content.ReadAsStringAsync(); 
     AccountResponse temp = JsonConvert.DeserializeObject<AccountResponse>(details); 
     return temp 
    } 
    catch (HttpRequestException ex) 
    { 
     throw ex; 
    } 
} 

ワーキングライブユニットテスト機能

[TestCategory("Account/Logon")] 
[TestMethod] 
public void LogOnNegativeBadPasswordTest() 
{ 
    try 
    { 
     string sessionKey = dmWeb.Account.LogOn(new DMWeb_REST.AccountLogOn { Password = "test#pasasdfasfsword" }).GetAwaiter().GetResult().ToString(); 
    } 
    catch (HttpRequestException ex) 
    { 
     Assert.IsTrue(ex.Message.Contains("400")); 
    } 
} 

テストがエラーなし限り、成功したものとして扱われますライブユニットテスト機能

[TestCategory("Account/Details")] 
[TestMethod] 
public void DisplayDetailsNegativeNoSessionKeyTest() 
{ 
    try 
    { 
     string details = dmWeb.Account.Details().GetAwaiter().GetResult().ToString(); 
    } 
    catch (HttpRequestException ex) 
    { 
     Assert.IsTrue(ex.Message.Contains("401")); 
    } 
} 
+2

。 – JLRishe

+5

IDEのスクリーンショットではなく、コードを投稿してください。あなたの質問に例外メッセージを入れてください。 –

+1

質問:なぜあなたは単純に 'throw ex;'でキャッチブロックを持っていますか?上記のコードをtry/catchブロック*にすべてラップすることのポイントは何ですか? –

答えて

0

を動作しませんスローされます。 catchブロックにエラーが検出されない場合、これはテストしているコードによってエラーがスローされなかったことをほぼ意味します。

ので、エラーをスローするはずの文の後Assert.Fail()を置く:質問_in_、ないimgurにあなたのコードを含めてください

public void TestMethod() 
{ 
    try 
    { 
     string details = ThingIAmTesting(); 
     // shouldn't get here 
     Assert.Fail(); 
    } 
    catch (Exception ex) 
    { 
     Assert.IsTrue(ex.Message.Contains("401"); 
    } 
} 
関連する問題