c# - 防止在单元测试期间执行方法
问题描述
我正在尝试测试一个名为“PuntuadorJuego”(GameScore) 的类,它有一个方法“PuntuarXAcertar”(PointsIfMatching),它调用一个私有方法“Actualiza”(Update),它基本上更新 Unity 界面上的分数,如您在下面的代码,问题是每次我运行测试它都会停在那里。我已经尝试评论调用该方法的行并且它有效,但我想知道是否有任何其他方法可以防止在测试期间调用方法“Actualiza”,或者如果有一种方法可以忽略与接口相关的代码而更好测试。谢谢。
[Testing class]
public class PuntuadorTest
{
[Test]
public void TestPuntuacionAcertar()
{
//Assign
PuntuadorJuego puntuador = new PuntuadorJuego(puntuacion: 50);
//Act
puntuador.PuntuarXAcertar(esTurnoJ1: true);
//Assert
Assert.AreEqual(expected: 60, actual: puntuador.GetPuntuacionJ1());
}
}
[Method called by the tested Method]
private void Actualiza(int cantidad, bool esTurnoJ1)
{
if (esTurnoJ1)
{
if (puntuacionJ1 < 0)
{
ValorPuntuacionText.color = Color.red;
}
else
{
ValorPuntuacionText.color = Color.white; //THIS is the error line
}
ValorPuntuacionText.text = puntuacionJ1 + "";
}
else
{
if (puntuacionJ2 < 0)
{
ValorPuntuacionJ2Text.color = Color.red;
}
else
{
ValorPuntuacionJ2Text.color = Color.white;
}
ValorPuntuacionJ2Text.text = puntuacionJ2 + "";
}
if (cantidad < 0)
{
burbujaPuntuacion.color = Color.red;
}
else
{
burbujaPuntuacion.color = Color.green;
}
burbujaPuntuacion.text = cantidad + "";
burbujaAnimacion.Play("Puntua");
}
[Tested Method]
public void PuntuarXAcertar(bool esTurnoJ1 = true)
{
if (esTurnoJ1)
{
puntuacionJ1 += ACERTAR;
}
else
{
puntuacionJ2 += ACERTAR;
}
Actualiza(ACERTAR, esTurnoJ1);
}
PS:我正在使用 C#、Visual Studio 和 Unity。
解决方案
在 Unity 中使用测试程序集文件夹时,Unity 默认定义了一个名为UNITY_INCLUDE_TESTS
. 您可以将其与//#if
预#else
#endif
处理器指令一起使用,以便仅在运行测试时包含代码。例如:
public void MyMethod()
{
#if UNITY_INCLUDE_TESTS
// Test specific code
#else
// Production specific code
#endif
}
这是一个非常简单的解决方案,但在使用这种方法时要非常小心,因为如果您在测试期间排除代码,则该代码不会被测试!确保调查该Actualiza
方法导致错误的原因。
已经建议的另一种方法是使用模拟框架,例如Moq或NSubstitute。
推荐阅读
- angular - 角 | 初始化后如何扩展 FormGroup?
- python - 如何在 Selenium 和 Python 中通过 IEDriverServer 使用 DesiredCapabilities 类
- python - lxml - Translate from indirect url to direct url
- css - 使用不透明度时 CSS 下划线消失
- node.js - Firebase 身份验证:在后端获取用户信息
- netsuite - 基于 netsuite 令牌的身份验证
- java - 两个Java应用程序之间的Java spring boot JSON时间戳转换问题
- webpack - 更改 src 文件时 webpack 开发服务器未重新加载
- c# - 为什么 nuget 安装一堆系统命名空间引用?
- r - 在一个中绘制多个直方图