如何在ASP.net Core中编写自定义模型绑定程序的单元测试

编程入门 行业动态 更新时间:2024-10-10 14:25:03
本文介绍了如何在ASP Core中编写自定义模型绑定程序的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经为属性编写了自定义模型活页夹。现在,我正在尝试编写相同的单元测试,但无法为模型绑定器创建对象。谁能帮我 ?下面是我必须为其编写测试的代码。

I have written custom model binder for a property. Now I am trying to write unit test for the same but not able to create object for model binder. Can anyone help me ? Below is the code for which I have to write test.

public class JourneyTypesModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { bool IsSingleWay = Convert.ToBoolean((bindingContext.ValueProvider.GetValue("IsSingleWay")).FirstValue); bool IsMultiWay = Convert.ToBoolean((bindingContext.ValueProvider.GetValue("IsMultiWay")).FirstValue); JourneyTypes journeyType = JourneyTypes.None; bool hasJourneyType = Enum.TryParse((bindingContext.ValueProvider.GetValue("JourneyType")).FirstValue, out journeyType); if (!hasJourneyType) { if (IsSingleWay) journeyType = JourneyTypes.Single; else journeyType = JourneyTypes.MultiWay; } bindingContext.Result = ModelBindingResult.Success(journeyType); return Task.CompletedTask; } }

推荐答案

我已经创建了单位使用Nunit进行测试(与XUnit几乎相同),然后使用Moq模拟依赖关系。联机C#编译器可能会导致一些错误,但是下面显示的代码将为您提供这个想法。

I have created the unit test with Nunit (which is almost the same withy XUnit) and I mocked dependencies with Moq. There might be some errors due to online C# compiler but code shown below will give you the idea.

[TestFixture] public class BindModelAsyncTest() { private JourneyTypesModelBinder _modelBinder; private Mock<ModelBindingContext> _mockedContext; // Setting up things public BindModelAsyncTest() { _modelBinder = new JourneyTypesModelBinder(); _mockedContext = new Mock<ModelBindingContext>(); _mockedContext.Setup(c => c.ValueProvider) .Returns(new ValueProvider() { // Initialize values that are used in this function // "IsSingleWay" and the other values }); } private JourneyTypesModelBinder CreateService => new JourneyTypesModelBinder(); [Test] public Task BindModelAsync_Unittest() { //Arrange //We set variables in setup function. var unitUnderTest = CreateService(); //Act var result = unitUnderTest.BindModelAsync(_mockedContext); //Assert Assert.IsNotNull(result); Assert.IsTrue(result is Task.CompletedTask); } }

更多推荐

如何在ASP.net Core中编写自定义模型绑定程序的单元测试

本文发布于:2023-11-14 03:56:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   绑定   模型   单元测试   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!