C
C#11mo ago
hunterlan

xUnit: Can't assert exceptions

Hello, there! I want to compare exception types, but I'm getting error. Here's my code:
var exception = await Assert.ThrowsAsync<ArgumentException>(() => _endpoint.GetReport("1.1.1.1", null));
Assert.Equal("Api key shouldn't be empty.", exception.Message);
var exception = await Assert.ThrowsAsync<ArgumentException>(() => _endpoint.GetReport("1.1.1.1", null));
Assert.Equal("Api key shouldn't be empty.", exception.Message);
Here's an error:
System.ArgumentException: Api key shouldn't be empty.

System.ArgumentException
Api key shouldn't be empty.
System.ArgumentException: Api key shouldn't be empty.

System.ArgumentException
Api key shouldn't be empty.
Here's part of code which I want to test:
protected string ApiKey
{
get => _apiKey;
init
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Api key shouldn't be empty.");
}

_apiKey = value;
}
}
protected string ApiKey
{
get => _apiKey;
init
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Api key shouldn't be empty.");
}

_apiKey = value;
}
}
5 Replies
Kouhai
Kouhai11mo ago
Can you show the code for _endpoint.GetReport?
hunterlan
hunterlanOP11mo ago
public async Task<IpAnalysisResult> GetReport(string ipAddress, CancellationToken? cancellationToken)
{
var request = new RestRequest($"/{ipAddress}").AddHeader("x-apikey", ApiKey);

RestResponse restResponse;

if (cancellationToken is not null)
{
restResponse = await Client.ExecuteGetAsync(request, cancellationToken.Value);
}
else
{
restResponse = await Client.ExecuteGetAsync(request);
}

if (restResponse is { IsSuccessful: true})
{
var resultJsonDocument = JsonDocument.Parse(restResponse.Content!);
var result = resultJsonDocument.RootElement.GetProperty("data").Deserialize<IpAnalysisResult>(_jsonSerializerOptions)!;
return result;
}

HandleError(restResponse.Content!);
return new IpAnalysisResult();
}
public async Task<IpAnalysisResult> GetReport(string ipAddress, CancellationToken? cancellationToken)
{
var request = new RestRequest($"/{ipAddress}").AddHeader("x-apikey", ApiKey);

RestResponse restResponse;

if (cancellationToken is not null)
{
restResponse = await Client.ExecuteGetAsync(request, cancellationToken.Value);
}
else
{
restResponse = await Client.ExecuteGetAsync(request);
}

if (restResponse is { IsSuccessful: true})
{
var resultJsonDocument = JsonDocument.Parse(restResponse.Content!);
var result = resultJsonDocument.RootElement.GetProperty("data").Deserialize<IpAnalysisResult>(_jsonSerializerOptions)!;
return result;
}

HandleError(restResponse.Content!);
return new IpAnalysisResult();
}
Kouhai
Kouhai11mo ago
You're not initializing ApiKey in that method though, it seems like it's already initialized in earlier code
hunterlan
hunterlanOP11mo ago
yep, and I realised that I should created an Endpoint class in test, not in constructor, thanks!
Kouhai
Kouhai11mo ago
ThumbsUpSmile
Want results from more Discord servers?
Add your server