My service class methode is
public async ValueTask<HttpResponseMessage> UploadFileAsync(string fileKey)
{
..
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(httpContent, "upfile", Path.GetFileName(fileKey));
//in negative test case I am sending empty fileKey value then throwing argument exception from here
..
return httpResponseMessage;
}
I am calling this value task fileupload method in my test case like below
[Fact]
public async Task UploadFileAsync_WhenFileKeyParameterIsEmpty_ReturnArguementException()
{
string fileKey = "";
var ex = Assert.Throws<ArgumentException>(()=>objHttpService.UploadFileAsync(fileKey));
Assert.Equal("The value cannot be null or empty. (Parameter 'fileName')", ex.Message);
}
I couldn't able to get any response in ex variable, and getting assert failure like below.
Message: Assert.Throws() Failure Expected: typeof(System.ArgumentException) Actual: (No exception was thrown)
CodePudding user response:
var ex = await Assert.ThrowsAsync<ArgumentException>(
() => objHttpService.UploadFileAsync(fileKey));
The Throws
version would only detect problems if the async API threw synchronously, rather than the more typical behaviour of synchronously or asynchronously returning a faulted value-task.
CodePudding user response:
You have two issues. Firstly because your code is async you need to use xUnit's ThrowsAsync method and await the result.
Secondly ThrowsAsync expects a Func<Task> as a parameter, and () => UploadFileAsync(fileKey)
is a Func<ValueTask>. We can get around this by calling AsTask() on the result of the call to UploadFileAsync. So we need to change the call to Assert.Throws to:
var ex = await Assert.ThrowsAsync<ArgumentException>(
() => objHttpService.UploadFileAsync(fileKey).AsTask());
Working test code is below. Note that UploadFileAsync is just a test stub that should behave like the method you are testing.
public class objHttpService
{
[Fact]
public async Task UploadFileAsync_WhenFileKeyParameterIsEmpty_ReturnArguementException()
{
string fileKey = "";
var ex = await Assert.ThrowsAsync<ArgumentException>(
() => objHttpService.UploadFileAsync(fileKey).AsTask());
Assert.Equal("The value cannot be null or empty. (Parameter 'fileName')", ex.Message);
}
// Test code only - existing method shouldn't need to be changed
public static async ValueTask<HttpResponseMessage> UploadFileAsync(string _)
{
await Task.Delay(10);
throw new ArgumentException("The value cannot be null or empty. (Parameter 'fileName')");
}
}