Mike
Mike

Reputation: 809

Asp.net core 2.2 ModelBinder Unit Test Issues

I'm seeing odd behavior while attempting to debug xUnits against components of the asp.net core pipeline. The code posted below has all purposeful functionality stripped out to illustrate the problem only which is :

  1. Not hitting all my breakpoints in JsonModelBinder.
  2. Not exiting on "return Task.Completed" even though it's being evaluated.

The production code for JsonModelBinder contains more logic to deserialize the incoming string data. This code contains failure logic which contains a number of return Task.Completed statements. When using this code the the debugger will evaluate these return statements but continue onward, not returning until reaching the end of the method, always reaching the end.

I'm using Moq, xUnit, VS2017, ASP.net Core 2.2.

// Simple fact

    [Fact]
    public async Task BindModelAsync_WithNullValueProvider_SetsDefaultError()
    {
        // arrange

        var queryStringCollection = new RouteValueDictionary
        {
            {"Page", "1"},
            {"Size", "20"}
        };

        var valueProvider = new RouteValueProvider(BindingSource.Path, queryStringCollection);

        ModelBindingContext bindingContext = new DefaultModelBindingContext
        {
            ModelName = "Test",
            ValueProvider = valueProvider
        };

        var jsonBinder = new JsonModelBinder();

        // act

        await jsonBinder.BindModelAsync(bindingContext);

        // not point in asserting :-)
    }

// JsonModelBinder

public class JsonModelBinder : IModelBinder
{
    private readonly IOptions<MvcJsonOptions> _jsonOptions;
    private readonly ILoggerFactory _loggerFactory;

    public JsonModelBinder() { }

    public Task BindModelAsync(ModelBindingContext bindCtx)
    {
        string modelName = bindCtx.ModelName;

        Debug.Print(modelName);

        if (string.IsNullOrEmpty(modelName))
        {
            return Task.CompletedTask;
        }

        return Task.CompletedTask;
    }
}

modelName is null yet bindCtx.ModelName is equal to "Test"

** Edit for Project Refs

enter image description here

Upvotes: 1

Views: 442

Answers (1)

bernard
bernard

Reputation: 136

One of my colleagues encountered the same problem. After a lot of debugging and investigation, we found this fixed the problem for him.

  1. Right-click on the solution in Visual Studio and do a ‘Clean Solution’.
  2. Manually delete the contents of the obj and bin folders of the projects.
  3. Delete the contents of the .vs folder in the solution root. (if the files are locked, close Visual Studio.)

The last step seems to be the important part.

Upvotes: 2

Related Questions