测试依赖和测试 get 和 setter 在一起

Test dependencies and testing get and setter together

我对单元测试和 TDD 很陌生,我怀疑现在是围绕下面的测试 运行:

class TypeTest extends TestCase
{
private $typeNameForTests = "staff";

public function setUp()
{
    parent::setUp();
}

public function testMake()
{
    $type = Type::make($this->typeNameForTests);

    $this->assertTrue(
        $type instanceof Type,
        "make() should return an instance of " . Type::class
    ); 

    return $type;
}

/**
*   @depends testMake
*/
public function testToString($type)
{
    $this->asserTrue(
        $type->__toString() == 'staff',
        "make() parameter should be set as the type name"
    );
}

/**
* @depends testMake
*/
public function testSetAndGetParent($type)
{
    $parent = $this->createMock(Type::class);

    $type->setParent($parent);

    $parent === $type->getParent();
}

}

我连接前两个测试的方式可以吗? 断言方法的 return 是必要的并且在这种情况下有意义吗?

测试依赖项 (testToString) 是否有意义?

在同一个测试中测试 Get 和 Set 怎么样?

感谢任何意见,因为我觉得我可能对某些原则考虑过多...

谢谢!

回答您的问题:

Is it ok the way I am concatenating the two first tests? Asserting the return of a method is necessary and makes sense on this case? Does the test dependency (testToString) makes sense there?

我不会在这两种情况之间引入依赖关系,因为它们实际上是两种截然不同的行为。第一种方法是测试创建新实例的 make() 方法的行为,第二种方法是测试转换为字符串的行为。

依赖测试应该是例外而不是规则。如果没有其他方法,请使用它们,例如在每个测试方法中重复调用太昂贵(想想集成测试中的网络调用等)。

And how about testing Get and Set in the same test?

我觉得还不错。您仍然涵盖相同的行为 - 一旦设置 parent 就可以访问它。

我的主要建议是开始专注于覆盖每个测试方法的单个行为,而不是覆盖单个方法。通常需要一个方法调用,但不是每次都这样。

我会将您的测试用例更新为:

  1. 尝试更好地命名您的测试方法。描述您期望的行为。使用 testIt...testItShould...

  2. 开始您的测试方法
  3. 与其专注于为每个生产方法添加测试方法,不如专注于描述行为(testMake vs testMakeCreatesNewType)。这样您就可以有多个测试方法来描述单个生产方法的行为。

  4. 避免@depends。它几乎从不需要,它只对集成测试有用,当你需要尽可能少地调用 I/O 时。单元测试应该是独立的。

  5. 关注每个测试用例的可读性。在此特定示例中,我认为私有 属性 不会使内容更具可读性。

  6. 使用更具体的断言以获得更好的反馈。使用更专业的断言,如 assertInstanceOfassertSame 等,可以在测试失败时为您提供更好的错误消息,从而减少对自定义消息的需求,并有效地提高测试的可读性。

  7. 去掉无用的setUp()。它只调用只会发出噪音的parent。

class TypeTest extends TestCase
{
    public function testMakeCreatesNewType()
    {
        $type = Type::make('staff');

        $this->assertInstanceOf(Type::class, $type); 
    }

    public function testItCanBeCastToString()
    {
        $type = Type::make('staff');

        $this->asserSame('staff', (string) $type);
    }

    public function testItExposesTheParent()
    {
        $type = Type::make('staff');
        $parent = $this->createMock(Type::class);

        $type->setParent($parent);

        $this->assertSame($parent, $type->getParent());
    }

    public function testItReturnsNullIfParentWasNotSet()
    {
        $type = Type::make('staff');

        $this->assertNull($type->getParent());
    }
}

这将使测试更具可读性、可维护性和可靠性。