如何在Blazor WASM中测试自定义验证。

huangapple go评论63阅读模式
英文:

How to test custom validations in Blazor WASM

问题

I have a Blazor WASM and are about to write some test cases. Im new at this and wonder how I can proceed to test the component below?

public class CustomValidation : ComponentBase, IDisposable
{
    private IDisposable? _subscriptions;
    private EditContext? _originalEditContext;

    [CascadingParameter] EditContext? CurrentEditContext { get; set; }

    [Parameter] public bool DoEditValidation { get; set; } = false;

    /// <inheritdoc />
    protected override void OnInitialized()
    {
        if (CurrentEditContext == null)
        {
            throw new InvalidOperationException($"{nameof(DataAnnotationsValidator)} requires a cascading " +
                $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(DataAnnotationsValidator)} " +
                $"inside an EditForm.");
        }

        _subscriptions = CurrentEditContext.EnableCustomValidation(DoEditValidation, true);
        _originalEditContext = CurrentEditContext;
    }
}

I have tried with Bunit:

public class CustomValidationTests : IDisposable
{
    private CustomValidation _customValidation;

    public CustomValidationTests()
    {
        _customValidation = new CustomValidation();
    }

    [Fact]
    public void OnInitialized_SubscribesToCustomValidation()
    {
        // Arrange
        using var ctx = new TestContext();
        var editContext = new EditContext(new object());

        // Act
        var cut = ctx.RenderComponent<CustomValidation>(
            builder => builder.Add(c => c.CurrentEditContext, editContext));

        // Assert
        Assert.NotNull(cut.Instance.CurrentEditContext);
    }
}

I have tried something like this but throws an error because of CurrentEditContext protection level because it is marked with the CascadingParameter attribute.

英文:

I have a Blazor WASM and are about to write some test cases. Im new at this and wonder how I can proceed to test the component below?

public class CustomValidation : ComponentBase, IDisposable
    {
        private IDisposable? _subscriptions;
        private EditContext? _originalEditContext;

        [CascadingParameter] EditContext? CurrentEditContext { get; set; }

        [Parameter] public bool DoEditValidation { get; set; } = false;

        /// &lt;inheritdoc /&gt;
        protected override void OnInitialized()
        {
            if (CurrentEditContext == null)
            {
                throw new InvalidOperationException($&quot;{nameof(DataAnnotationsValidator)} requires a cascading &quot; +
                    $&quot;parameter of type {nameof(EditContext)}. For example, you can use {nameof(DataAnnotationsValidator)} &quot; +
                    $&quot;inside an EditForm.&quot;);
            }

            _subscriptions = CurrentEditContext.EnableCustomValidation(DoEditValidation, true);
            _originalEditContext = CurrentEditContext;
        }
}

I have tried with Bunit:

public class CustomValidationTests : IDisposable
{
    private CustomValidation _customValidation;

    public CustomValidationTests()
    {
        _customValidation = new CustomValidation();
    }

    [Fact]
        public void OnInitialized_SubscribesToCustomValidation()
        {
            // Arrange
            using var ctx = new TestContext();
            var editContext = new EditContext(new object());

            // Act
            var cut = ctx.RenderComponent&lt;CustomValidation&gt;(
                builder =&gt; builder.Add(c =&gt; c.CurrentEditContext, editContext));

            // Assert
            Assert.NotNull(cut.Instance.CurrentEditContext);
        }
}

I have tried something like this but throws and error because of CurrentEditContext protection level because it is marked with the CascadingParameter attribute.

答案1

得分: 1

Testing lifecycle methods directly is tricky, because the way they're called is controlled by the runtime. There are two ways to test the code in them:

  1. 直接测试生命周期方法很棘手,因为它们的调用方式由运行时控制。有两种测试其中代码的方法:

  2. 使用 bUnit 或任何将来出现的类似 Blazor 组件测试框架来托管和测试组件。

bUnit 不是一个完整的单元测试框架。它允许您使用您喜欢的框架,如 xUnit 或 NUnit,来测试组件。

bUnit 的首页 上显示的简单测试足以测试简单组件的正确初始化,例如:

public class MyCounterTest : TestContext
{
  [Fact]
  public void CounterShouldIncrementWhenClicked()
  {
    // Arrange: render the Counter.razor component
    var cut = Render(@&lt;Counter /&gt;);

    // Act: find and click the &lt;button&gt; element to increment
    // the counter in the &lt;p&gt; element
    cut.Find(&quot;button&quot;).Click();

    // Assert: first find the &lt;p&gt; element, then verify its content
    cut.Find(&quot;p&quot;).MarkupMatches(@&lt;p&gt;Current count: 1&lt;/p&gt;);
  }
}

文档还显示了如何测试具有 参数和级联值 的组件。

给定此组件:

public class NonBlazorTypesParams : ComponentBase
{
  [Parameter]
  public int Numbers { get; set; }

  [Parameter]
  public List&lt;string&gt; Lines { get; set; }
}

您可以使用 RenderComponentparameters 参数进行测试:

public class NonBlazorTypesParamsTest : TestContext
{
  [Fact]
  public void Test()
  {
    var lines = new List&lt;string&gt; { &quot;Hello&quot;, &quot;World&quot; };

    var cut = RenderComponent&lt;NonBlazorTypesParams&gt;(parameters =&gt; parameters
      .Add(p =&gt; p.Numbers, 42)
      .Add(p =&gt; p.Lines, lines)
    );
  }
}
英文:

Testing lifecycle methods directly is tricky, because the way they're called is controlled by the runtime. There are two ways to test the code in them:

  1. Extract the code into other methods or even classes that can be called directly and
  2. Use bUnit or any other similar Blazor component testing framework that appears in the future to host and test the component.

bUnit isn't a full unit testing framework. It allows you to test components using your preferred framework eg xUnit or NUnit.

The simple test shown in bUnit's landing page would be enough to test that a simple component initializes properly, eg :

public class MyCounterTest:TestContext
{
  [Fact]
  public void CounterShouldIncrementWhenClicked()
  {
    // Arrange: render the Counter.razor component
    var cut = Render(@&lt;Counter /&gt;);

    // Act: find and click the &lt;button&gt; element to increment
    // the counter in the &lt;p&gt; element
    cut.Find(&quot;button&quot;).Click();

    // Assert: first find the &lt;p&gt; element, then verify its content
    cut.Find(&quot;p&quot;).MarkupMatches(@&lt;p&gt;Current count: 1&lt;/p&gt;);
  }    
}

The documentation shows how to test components with Parameters and Cascading Values too.

Given this component

public class NonBlazorTypesParams : ComponentBase
{
  [Parameter]
  public int Numbers { get; set; }

  [Parameter]
  public List&lt;string&gt; Lines { get; set; }
}

You can test it using the parameters argument of RenderComponent

public class NonBlazorTypesParamsTest : TestContext
{
  [Fact]
  public void Test()
  {
    var lines = new List&lt;string&gt; { &quot;Hello&quot;, &quot;World&quot; };

    var cut = RenderComponent&lt;NonBlazorTypesParams&gt;(parameters =&gt; parameters
      .Add(p =&gt; p.Numbers, 42)
      .Add(p =&gt; p.Lines, lines)
    );
  }
}

huangapple
  • 本文由 发表于 2023年5月22日 16:34:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定