Usman
Usman

Reputation: 2029

Unit test case for uploading file using nunit C#

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.

Upvotes: 1

Views: 824

Answers (1)

Vinicius Bassi
Vinicius Bassi

Reputation: 504

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.

Upvotes: 1

Related Questions