jeudi 31 mars 2016

How to write unit test for ParameterBindingAttribute?

I wrote a custom ParameterBindingAttribute that simply does:

  • Check if there are any parameters passed in the URI. If there are any, parse them and try to match with the model. If it fails, then fail.
  • If no parameters are found, then look at the body. Analogically, parse the body.

My code seems to be working. I've tested various scenarios in Postman (extension for Google Chrome) and it passed it. However, it would be best to write some unit tests for this. Could you give me some guidelines on how to perform such unit testing? Thanks.

Here is the code:

public class FromUriOrBodyAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor descriptor)
    {
        return new FromUriOrBodyParameterBinding(descriptor);
    }
}

public class FromUriOrBodyParameterBinding : HttpParameterBinding
{
    private readonly HttpParameterBinding defaultUriBinding;
    private readonly HttpParameterBinding defaultFormatterBinding;

    public FromUriOrBodyParameterBinding(HttpParameterDescriptor descriptor)
        : base(descriptor)
    {
        this.defaultUriBinding = new FromUriAttribute().GetBinding(descriptor);
        this.defaultFormatterBinding = new FromBodyAttribute().GetBinding(descriptor);
    }

    public override Task ExecuteBindingAsync(
        ModelMetadataProvider metadataProvider,
        HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {
        var query = actionContext.Request.RequestUri.Query;

        return string.IsNullOrWhiteSpace(query)
            ? this.defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)
            : this.defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
    }
}

Aucun commentaire:

Enregistrer un commentaire