jeudi 3 mars 2016

End-to-end test web api 2 end-point with file upload

I'm currently working on an end-point that involves the upload of image files. I've come to a place of mind, where I want to make sure everything works the way it's intended from front to back (and back to front again), but I can't seem to come up with a way to write a test that "fakes" the request to the end-point containing an image (it's this last part that's bugging me; the embedding of the image in the request content).

Here's the first part of my post method:

[HttpPost]
[Route]
public async Task<IHttpActionResult> Post(ImageType imageType, int id)
{
    // Check request content for supported media format content.
    if (!Request.Content.IsMimeMultipartContent())
        return BadRequest("Unsupported file format.");

    // Check upload supportability of the specified image type.
    string message;
    if (!imageType.IsUploadable(out message))
        return BadRequest(message);
    if (id < 0)
        return BadRequest("A valid ID must be supplied.");

    // Read request content into memory.
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
...

Here's my (completely unfinished) test method:

[Test]
[Category("Controller Test")]
public async Task Image_Controller_Post_Single_Image_Success()
{
    // Arrange
    const ImageType type = ImageType.TestImage;
    const int listingId = 999999;

    // Act
    var response =
        await
            Client.PostAsJsonAsync($"v1/images?imageType={type}&id={listingId}", _image);

    Console.WriteLine(response);

    // Assert
    response.Should().BeSuccessful();
}

The test already fails at response.Should().BeSuccessful(); because the content of the request isn't mime multi part content (I've tried tinkering with the type of _image - System.Drawing.Image, byte[], stream, location etc. - but to no avail). Another problem is my utter inability to properly articulate this question, due to the fact that I'm quite new to this whole API business, but there you have it. Hope one of you wizards can illuminate the path to wherever it is you illuminate paths to. :)

Thanks.

PS. I'm not really looking for a solution to the exact problem you see in the posted code samples, I'm more on the lookout for a general solution to the whole, "how to properly test an end-point from front to back (in code - not with postman or swagger something like that)"-business.

Aucun commentaire:

Enregistrer un commentaire