首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >简单单元测试-解析无效输入以抛出错误C# Visual Studio

简单单元测试-解析无效输入以抛出错误C# Visual Studio
EN

Stack Overflow用户
提问于 2017-05-05 11:13:12
回答 4查看 1.4K关注 0票数 1

我有一个非常基本的方法,可以将两个双精度值相除。对于单元测试,我希望包含一个无效的输入(字符串)来抛出错误消息或异常。解析值或测试失败(预期)的最简单方法是什么?

CalculatorClass.cs

代码语言:javascript
运行
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Calculator
{
    public class CalculatorClass
    {
        //METHODS
        public double Divide(double num1, double num2)
        {
            double result = num1 / num2;
            return result;
        }
    }
}

UnitTest1.cs

代码语言:javascript
运行
复制
using System;
using Calculator; //ADD REFERENCE
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CalcMethodTest
{
    //AreEqual
    //AreNotEqual
    //AreNotSame
    //AreSame
    //Equals
    //Fail
    //Inconclusive
    //IsFalse
    //IsInstanceOfType
    //IsNotNull
    //IsNull
    //IsTrue
    //ReplaceNullChars

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void _1_3_Test_Divide_Input_Seven_2_Output_Error()
        {
            //ARRANGE
            CalculatorClass calcObj = new CalculatorClass();
            string expectedOutput = "Error - Invalid Input";
            //ACT

            //----HERE WRONG DATA TYPE FOR TESTING----
            double result = calcObj.Divide("Seven", 2);
            //ASSERT
            Assert.AreEqual(expectedOutput, result);
        }
    }
}
EN

回答 4

Stack Overflow用户

发布于 2017-05-05 11:23:32

因为您的Divide方法接受double,double的输入,所以您使用的string错误数据类型不能用作输入。

为了允许输入为string或number,我建议您将参数类型更改为两者通用的基类(比如object),如果过程无法完成(或者发生异常,由您决定),则通过解析返回数据的false来扩展Divide,类似于.Net提供的TryParse方法。如果您觉得合适的话,还可以扩展out变量以包含error string

而且,比起Divide,更合适的名称是TryDivide

代码语言:javascript
运行
复制
namespace Calculator {
  public class CalculatorClass {
    //METHODS
    public bool TryDivide(object num1, object num2, out double doubleVal, out string errorString) {
      doubleVal = 0;
      errorString = string.Empty;

      try {
        if (num1 == null || num2 == null) {
          errorString = "number(s) cannot be null";
          return false;
        }

        double num = 0, den = 0;
        bool parseResult;

        if (num1 is double)
          num = (double)num1;
        else {
          parseResult = double.TryParse(num1.ToString(), out num);
          if (!parseResult) {
            errorString = "numerator cannot be parsed as double";
            return false;
          }
        }

        if (num2 is double)
          den = (double)num2;
        else {
          parseResult = double.TryParse(num2.ToString(), out den);
          if (!parseResult) {
            errorString = "denominator cannot be parsed as double";
            return false;
          }
        }

        doubleVal = num / den;
        return true;

      } catch (Exception ex) {
        errorString = ex.ToString();
        return false; //may also be changed to throw
      }
    }
  }
}

此时,您将能够使用string输入调用您的TryDivide

代码语言:javascript
运行
复制
double doubleResult;
string errorString;
bool result = calcObj.TryDivide("Seven", 2, out doubleResult, out errorString);
if (!result){ //something is wrong
    Console.WriteLine(errorString);        
}
票数 1
EN

Stack Overflow用户

发布于 2017-05-05 11:19:38

不能在需要double参数的地方传递string。如果您绝对需要能够将string参数传递给此方法,则不应期望它会因为它是无效类型而失败-只有在转换到double失败的情况下。在这种情况下,我会尝试从stringdouble的一些基本解析(但是,在这种情况下,您可能只想解析"7",而不是“7”-这取决于您)。

您编写的代码将永远无法测试,纯粹是因为它永远不会使用C#进行编译。

票数 0
EN

Stack Overflow用户

发布于 2017-05-05 11:41:31

如果您只想测试单元测试中的异常处理,以及如何通过传递错误的参数来使测试失败,请看此示例。

代码语言:javascript
运行
复制
public class Sum
{
    //Returns the sum of 2 positive odd integers
    //If either of arguments is even, return -1
    //If either of arguments is negative, throw exception
    public int PositiveSumOddOnly(int a, int b)
    {
        if(a < 0 || b < 0)
            throw new InvalidArgumentException("One or more of your arguments is negative");
        if(a%2 == 0 || b%2 == 0)
            return -1;
        return a + b;
    }
}

[TestClass]
public class Sum_Test
{
    [TestMethod]
    public int PositiveSumOddOnly_ShouldThrowInvalidArgumentExecption(int a, int b)
    {
        Sum s = new Sum();
        try
        {
            int r = s.PositivesumOddOnly(1,-1);
        }
        catch(InvalidArgumentException e)
        {
            Assert.AreEqual("One or more of your arguments is negative", e.Message);
        }
    }
    [TestMethod]
    public int PositiveSumOddOnly_ShouldReturnNegativeOne(int a, int b)
    {
        Sum s = new Sum();
        int r = s.PositiveSumOddOnly(1,2);
        Assert.AreEqual(r,-1);
    }

    [TestMethod]
    public int PositiveSumOddOnly_ShouldReturnSumOfAandB(int a, int b)
    {
        Sum s = new Sum();
        int r = s.PositiveSumOddOnly(1,1);
        Assert.AreEqual(r,2);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43795909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档