我的项目是一个机器人电报.我有一个名为Mainclass的类.我想测试它的一个方法(SubmitNewsGetType).这个方法没有输入和输出.这个方法检查从用户收到的消息并发送适当的响应.这是我的辩护类和方法.
public class MainClass
{
enum state : int
{
_firstState = 0,
_submitNewsGetType = 1,
_submitNewsGetNews = 11,
_reservationGym = 2,
_reservationGymGetSans = 22,
_pollingForFood = 3,
_appointment = 4,
_cancelingReservation = 5,
_cancelingAppointment = 6,
Registeration = 7
};
public TelegramBot bot;
private int stateBot;
public Message sendMessage;
private string tempString;
public Message message;
private MessageTarget target;
public void SubmitNewsGetType()
{
if (message.Text.Contains("/submitnews"))
{
sendMessage = bot.SendMessage(target, "Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return");
}
else if (message.Text.Contains("/Elmi") ||
message.Text.Contains("/Farhangi") ||
message.Text.Contains("/Honari") ||
message.Text.Contains("/Amoozeshi") ||
message.Text.Contains("/Varzeshi"))
{
sendMessage = bot.SendMessage(target, "Please enter your news: \n\n/Return");
stateBot = (int)state._submitNewsGetNews;
tempString = message.Text;
}
else
{
bot.SendMessage(target, "Non definded! Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return");
}
}
这是我的单元测试.我的问题是我无法初始化消息类型.
[TestMethod]
public void SubmitNewsGetNews_Test()
{
MainClass instance = new MainClass();
Message mess_output;
//How to set value for a Message type??
//This line get error
Message mess_input="/submitnews"
string expected="Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return";
if (mess_input is "/submitnews")
{
a.SubmitNewsGetType();
mess_output= a.sendMessage;
Assert.AreEqual(mess_output.Text,expected);
}
else if (mess_input is "/elmi" or "/farhangi" or ...)
else if ....
}
最佳答案 >创建涵盖TelegramBot功能的界面,并使TelegramBot实现它.
interface ITelegramBot
{
Message SendMessage(MessageTarget target, string msg);
}
>将机器人成员的类型更改为ITelegramBot
public ITelegramBot bot;
>创建TelegramBot的“假”类
class TelegramBotFake : ITelegramBot
{
public Message ReturnMessage { get; set; }
public string SendedMessage { get; set; }
public Message SendMessage(MessageTarget target, string msg)
{
this.SendedMessage = msg;
return this.ReturnMessage;
}
}
>测试.尽量使任何逻辑操作远离测试方法.任何逻辑都可能包含错误,测试方法中的错误很难发现.
为您的方法中的每个可能结果创建自己的测试 – 您将需要多个…
[TestMethod]
public void SubmitNewsGetNews_MessageContainsSubmitItems_SendPleaseSelectType()
{
const string SUBMITITEMS = "/submitnews";
TelegramBotFake fakebot = new TelegramBotFake();
MainClass instance = new MainClass();
instance.bot = fakebot; //Assign our fake bot
instance.message.Text = SUBMITITEMS;
string expected = "Please select a type news: \n/Elmi\n/Farhangi\n/Honari\n/Amoozeshi\n/Varzeshi\n\n/Return";
instance.SubmitNewsGetType();
//By checking faking bot.SendedMessage we sure that right method was executed
Assert.AreEqual(instance.bot.SendedMessage, expected);
}