首页 > 解决方案 > 防止在单元测试期间执行方法

问题描述

我正在尝试测试一个名为“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。

标签: c#unit-testingunity3dtestingnunit

解决方案


在 Unity 中使用测试程序集文件夹时,Unity 默认定义了一个名为UNITY_INCLUDE_TESTS. 您可以将其与//#if#else#endif处理器指令一起使用,以便仅在运行测试时包含代码。例如:

public void MyMethod()
{
#if UNITY_INCLUDE_TESTS
    // Test specific code
#else
    // Production specific code
#endif
}

这是一个非常简单的解决方案,但在使用这种方法时要非常小心,因为如果您在测试期间排除代码,则该代码不会被测试!确保调查该Actualiza方法导致错误的原因。

已经建议的另一种方法是使用模拟框架,例如MoqNSubstitute


推荐阅读