2017-07-10 2 views
6

Ich bin ein Neuling für XUnit und Moq. Ich habe eine Methode, die Zeichenfolge als Argument verwendet. So behandeln Sie eine Ausnahme mit XUnit.Eine Ausnahme mit XUnit bestätigen

[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("")); 
} 

Methode unter Test

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

Was bedeuten extrahieren können Sie durch „funktioniert nicht wie erwartet“? (Bitte formatieren Sie Ihren Code auch lesbarer. Verwenden Sie die Vorschau, und senden Sie sie, wenn Sie sehen, wie sie aussehen soll, wenn Sie sie lesen.) –

+2

Hinweis: Sie rufen 'GetSettingsForUserID (" ")' vor Ihnen auf fange an 'Assert.Throws' zu nennen. Der 'Assert.Throws'-Aufruf kann Ihnen dort nicht helfen. Ich würde vorschlagen, über AAA weniger streng zu sein ... –

Antwort

10

Assert.Throws Der Ausdruck wird die Ausnahme abfangen und den Typ durchsetzen. Sie rufen jedoch die zu testende Methode außerhalb des Assert-Ausdrucks auf und können somit den Testfall nicht bestehen.

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

Wenn gebogen auf folgende AAA Sie die Aktion in seine eigene Variable

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