简体   繁体   English

单元测试 - 依赖测试

[英]Unit Testing - dependent tests

I am creating a list of unit tests that are dependent on each other. 我正在创建一个相互依赖的单元测试列表。 For example, my first test creates a record in the database and checks that the return value is greater than 0. 例如,我的第一个测试在数据库中创建一条记录,并检查返回值是否大于0。

The second test then checks the data of the record created in the first test. 然后第二个测试检查在第一个测试中创建的记录的数据。 However, it needs the ID of the record produced in the first test. 但是,它需要在第一次测试中生成的记录的ID。

Originally I called the second test from within the first test so that I could pass the ID as a parameter, which worked fine except this meant that essentially there was only one test. 最初我在第一次测试中调用了第二个测试,这样我就可以将ID作为参数传递,这很好用,除非这意味着基本上只有一个测试。

I created an ordered list with the ID declared outside the scope but after the first unit test this value returns to 0 so obviously the second unit test fails. 我创建了一个有序列表,其ID在范围之外声明,但在第一次单元测试之后,此值返回0,因此显然第二个单元测试失败。

Is there any way to create the tests so that they share the value produced in the first test? 有没有办法创建测试,以便它们共享第一次测试中产生的值?

The code is below: 代码如下:

[TestMethod]
public void TestNewLandlord_InsertIntoImportFiles_ReturnFileID()
{
    try
    {
        DataSet ds = EngineBllUtility.InsertIntoImportFiles(connString, @"C:\Documents and Settings\dTrunley\My Documents", "HFISNewLandlordTest.csv",
        "TestNewLandlord()", WindowsIdentity.GetCurrent().Name, "HFIS Landlords", "NA", 30247531, false);

        importFileId = long.Parse(ds.Tables[0].Rows[0]["ImportFileID"].ToString());
        Assert.IsTrue(importFileId > 0);
    }
    catch (Exception ex)
    {
        Assert.Fail(ex.Message);
    }
}

[TestMethod]
public void TestNewLandlord_InsertIntoImportFiles_CorrectData()
{
    try
    {
        using (SqlConnection connectionString = new SqlConnection(connString))
        {
            using (SqlCommand sqlCommand = new SqlCommand(
                String.Format("SELECT * FROM [mydeposits].[import].[ImportFiles] WHERE [ImportFileID] = {0}", importFileId), connectionString))
            {
                connectionString.Open();
                using (SqlDataReader dr = sqlCommand.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        bool correctData = true;
                        dr.Read();
                        if (!dr["ImportFileStatusID"].ToString().Equals("1"))
                            correctData = false;
                        if (!dr["HeadOfficeMemberID"].ToString().Equals("247531"))
                            correctData = false;
                        Assert.IsTrue(correctData);
                        TestCleanup();
                    }
                    else
                        throw new Exception("Import does not exist in database");
                }
            }
        }
    }
    catch (Exception ex)
    {
        Assert.Fail(ex.Message);
        TestCleanup();
    }
}

I am creating a list of unit tests that are dependent on each other. 我正在创建一个相互依赖的单元测试列表。 For example, my first test creates a record in the database and checks that the return value is greater than 0. 例如,我的第一个测试在数据库中创建一条记录,并检查返回值是否大于0。

In my opinion, such approach is incorrect. 在我看来,这种方法是不正确的。 You may create evil code that's going to bite you back. 你可能会制造出会让你反感的邪恶代码。 Such code: 这样的代码:

  • breaks the unit test principles 打破了单元测试原则
  • is hard to maintain 难以维持
  • is very rigid, cumbersome and error-prone 非常僵硬,笨重且容易出错

Unit tests must be independent , or else don't write them at all. 单元测试必须是独立的 ,否则根本不写。 The reason for that is as the complexity of your software grow - so does the complexity of tests. 原因在于软件的复杂性增加 - 测试的复杂性也随之增加。 If you have one test depends on others maintenance of the tests become a burden. 如果你有一个测试取决于其他人维护测试成为负担。 So the cost of software increases, but the quality of code - doesn't. 因此,软件的成本增加,但代码的质量却没有。 If you do not have dependencies between tests - the complexity of software doesn't matter as you can test each individual piece of functionality separately. 如果您在测试之间没有依赖关系 - 软件的复杂性并不重要,因为您可以单独测试每个单独的功能。

Another advantage is that you can run tests in parallel. 另一个优点是您可以并行运行测试。 For large systems, it is important that the Continuous Integration (and Deployment) cycle is fast. 对于大型系统,持续集成(和部署)周期很快很重要。 By running tests in parallel you could significantly speed up yout release cycle. 通过并行运行测试,您可以显着加快发布周期。

Suggested solution 建议的解决方案

What you are trying to accomplish are possibly the integration tests. 您要完成的任务可能是集成测试。 One way to write them would be to create a separate project for such tests. 编写它们的一种方法是为这些测试创建一个单独的项目。 Each test will still be independent of each other, but probably each test would require some SetUp and TearDown in NUnit test terms. 每个测试仍将彼此独立,但可能每个测试都需要NUnit测试术语中的一些SetUpTearDown So the SetUp would prepare everything that is required for the integration tests to pass and TearDown would perform a clean up after each test. 因此,SetUp将准备集成测试所需的所有内容,TearDown将在每次测试后执行清理。

That's very naughty, however you can un comment (if created by the test wizard or add) 这很顽皮,但你可以不发表评论(如果由测试向导创建或添加)

//You can use the following additional attributes as you write your tests:

//Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
}

//Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
}

//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
}

//Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
}

No different as such to mocking up some common tests data, though just as dubious. 与模拟一些常见的测试数据没有什么不同,尽管同样可疑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM