使用动态单元测试

时间:2011-03-29 14:25:39

标签: c# unit-testing dynamic

我在这里看到一些人要求批评他们的单元测试的问题。我似乎没有被关闭,所以我想做同样的事情。

我掀起了这些测试,我相信使用dynamic可以使这些测试更具可读性,但我想知道SO社区中是否有人有任何要添加的内容。

我知道动态的使用出于某种原因非常有争议,并且由于某种原因在C#开发者之间开始宗教战争。我真的希望避免这种情况;我只是想写一些好的测试来帮助我完成我的工作:)

    [TestMethod]
    public void TestAllocation() {
        SearchView.StubPropertyNumValueThenSetUpSearchView<WellDetail>("TX", Property.WorkingInterestTaxSubtypeId);
        Presenter.SetUpPhaseAndFmvValues(Phase.PhaseIdForForRenderAppraiser, 1000);

        AddTheseItems(
            new { PropNum = "pn1", CAN = "can1", MostRecentFmv = 10 },
            new { PropNum = "pn1", CAN = "can1", MostRecentFmv = 10 },
            new { PropNum = "pn1", CAN = "can1", MostRecentFmv = 10 },
            new { PropNum = "pn1", CAN = "can1", MostRecentFmv = 10 },

            new { PropNum = "pn1", CAN = "can2", MostRecentFmv = 40 },
            new { PropNum = "pn1", CAN = "can2", MostRecentFmv = 40 },
            new { PropNum = "pn1", CAN = "can2", MostRecentFmv = 40 },

            new { PropNum = "pn2", CAN = "can1", MostRecentFmv = 50 },
            new { PropNum = "pn2", CAN = "can1", MostRecentFmv = 50 });

        Presenter.Process(SearchView, ItemsToProcess);

        AssertTheseItemsExist(
            new { NumberOfTimes = 4, PropNum = "pn1", CAN = "can1", FmvCalculated = 100 },
            new { NumberOfTimes = 3, PropNum = "pn1", CAN = "can2", FmvCalculated = 400 },
            new { NumberOfTimes = 2, PropNum = "pn2", CAN = "can1", FmvCalculated = 500 });
    }

    private void AddTheseItems(params dynamic[] MassUpdateDtos) {
        foreach(dynamic item in MassUpdateDtos)
            ItemsToProcess.Add(new MassFMVUpdateDTO(new WellDetail() { PropertyNum = item.PropNum, CountyAccountNum = item.CAN }, new FMVHistory(), 0, item.MostRecentFmv));
    }

    private void AssertTheseItemsExist(params dynamic[] uniqueTargets) {
        foreach (dynamic target in uniqueTargets)
            Assert.AreEqual(target.NumberOfTimes, ItemsToProcess.Count(f => f.PropertyNum == target.PropNum && f.CountyAccountNum == target.CAN && f.FMV == target.FmvCalculated));
    }

1 个答案:

答案 0 :(得分:2)

确保使用动态减少了您需要使用的代码行。但首先想想你想从单元测试中得到什么。您希望他们告诉您代码出错的地方。

如果您添加的其中一行数据错误,它会告诉您哪一行失败了吗? 如果其中一个断言失败了,它会告诉你哪一个吗?

只要你能得到你需要的信息,你应该没问题。所以它应该确切地说明出了什么问题以及它何时出错。