我试图测试一个名为 "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。
在你要测试的代码中混合UI调用是问题的根源。如果你是这里的游戏开发者,可以考虑重新组织,让 PuntuadorJuego
只确定分数,但不显示分数。其他代码可以同时调用 PuntuadorJuego
和 Actualiza
.
最好的方法是使用一些架构,把UI的东西分离出来,比如MVC、MVP、MVVM。我对Unity不熟悉,但google "Unity3d MVC","Unity3d MVP "和 "Unity3d MVVM "给了我几天的参考资料,如果我想看的话。 :-)
另外......MVP传统上是指Model-View-Presenter。我确实找到了一些Unity文章中MVP用在其他意思上,所以要注意。