0

In my service class, I have this constructor.

public IngestService()
{
    _extractedFilePath = configuration["Path:Ingest"];

    if (string.IsNullOrEmpty(_extractedFilePath))
    {
        _logger.LogError($"Invalid conguration. Check appsettings.");
        throw new Exception("Invalid conguration. Check appsettings.");
    }
}

and I have this test using XUnit

[Fact]
public async Task WhenInvalidConstructor_ThenShouldThrowETest() {
        var _ingestService = new IngestService();
}

When I debug it, it can reach the constructor. But how do I capture the exception and assert the exception message "Invalid conguration. Check appsettings."?

Steve
  • 2,963
  • 15
  • 61
  • 133
  • 3
    This might help you: https://stackoverflow.com/questions/45017295/assert-an-exception-using-xunit – Shai Aharoni Jul 11 '21 at 07:57
  • 1
    BTW, [a good read](https://stackoverflow.com/questions/77639/when-is-it-right-for-a-constructor-to-throw-an-exception) –  Jul 11 '21 at 08:04
  • @ShaiAharoni, I tried but unable to get it since it is not calling any method but the constructor. If call any method, I can get the exception message. – Steve Jul 11 '21 at 08:51
  • 1
    Does this answer your question? [Assert an Exception using XUnit](https://stackoverflow.com/questions/45017295/assert-an-exception-using-xunit) – Progman Jul 12 '21 at 14:56

1 Answers1

3

Try this:

    Exception actualException = Assert.Throws<Exception>(() => new IngestService());
    Assert.Equal("Invalid conguration. Check appsettings.", actualException.Message);
Stam
  • 2,410
  • 6
  • 32
  • 58