无法将类型void隐式转换为int [英] Cannot implicitly convert type void to int
问题描述
我正在为现有项目创建单元测试.
I'm creating a unit test for an existing project.
-
n1
和n2
是输入数字 -
op
是主程序中切换情况下的操作数
n1
andn2
are input numbersop
is operands in a switch case in the main program
问题出在 actual
上.我无法匹配期望值和实际值,因为出现错误无法将void隐式转换为int
.
The problem is with actual
. I cannot match the expected and actual value because I get the error cannot implicitly convert void to int
.
我的单元测试:
[TestMethod()]
public void docalcTest(int actual)
{
Form1 target = new Form1(); // TODO: Passenden Wert initialisieren
double n1 = 15; // TODO: Passenden Wert initialisieren
double n2 = 3; // TODO: Passenden Wert initialisieren
int op = 2; // TODO: Passenden Wert initialisieren
int expected = 5;
actual = target.docalc(n1, n2, op);
Assert.AreEqual(expected,actual);
}
docalc的代码:
The code for docalc:
public void docalc(double n1, double n2, int op)
{
result = 0;
setText("clear");
switch (op)
{
case 1:
result = n1 + n2;
break;
case 2:
result = n1 - n2;
break;
case 3:
result = n1 * n2;
break;
case 4:
result = n1 / n2;
break;
}
setText(result.ToString());
}
推荐答案
您的方法 target.docalc()
是一个空方法,而 actual
是一个int.如编译器所说,您不能将 void
分配给 int
.
Your method target.docalc()
is a void method, while actual
is an int. You can't assign void
to an int
, as the compiler says.
根据您的评论(您实际上应该只编辑您的问题),您的 docalc()
看起来像这样:
According to your comment (you really should just edit your question), your docalc()
looks like this:
public void docalc(double n1, double n2, int op)
{
result = 0;
...
setText(result.ToString());
}
您必须将方法的返回类型更改为 int
,然后返回结果:
You'll have to change the return type of the method to int
, and return result:
public int docalc(double n1, double n2, int op)
{
int result = 0;
...
return result;
}
旁注,为什么要这么做?
Sidenote, why do you do this?
[TestMethod()]
public void docalcTest(int actual)
{
...
actual = ...
将在不带参数的情况下调用测试方法,因此该方法有点用处.您可能需要将其更改为:
The test method will be called without parameters, so it's a bit useless there. You might want to change it to:
[TestMethod()]
public void docalcTest()
{
...
int actual = ...
这篇关于无法将类型void隐式转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!