Php 测试之间的相关性

Php 测试之间的相关性,php,phpunit,Php,Phpunit,我尝试使用phpunit在几个类之间建立依赖关系来进行一系列测试。我有3门课,A、B和C,每门课都有测试。A有5项测试,B 3项测试和C 3项测试 B对A进行依赖测试,C对A进行依赖测试,A最终测试取决于B和C测试 class A extends TestCase { public function test1(){} // @depends test1 public function test2(){} // @depends test2 publ

我尝试使用
phpunit
在几个类之间建立依赖关系来进行一系列测试。我有3门课,A、B和C,每门课都有测试。A有5项测试,B 3项测试和C 3项测试

B对A进行依赖测试,C对A进行依赖测试,A最终测试取决于B和C测试

class A extends TestCase {

    public function test1(){}

    // @depends test1
    public function test2(){}

    // @depends test2
    public function test3(){}

    // @depends test3
    public function test4(){}

    // @depends test3
    // @depends B::test3
    // @depends C::test3
    public function test5(){}

}

class B extends TestCase {

    // @depends A::test1
    public function test1(){}

    // @depends B::test1
    public function test2(){}

    // @depends B::test2
    // @depends A::test4
    public function test3(){}

}

class C extends TestCase {

    // @depends A::test1
    public function test1(){}

    // @depends C::test1
    public function test2(){}

    // @depends C::test2
    // @depends A::test4
    public function test3(){}

}

在本例中,我的问题是跳过了A::test5、B::test3和C::test3。

您的测试设计非常糟糕

您应该能够独立运行所有测试

如果您需要预先设置某些数据,请使用
setup()
方法或测试方法本身进行设置

正如已经指出的,如果您有外部依赖项,请模拟它们

如果您有一组测试都需要相同或相似的数据,那么将该设置代码放入基类中,然后通过测试扩展它是完全可以接受的。像这样的

class AppTestCase extends TestCase
{
    public function setUp()
    {

        // this will be run before every test class that extends this class.  So make your test user/product here.

        // you can invoke all your mocking in here to if thats easier, 
        // just make sure the resulting mock objects are all in visible 
        // properties to be accessed elsewhere
    }

    public function tearDown()
    {
        // if youre functional testing, remove test data in here. This will fire after each test has finished in any class that extends this one.

    }
}


class A extends AppTestCase
{
    public function setUp()
    {
        parent::setUp();

        // do other, class specific setup stuff here.

    }

    public function test1()
    {
        // your test data will be setup for you by the time you get here.
        // if you only have 1 test and it needs adapted base data, do it here,
        // if you have lots of tests in here, override and extend the `parent::setUp()` method.
    }
}

然后在所有测试中重复该模式。

我可以问一个问题吗?选择这种设计的原因吗?外部依赖项应该在单元测试中模拟。类a创建用户,类B和C从外部服务添加一些关于用户的额外数据,以及测试删除用户的最后一个测试,所以我必须在删除B类和C类之前运行所有测试。@Yoleth避免测试之间的依赖关系。您应该单独测试三个类。如果你关心它们的行为,就编写一个集成测试。@JakubZalas,这是非常正确的,但几乎不适用于上下文。我可能不得不说“依赖于其他类”,而不是“外部依赖”。似乎这种搭配倾向于触发与嘲笑外部服务节的关联。