1

I am writing some unit test to check my end points of webservice. Fortunately I write some of the test cases for get/post request and it works fine except the one. I want to write the test case to check the file uploading method of webservice. The webservice endpoint on PostMan is :

enter image description here

The body of the request takes userID and fileUpload attribute.

I write the basic code for this but don't know how to pass the form data as request body in Nunit test case.

        private HttpClient _client;
        
        [Test]
        public async Task UploadPDFfile()
        {
            var response = await _client.PostAsync("http://localhost:5000/documents/");
            
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }

Can anyone please tell me how I can pass the form-data attribute in PostAsync method in Nunit testing C# to check the file upload functionality.

Usman
  • 1,983
  • 15
  • 28
  • 2
    Does this answer your question? [How to send a file and form data with HttpClient in C#](https://stackoverflow.com/questions/42212406/how-to-send-a-file-and-form-data-with-httpclient-in-c-sharp) – Peska Feb 04 '21 at 19:24

1 Answers1

1

I like to use foo files in this kind of test.

HttpClient.PostAsync() has a parameter called content. You should create a HttpContent instance and send it with the post method:

        var filePath = "yourFooFilePathHere";

        using (var fs = File.OpenRead(filePath))
        using (var fileContent = new StreamContent(fs))
        {
            var content = new MultipartFormDataContent
            {
                { fileContent, "file", yourFileName }
            };
            content.Add(new StringContent(userId.ToString(), Encoding.UTF8, "application/json"));
            var response = await _client.PostAsync("http://localhost:5000/documents/", content);
        }

Please notice that I'm passing the created HttpContent as a parameter for the PostAsync method.

Vinicius Bassi
  • 401
  • 4
  • 14