2017-07-10 16 views
6

Jestem początkującym użytkownikiem XUnit i Moq. Mam metodę, która przyjmuje ciąg jako argument.Jak obsługiwać wyjątek przy użyciu XUnit.Wystąpienie wyjątku przy użyciu 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("")); 
} 

Sposób badanego

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

Co masz na myśli mówiąc „nie działa zgodnie z oczekiwaniami”? (Proszę również sformatować swój kod w bardziej przystępny sposób.) Użyj podglądu i opublikuj, kiedy wygląda, jakbyś chciał, żeby wyglądało, gdybyś go czytał.) –

+2

Wskazówka: nazywasz 'GetSettingsForUserID (" ")' przed tobą zacznij wywoływać 'Assert.Throws'. Wywołanie 'Assert.Throws' nie może ci w tym pomóc. Sugeruję bycie mniej sztywnym o AAA ... –

Odpowiedz

10

Wyrażenie Assert.Throws złapie wyjątek i dochodzić typu. Wywołujesz jednak testowaną metodę poza wyrażeniem assert, a tym samym niepowodzenie testu.

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

Jeśli wygięte na następujących AAA można wyodrębnić działania na swój własny zmienna

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