首页 > 解决方案 > 在 NUnit 测试中将数组传递给参数

问题描述

我正在学习 C# 并尝试将数组作为参数传递(这在我的代码中很好,但我似乎无法TestCase在 NUnit 中为其创建。我的文件是:

步行.cs:

using System;

namespace TenMinWalk
{
    public class Walk
    {
        static void Main(string[] args)
        {

        }

        public string Walking(Array[] newWalk)
        {
            if (newWalk.Length == 10)
            {
                return "true";
            }
            return "false";
        }

    }
}

WalkTests.cs:

using NUnit.Framework;
using TenMinWalk;

namespace TenMinWalkTests
{
    public class TenMinWalkTests
    {
        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void WalkMustOnlyLast10Minutes()
        {
            Walk walk = new Walk();
            string actual = walk.Walking(['w', 's', 'e', 'e', 'n', 'n', 'e', 's', 'w', 'w']);
            string expected = "true";
            Assert.AreEqual(actual, expected);

        }
    }
}

在我的测试文件中,显示的错误是:There is no argument given that corresponds to the required formal parameter 'newWalk' of 'Walk.Walking(Array[])'

我搜索了其他答案,可以看到如何将数组传递给函数,但似乎无法在我的测试文件中正确执行此操作。有人可以帮忙吗?(对不起,如果这个问题非常基础,但我对 C# 很陌生)

谢谢!

标签: c#nunit

解决方案


而不是传入Array[]您的 Walking() 方法,而是传递char array. 喜欢,

public string Walking(char[] newWalk)
   {
        if (newWalk.Length == 10)
        {
            return "true";
        }
        return "false";
   }

从 NUnit 测试中传递它时,创建 char 数组的实例并将其作为参数传递给函数。

喜欢,

    [Test]
    public void WalkMustOnlyLast10Minutes()
    {
        Walk walk = new Walk();
        var charArray = new char[] {'w', 's', 'e', 'e', 'n', 'n', 'e', 's', 'w', 'w'};
        string actual = walk.Walking(charArray);
        string expected = "true";
        Assert.AreEqual(actual, expected);

    }

老实说,我会通过直接计数而不是传递整个数组,因为您只是在检查数组的长度。

就像是,

   public bool Walking(int newWalkCount)
    {
        return newWalkCount == 10;
    }

在 NUnit 中,

    [Test]
    public void WalkMustOnlyLast10Minutes()
    {
        Walk walk = new Walk();
        var charArray = new char[] {'w', 's', 'e', 'e', 'n', 'n', 'e', 's', 'w', 'w'};

        //Passing length instead of entire array. Checking Assert.IsTrue()
        Assert.IsTrue(walk.Walking(charArray.Length));

    }

推荐阅读