【问题标题】:Unit testing of complex objects C#复杂对象的单元测试 C#
【发布时间】:2021-03-29 12:35:45
【问题描述】:

我写了一个简短的应用程序,但是我遇到了编写单元测试方法MaximumRowSum_DefectiveLines的问题。请告诉我应该如何行动,我的测试课

public class OutputtingStrings
{
    public class MaxSumLineResult
    {
        public int MaxSumLineIndex { get; set; }
        public List<string> DefectiveLines { get; set; }
        public override string ToString()
        {
            return $"Line number with maximum sum of elements: { MaxSumLineIndex + 1}"; /* + "\n" +
                 $"Defective lines:{string.Join("\n", DefectiveLines)}";*/
        }
    }

    public static bool IsValidateFileExist(string filePath)
    {
        if (File.Exists(filePath))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public MaxSumLineResult MaximumRowSum_DefectiveLines(string[] fileData)
    {
        List<string> defectiveLines = new List<string>();
        int lineNumber = 0;
        var indexOfLines = new Dictionary<int, double>();
        foreach (var line in fileData)
        {
            NumberStyles style = NumberStyles.Number;
            CultureInfo culture = CultureInfo.CreateSpecificCulture("en-GB");

            var stringElements = line.Split(",",  StringSplitOptions.RemoveEmptyEntries);
            if (stringElements.Any(n => double.TryParse(n, style, culture, out var number)))
            {
                indexOfLines.Add(lineNumber, stringElements.Sum(n =>
                {
                    return double.Parse(n, style, culture);
                }));
            }
             else  
            {
                 defectiveLines.Add(line);
            }

            lineNumber++;

        }
        var maxSumLineIndex = indexOfLines.FirstOrDefault(x =>
           x.Value == indexOfLines.Values.Max()).Key;

        var resultLines = new MaxSumLineResult
        {
            MaxSumLineIndex = maxSumLineIndex,
            DefectiveLines = defectiveLines
        };

        return resultLines;
    }
}

我的单元测试课:

[TestClass]
public class UnitTestOutputtingStrings
{
    [TestMethod]
    public void Should_FindingMaximumRowSum_TheFileIsValidAndReadable()
    {
        /* Arrange*/
        var maxsumlineresult = new MaxSumLineResult();
        var sut = new OutputtingStrings();

        /* Act*/

        /* Assert*/
    }
}

我读过《单元测试的艺术。用 C# 中的示例》一书。我了解这些原则,但我不知道如何处理复杂的类。提前谢谢你们,我会很高兴每个答案或链接到带有单元测试材料的来源。

【问题讨论】:

  • 准备一些测试字符串数组,调用MaximumRowSum_DefectiveLines并检查返回值。
  • 构建一个您可以在脑海中轻松解决的示例。然后检查您的方法的返回值是否与预期的输出匹配,如果您使用该示例字符串数组提供您的方法。
  • @Klaus Gütter 谢谢!

标签: c# .net unit-testing


【解决方案1】:

肯定在方法上,责任太大了。 我认为开始的好主意是将方法分成多个更小的方法。之后,对该方法的单元测试将更容易完成。

【讨论】:

  • 也许你是对的,必须尊重单一责任原则。
  • 这似乎更像是一个建议而不是一个答案。也许它应该在 cmets 中而不是作为答案发布?
猜你喜欢
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多