我已经开始为if语句编写第一个单元测试,希望在没有输入时显示错误。每当我运行测试时,它被识别出来,但它显示为一个错误,没有错误信息,我不知道为什么。
//The test
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practice_1._0
{
[TestClass]
public class MyFirstProgramTest
{
public const string V = "";
public object IgnoreCase { get; private set; }
[TestMethod]
public void ExactResults()
{
String expectedAnswer = ("good");
String expectedAnswer1 = ("bad");
String expectedAnswer2 = ("poorly");
string actualAnswer = V;
Assert.AreEqual(IgnoreCase,expectedAnswer, expectedAnswer1, expectedAnswer2, actualAnswer,"please Enter an Emotion!");
}
}
}
// the if statement
static void Main(string[] args)
{
Console.WriteLine("Tell me how you are?");
string userInput = Console.ReadLine();
if (userInput == $"Good")
{
Console.WriteLine("Great, have a good day!");
}
else if (userInput == "bad")
{
Console.WriteLine("Hey it could be worse!");
}
else if (userInput == "poorly")
{
Console.WriteLine("Get better soon!");
}
else if (userInput == "no")
{
Console.WriteLine("Oh just tell me!");
}
else
{
Console.WriteLine("please! Tell us how you feel!");
}
我希望这段代码将引导您了解单元测试的概念以及如何正确地进行单元测试。首先,我将您的if语句提取到方法:
public string IfStatment(string userInput)
{
if (userInput == $"Good")
{
return "Great, have a good day!";
}
else if (userInput == "bad")
{
return"Hey it could be worse!";
}
else if (userInput == "poorly")
{
return"Get better soon!";
}
else if (userInput == "no")
{
return"Oh just tell me!";
}
else
{
return"please! Tell us how you feel!";
}
}
然后写一个简单的测试检查所有的可能性
[TestMethod]
public void TestMEthod()
{
Assert.AreEqual("Great, have a good day!",IfStatment("Good"));
Assert.AreEqual("Hey it could be worse!",IfStatment("bad"));
Assert.AreEqual("Get better soon!",IfStatment("poorly"));
Assert.AreEqual("Oh just tell me!",IfStatment("no"));
Assert.AreEqual("random string",IfStatment("please! Tell us how you feel!"));
}
请考虑到这只是一个如何解决这个问题的例子,但正如建议的那样,您应该首先掌握基本知识