简体   繁体   中英

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 为 null 但 bindCtx.ModelName 等于“Test”

** Edit for Project Refs

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM