Asp.net core 2.2 ModelBinder Unit Test Issues

岁酱吖の 提交于 2019-12-02 08:19:21

问题


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;
    }
}

** Edit for Project Refs


回答1:


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.



来源:https://stackoverflow.com/questions/55032498/asp-net-core-2-2-modelbinder-unit-test-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!