Any real word example about how setUp() and tearDown() should be used in PHPUnit?

前端 未结 4 1550
温柔的废话
温柔的废话 2021-02-02 08:27

Methods setUp() and tearDown() are invoked before and after each test. But really, is there any real word example about why should I need this?

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 08:57

    You could use this almost anytime you would have a dependency within the class you are testing. A classic example of this might be some sort of object storing application state (a session object, a shopping cart, etc.).

    Say for example I had a class that was going to calculate shipping costs on the contents of a shopping cart defined by a cart object. And let's say this shopping cart is passed into the shipping calculation class via dependency injection. To test most methods of the class you might need to actually instantiate a cart object and set it in the class in order to unit tests your various methods. You might also need to add items into the cart ass well. So you might might have a setup like this:

    public function setUp()
    {
        $this->cart = new cart();
        $this->cart->add_item('abc');
        $this->cart->add_item('xyz');
    }
    

    Let's also assume your test methods might actually modify the cart's items, decorating them with shipping cost information. You don;t want information from one test bleeding into the next, so you just unset the cart at the end.

    public function tearDown()
        unset($this->cart);
    }
    

提交回复
热议问题