2017-07-10 8 views
6

私はXUnitとMoqの初心者です。私は文字列を引数として取るメソッドを持っています.XUnitを使って例外を処理する方法。XUnitを使用して例外をアサートする

[Fact] 
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { 
    //arrange 
    ProfileRepository profiles = new ProfileRepository(); 
    //act 
    var result = profiles.GetSettingsForUserID(""); 
    //assert 
    //The below statement is not working as expected. 
    Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID("")); 
} 
テスト中の

方法

public IEnumerable<Setting> GetSettingsForUserID(string userid) 
{    
    if (string.IsNullOrWhiteSpace(userid)) throw new ArgumentException("User Id Cannot be null"); 
    var s = profiles.Where(e => e.UserID == userid).SelectMany(e => e.Settings); 
    return s; 
} 
+0

あなたは「期待通りに動作していない」とはどういう意味ですか? (また、あなたのコードをより読みやすくフォーマットしてください。プレビューを使って、読んでいたかどうかを見たいときにポストしてください) –

+2

ヒント:あなたの前に 'GetSettingsForUserID(" ")'を呼んでいますAssert.Throwsを呼び出す。 'Assert.Throws'コールはあなたを助けません。私はAAAについて厳格ではないとお勧めします... –

答えて

10

Assert.Throws式が例外をキャッチし、タイプをアサートします。しかし、assert式の外でテスト中のメソッドを呼び出しているため、テストケースが失敗します。

[Fact] 
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() 
{ 
    //arrange 
    ProfileRepository profiles = new ProfileRepository(); 
    // act & assert 
    Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID("")); 
} 

次AAAに曲がっている場合は、それ自身の変数にアクションを抽出することができます

[Fact] 
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() 
{ 
    //arrange 
    ProfileRepository profiles = new ProfileRepository(); 
    //act 
    Action act =() => profiles.GetSettingsForUserID(""); 
    //assert 
    Assert.Throws<ArgumentException>(act); 
} 
関連する問題