Javascript 我如何对这个类进行单元测试?

Javascript 我如何对这个类进行单元测试?,javascript,unit-testing,Javascript,Unit Testing,假设我需要从遗留代码(目前还没有单元测试)中为以下类添加单元测试。它只是一个简单的地图或字典 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 speci

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

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()。如何对其进行单元测试?

如果您使用的是数据库,那么对于“get”方法,您可以在数据库中创建带有插入项的dbscript,然后获取这些插入项。 然后您必须创建用于删除这些添加项的dbscript。 对于“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");
        }

每个方法都有一个契约,显式或隐式。put()接受某种类型的输入,并对映射的内部或外部内容进行变异。为了测试该功能,您的测试需要访问变异的内容。如果它是内部的,而不是外部公开的,那么您的测试必须存在于Map类内部,状态必须公开,或者可以外部访问的方式将可变状态结构注入到类中: 即:


如果这两种方法之间存在严重的依赖性,您可以对所有其他方法进行存根或模拟。。看看这个。

如果我们知道put和get的用法,会很有帮助。它只是一个简单的字典,就像上面java.util.Map或Python的dict所说的“can”。。。我的意思是“应该”!
/*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 */