0

大家好,我在为 TestCaseSource 生成测试用例时遇到问题。我为测试编写了这段代码:

using System;
using System.Collections.Generic;
using System.Linq;

using NUnit.Framework;

namespace HeapSort.Tests
{
    [TestFixture]
    public class Tests
    {
        [Test, TestCaseSource(typeof(TestsGenerator),"TestCases")]
        public void IsEqualCollections(int[] received, int[] expected)
        {
            CollectionAssert.AreEqual(received, expected);
        }
    }

    public class TestsGenerator
    {
        public static IEnumerable<TestCaseData> TestCases
        {
            get
            {
                for (var i = 0; i < 25; i++)
                {
                    int[] t1 = GenerateCollection(i), t2 = t1.ToArray();
                    HeapSort.Sort(t1);
                    Array.Sort(t2);

                    yield return new TestCaseData(t1, t2);
                }
            }
        }

        private static int[] GenerateCollection(int seed)
        {
            var rnd = new Random(seed+DateTime.Now.Millisecond);
            int size = rnd.Next(100, 10000); 
            int[] array = new int[size];
                for (var i = 0; i < size; i++)
                    array[i] = rnd.Next(-100, 100);
            return array;

//            return Enumerable
//                .Repeat(100, rnd.Next(100, 10000))
//                .Select(i => rnd.Next(-100, 100))
//                .ToArray();
        }
    }
}

问题出在哪里?我得到的不是 25 个测试,而是从 1 到 8。通常在测试的起点它显示测试是 7/8,最后只有一个测试用例。

我怎么解决这个问题?

UPD1:有趣的是,当我通过控制台运行测试时,我处理了所有 25 个测试,我如何通过 GUI 获得相同的结果!?

PS对不起我的英语不好。

也许我应该提到我在 Rider 的 Ubuntu 下工作

4

2 回答 2

1

DateTime.Now is normally not very accurate. Your loop is generating many identical tests because they are all starting from the same seed. Why are you using a seed rather than simply letting Random work on its own?

Different runners will handle identical test in different ways. If you indicate what runner you are using to execute your tests, I can edit this answer with more information. However, in general, you most certainly don't want to generate a bunch of tests with the same data. They don't do anything for you!

于 2018-04-29T15:30:19.837 回答
0

原因是 TestExplorer 查看测试用例的名称并将具有相同名称的测试用例分组。所以你看不到所有的测试用例结果。原因是 TestExplorer 使用控制台运行测试没有相同的问题。详情请看这个问题。根据问题有两种解决方案:

  1. 为您的测试用例创建类并覆盖ToString()方法,使其为每个测试用例返回唯一值。
  2. 使用TestCaseData类及其方法SetName为每个测试设置唯一名称。
于 2020-07-10T20:22:03.270 回答