启动Visual Studio MSTest项目的好方法?



>我正在VS 2017上为旧软件的新模块启动一个测试项目。我是TDD和单元测试的新手,所以我想知道这是否是正确的方法......

我首先测试如何将对象添加到视图模型类的列表中:

[TestClass]
public class RTCM_Config_Test
{
static RTCM_Bouton input = new RTCM_Bouton();
static RTCM_Sortie output = new RTCM_Sortie();
[TestMethod]
public void CreateConfig()
{
//Arrange
//Act
RTCM_Config conf = new RTCM_Config();
//Assert
Assert.IsNotNull(conf);
}
[TestMethod]
public void AddNewInputInConfig()
{
//Arrange
RTCM_Config conf = new RTCM_Config();
//Act
bool isOk = conf.CreateElements(input);
//Assert
Assert.IsTrue(isOk);
}
[TestMethod]
public void AddNewOutputInConfig()
{
//Arrange
RTCM_Config conf = new RTCM_Config();
//Act
bool isOk = conf.CreateElements(output);
//Assert
Assert.IsTrue(isOk);
}
}

视图模型中的 CreateElements 函数:

public bool CreateElements(RTCM_Bouton btn)
{
if (listButtonsInput == null) return false;
if (btn == null) return false;
if (listButtonsInput.Count >= 10) return false;
return true;
}
public bool CreateElements(RTCM_Sortie sortie)
{
if (listButtonsOutput == null) return false;
if (sortie == null) return false;
if (listButtonsOutput.Count >= 10) return false;
return true;
}

在测试方法之前,我将静态输入和输出对象声明为测试参数,这是好方法吗?还是应该在每个测试方法中声明测试对象?

谢谢!

我不是 100% 确定你的问是什么,但我认为你问如何处理你传递的参数,RTCM_Bouton btn 和 RTCM_Sortie 出击。

public bool CreateElements(RTCM_Bouton btn)
{
if (listButtonsInput == null) return false;
if (btn == null) return false;
if (listButtonsInput.Count >= 10) return false;
return true;
}

这段代码对我来说有 4 个可能的返回值或路由,所以我需要 4 个测试,通常我遵循命名约定MethodName_Scenario_ExpectedResult

CreateElements_ListButtonsIsNull_ReturnsFalse()
CreateElements_BtnIsNull_ReturnsFalse()
CreateElements_ListButtonsIsNull_ReturnsFalse()
CreateElements_ListInputButtonsIs10orMore_ReturnsTrue()

您应该使用测试的//arrange 部分来"设置"测试,包括该方法需要运行的任何内容。使用最少的实现创建类和需要传递的任何对象(刚好足以使测试通过(。

所以例如

[TestMethod]
CreateElements_BtnIsNull_ReturnsFalse()
{
//arrange
RTCM_Config conf = new RTCM_Config();
var RTCM_Bouton btn = null;
//act
var result = conf.CreateElements(btn);
//assert
Assert.IsFalse(result);
}

因为RTCM_Bouton对于某些测试需要为 null,而对于其他测试需要是值,所以我会在每个测试安排方法中声明它,而不是像全局变量那样声明它。

对于 const 测试对象RTCM_Config,您可以使用类变量并在测试 initialize 方法中对其进行初始化:

private RTCM_Config _config;
[TestInitialize]
public void TestInitialize()
{
_config = new RTCM_Config();
}

在我看来,任何减少代码的东西都是受欢迎的。您也可以为按钮引入一个类变量,但必须为每个测试用例重新排列它。

二、你的第二个问题,你可以使用数据驱动测试。

[DataTestMethod]        
[DataRow(60, 13d)]
[DataRow(1800, 44d)]
public void Testcase(int input, double expected)
{
//Do your stuff
}

祝您编码愉快!

相关内容

最新更新