首页 > 解决方案 > 如何对返回 Action 的方法进行单元测试?

问题描述

我正在尝试对这个返回的方法进行单元测试Action<SomeOptions>

public class MyOption
{
    public Action<SomeOptions> GetOptions()
    {
        return new Action<SomeOptions>(o =>
            {
                o.Value1 = "abc";
                o.Value2 = "def";
            }
        );
    } 
}

我想在我的测试中验证Value1"abc"并且Value2"def"

[Test]
public void GetOptions_ReturnsExpectedOptions()
{   
    var option = new MyOption();

    Action<SomeOptions> result = option.GetOptions();

    //Assert
    Assert.IsNotNull(result);

    //I also want to verify that the result has Value1="abc" & Value2 = "def"
}

我不确定如何测试验证结果是否具有Value1="abc"&的那部分代码Value2 = "def"

标签: c#unit-testingasp.net-core

解决方案


正如@Igor 评论的那样,您必须调用该操作并检查该操作的结果。试试这个:

[Test]
public void GetOptions_ReturnsExpectedOptions()
{
    var option = new MyOption();

    Action<SomeOptions> result = option.GetOptions();

    //Assert
    Assert.IsNotNull(result);


    //Assign SomeOptions and pass into the Action
    var opts = new SomeOptions();
    result(opts);
    Assert.AreEqual("abc", opts.Value1);
    Assert.AreEqual("def", opts.Value2);
}

推荐阅读