我有一个非常基本的方法来划分两个双精度值。 对于单元测试,我想包含一个无效的输入(字符串)来抛出错误消息或异常。解析值或测试失败(预期)的最简单方法是什么?
计算器类.cs
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;
}
}
}
单元测试1.cs
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);
}
}
}
由于您的Divide
方法接受double,double
的输入,因此您使用的string
错误的数据类型不能用作输入。
为了允许输入string
或编号,我建议您将参数类型更改为两者共有的基类(例如,object
),然后通过尝试解析数据来扩展Divide
false
- 如果过程无法完成(或者如果发生异常, 由您决定),类似于.Net
提供TryParse
方法。您还可以扩展out
变量以包含错误string
(如果认为合适)。
此外,比Divide
更合适的名称是TryDivide
:
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
:
double doubleResult;
string errorString;
bool result = calcObj.TryDivide("Seven", 2, out doubleResult, out errorString);
if (!result){ //something is wrong
Console.WriteLine(errorString);
}
您无法传递需要double
参数的string
。如果绝对需要能够将string
参数传递给此方法,则不应期望它基于它是无效类型而失败 - 仅当转换为double
失败时。在这种情况下,我会尝试将string
解析为double
(但是在这种情况下,您可能只想解析"7",而不是"七" - 不过由您决定)。
你写的东西永远无法得到测试,纯粹是因为它永远不会使用 C# 编译。
如果您只想测试单元测试中的异常处理以及如何通过传递错误的参数来使测试失败,请查看此示例。
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);
}
}
这似乎有效:
[TestMethod]
public void _1_3_Test_Divide_Input_Seven_2_Output_Error()
{
//ARRANGE
CalculatorClass calcObj = new CalculatorClass();
string expectedOutput = "Error - Invalid Input";
//ACT
//----CHANGED TO STRING. THEN CAST BACK TO DOUBLE INSIDE METHOD----
string result = calcObj.Divide("Seven", "2");
//ASSERT
Assert.AreEqual(expectedOutput, result);
}
方法:
public string Divide(string num1, string num2)
{
string resultMsg = "";
try
{
double num1Dbl = double.Parse(num1);
double num2Dbl = double.Parse(num2);
double result = num1Dbl / num2Dbl;
resultMsg = result.ToString();
return resultMsg;
}
catch (FormatException error)
{
resultMsg = "Error - Invalid Input";
return resultMsg;
}
}