0

I never did unittesting for an asp.net web api. The service is about posting a JSON in the request and returning a JSON result after JSON schemavalidation and querying. Just wondering how to unittest a web api in general. An example of a test would be posting an invalid JSON string and testing whether this returns the correct HTTPcode ie 400 or something. This is roughly what my service looks like:

public class MyApiController : ApiController
{
   public HttpResponseMessage Post([FromBody]dynamic value)
   {
      return response;
   }
}

Also how can I use constructor injection with web apis? If I use a constructor here my value that is posted is null?

2

3 Answers 3

1

You can directly create the instance of controller. If you are used any complicated code, you can create mock for the class for unit testing. Refer this link to understand unit testing of ASP.NET web API.

Sign up to request clarification or add additional context in comments.

Comments

0
[Test]
    public async void GetSettingsRequest()
    {
        var getSettingsResponse = await api.GetSettings();
        Assert.IsNotNull (getSettingsResponse);
        Assert.IsTrue (getSettingsResponse.Success);
        Assert.IsNotNullOrEmpty (getSettingsResponse.Email);
    }

I made test project which is making request on api server. After request is made, wait for response and test response.

Comments

0

My first thought is that you should figure out what you want to test first. That means just jotting down all of the expected behaviors, then writing tests to ensure that your controller behaves as... expected.

Let's start with two fictional test cases:

  • The response is not null
  • The response always carries a success status code

--

class MyApiControllerTest
{
    private MyApiController myApiControllerFixture;

    [TestInitialize]
    void Initialize()
    {
        this.myApiControllerFixture = new MyApiController();
    }

    [TestMethod]
    void MyApiController_Post_ResponseNotNullTest()
    {
        var response = this.myApiControllerFixture.Post(new { });

        Assert.IsNotNull(response);
    }

    [TestMethod]
    void MyApiController_Post_SuccessStatusCodeTest()
    {
        var response = this.myApiControllerFixture.Post(new { });

        Assert.IsTrue(response.IsSuccessStatusCode);
    }
}

Just add tests as you discover new required behaviors, and delete obsolete tests when behaviors change.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.