如何对只调用其他函数的函数进行单元测试?

bat*_*man 6 javascript unit-testing

我的代码库(旧版)中有一个函数,它具有:

function test()
{
 method1("#input a")
 method2("test")
 method3(1,2)
}
Run Code Online (Sandbox Code Playgroud)

鉴于它调用 other 的事实methods,如何为这些类型的函数编写一个好的单元测试?

Dan*_*vah 4

首先,我认为您所描述的这种行为甚至不需要进行单元测试。但是,如果您确实需要检查是否使用特定参数(甚至任何参数)调用方法。有一种方法可以做到这一点,您可以使用像 ShortifyPunit 这样的模拟框架: https: //github.com/danrevah/ShortifyPunit

请按照以下步骤操作:

  1. 确保附加到可以模拟的对象的方法
  2. 将模拟对象注入到您的类中并存根方法
  3. 您可以 verify() 使用特定参数调用方法

例如,如果您的类正在使用依赖项注入,这对于单元测试至关重要,如下所示:

class SomeClass {

    private $obj;

    public function __construct($obj) {
        $this->obj = $obj;
    }

    public function test()
    {
        $this->obj->method1("#input a")
        $this->obj->method2("test")
        $this->obj->method3(1,2)
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以编写一个单元测试,如下所示:

public function testMethodCalled()
{
    $mockedObj = ShortifyPunit::mock('object');

    $class = new SomeClass($mockedObj);

    // Stub the methods so you could verify they were called
    ShortifyPunit::when($mockedObj)->method1(anything())->returns(1);
    ShortifyPunit::when($mockedObj)->method2(anything())->returns(2);
    ShortifyPunit::when($mockedObj)->method3(anything(), anything())->returns(3);

    $class->test(); // run test() method

    // Verify it was called
    $this->assertTrue(ShortifyPunit::verify($mockedObj)->method1(anything())->calledTimes(1));
    $this->assertTrue(ShortifyPunit::verify($mockedObj)->method2(anything())->calledTimes(1));
    $this->assertTrue(ShortifyPunit::verify($mockedObj)->method3(anything(), anything())->calledTimes(1));
}
Run Code Online (Sandbox Code Playgroud)