【问题标题】:How do I unit test this class?我如何对这个类进行单元测试?
【发布时间】:2010-07-15 15:23:44
【问题描述】:

假设我需要从遗留代码中为以下类添加单元测试(目前没有单元测试)。它只是一个简单的地图或字典。

function Map(...) { ... }
Map.prototype.put = function (key, value) {
    // associate the value with the key in this map
}
Map.prototype.get = function (key) {
    // return the value to which the specified key is mapped, or undefined 
    // if this map contains no mapping for the key
}
Map.prototype.equals = function (obj) { ... }
// ... and more bound functions

似乎没有办法一次只测试一个功能。例如,您不能在不调用 put() 的情况下测试 get()。如何对此进行单元测试?

【问题讨论】:

  • 如果我们知道 put 和 get 做什么会很有帮助。
  • 它只是一个简单的字典,就像 java.util.Map 或 Python 的 dict

标签: javascript unit-testing


【解决方案1】:

如果您可以存根或模拟所有其他方法的方法之间存在严重依赖关系。请查看jsMock

【讨论】:

  • 我在上面说“可以”...我的意思是“应该”!
【解决方案2】:

每个方法都有一个显式或隐式的契约。 Map.put() 接受某种输入并改变 Map 内部或外部的某些内容。为了测试该功能,您的测试需要访问已变异的内容。如果它是内部的并且没有暴露在外部,那么您的测试必须存在于 Map 类中,状态必须暴露,或者可变状态结构必须以外部访问仍然可能的方式注入到类中: 即:

/*Definition*/

function MockRepository() { /*implementation of the repository*/ }
function Map(repository) { /* store the repository */ }
Map.prototype.put = function() { /* mutate stuff in the repository */ }

/*Instantiation/Test*/
var mockRepository = new MockRepository(); /*mock repository has public methods to check state*/
var myMap = new Map(mockRepository);
myMap.put(/*whatever test input*/);
/* here use the mock repository to check that mutation of state occurred as expected based on ititial state of respository and input */

【讨论】:

    【解决方案3】:

    如果您正在使用数据库,对于“get”方法,您可以在数据库中创建带有插入的 DbScript,然后获取那些插入的项目。 那么你必须创建 DbScripts 来删除那些添加的项目。 对于“put”测试,您必须调用 get 方法来检查它是否被插入。

    你只需要在你的测试基类中配置它。

    [TestFixtureSetUp]
            public virtual void InitializeTestData()
            {
                TestConfiguration.ExecuteSqlFilesInFolder(this.DefaultScriptDirectory + "\\SetUp");
                if (!string.IsNullOrEmpty(this.TestFixtureSpecificScriptDirectory))
                {
                    TestConfiguration.ExecuteSqlFilesInFolder(this.TestFixtureSpecificScriptDirectory + "\\SetUp");
                }
            }
    
    [TestFixtureTearDown]
            public virtual void FinalizeTestData()
            {
                if (!string.IsNullOrEmpty(this.TestFixtureSpecificScriptDirectory))
                {
                    TestConfiguration.ExecuteSqlFilesInFolder(this.TestFixtureSpecificScriptDirectory + "\\TearDown");
                }
    
                TestConfiguration.ExecuteSqlFilesInFolder(this.DefaultScriptDirectory + "\\TearDown");
            }
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      相关资源
      最近更新 更多