mardi 1 décembre 2015

How to Unit Test a custom JsonConverter in ASP.NET Web API?

I have a custom JsonConverter that takes a local datetime string from the front-end and converts it to DateTimeOffset using NodaTime.

I replaced the default resolver in Json.NET.

formatter.SerializerSettings = new JsonSerializerSettings
          {
              Formatting = Formatting.Indented,
              ContractResolver = new CustomResolver(),
              ReferenceLoopHandling = ReferenceLoopHandling.Ignore
          };

So in my tests I need to make sure I configure this.

What happens under-the-hood is that a POST request is made to my API controller. If the ViewModel (that is used in the API action) contains a DateTimeOffset property, then the associated JSON datetime property goes through the converter.

When the converter is triggered, then the application first gets the User.Identity:

var user = (ClaimsIdentity) Thread.CurrentPrincipal.Identity;

Upon success we extract the Locality claim, which contains the IANA timezone ID (e.g. "America/New_York").

We use this to convert the local datetime to the corresponding DateTimeOffset.

This is what I want to test.

I have the JSON object:

NameValueCollection nameValueCollection = new NameValueCollection() {
            {"dateCreated", "2015-11-30T14:22:00+1:00"},
            {"message", "Some message."},
            {"timelinePostId", "1"},
            {"applicationUser", ""},
            {"thumbs","" }
        };

But I'm stuck on how to perform the --

// Arrange

// Act

// Assert

I found this MockHelper class, so I have this ready for use.

public static HttpContextBase FakeHttpContext(HttpVerbs verbs, NameValueCollection nameValueCollection)
{
    var httpContext = new Mock<HttpContextBase>();
    var user = new ApplicationUser { 
            Id = "abc", 
            TimezoneId = "America/New_York" 
        };

    var request = new Mock<HttpRequestBase>();
    request.Setup(c => c.Form).Returns(nameValueCollection);
    request.Setup(c => c.QueryString).Returns(nameValueCollection);
    request.Setup(c => c.RequestType).Returns(verbs.ToString().ToUpper());

    var response = new Mock<HttpResponseBase>();
    var session = new Mock<HttpSessionStateBase>();
    var server = new Mock<HttpServerUtilityBase>();
    httpContext.Setup(c => c.Request).Returns(request.Object);

    var u = verbs.ToString().ToUpper();

    httpContext.Setup(c => c.Response).Returns(response.Object);
    httpContext.Setup(c => c.Server).Returns(server.Object);
    httpContext.Setup(c => c.User.Identity.GetUserId()).Returns("abc");
    httpContext.Setup(c => c.User.ApplicationUser()).Returns(user);
    return httpContext.Object;
}

So I have my JSON mock and I have my Identity mock, but how do I get it to work? Any help is greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire