I'm attempting to debug my xUnit(s) relating to a custom IModelBinder implementation and the Visual Studio debugger is :
None of my other xUnits behave this way. At this point the only Units giving me troubles are one associated with the asp.net core pipeline. I tried cleaning my solution and re-adding project refs thinking a may have had an old pdb file?
I'm using Moq, xUnit, VS2017, ASP.net Core 2.2.
// JsonModelBinder
public class JsonModelBinder : IModelBinder
{
private readonly IOptions<MvcJsonOptions> _jsonOptions;
private readonly ILoggerFactory _loggerFactory;
public JsonModelBinder() { }
public JsonModelBinder(IOptions<MvcJsonOptions> jsonOptions, ILoggerFactory loggerFactory)
{
_jsonOptions = jsonOptions;
_loggerFactory = loggerFactory;
}
public Task BindModelAsync(ModelBindingContext bindCtx)
{
string modelName = bindCtx.ModelName;
ValueProviderResult valueProviderResult = bindCtx.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindCtx.ModelState.SetModelValue(bindCtx.ModelName, valueProviderResult);
string value = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
JToken token;
try
{
token = JToken.Parse(value);
}
catch (JsonReaderException)
{
bindCtx.ModelState.TryAddModelError(modelName, "Invalid json object.");
return Task.CompletedTask;
}
catch (Exception ex)
{
bindCtx.ModelState.TryAddModelError(modelName, ex.Message);
return Task.CompletedTask;
}
bindCtx.Result = ModelBindingResult.Success(token);
return Task.CompletedTask;
}
}
// xUnits
public class JsonModelBinderFacts
{
[Fact]
public async Task BindModelAsync_WithNullValueProvider_SetsDefaultError()
{
// arrange
var bindingCtx = new Mock<ModelBindingContext>();
bindingCtx
.Setup(x => x.ModelName)
.Returns("Test");
var valueProvider = new Mock<IValueProvider>();
bindingCtx
.Setup(x => x.ValueProvider)
.Returns(valueProvider.Object);
var providerResult = new ValueProviderResult(new StringValues(new []{ "test"}));
valueProvider
.Setup(x => x.GetValue("Test"))
.Returns(providerResult);
var binder = new JsonModelBinder();
// act
await binder.BindModelAsync(bindingCtx.Object)
.ConfigureAwait(false);
// assert
Assert.True(bindingCtx.Object.ModelState.ErrorCount > 0);
}
My question was answered on this post : Asp.net core 2.2 ModelBinder Unit Test Issues
Something is getting corrupted in the hidden .vs folder in the root of the solution. Deleting the contents of this folder and rebuilding the solution worked.