php - Is it a good practice to define expectation in dataProvider

591

quick example of dataProvider:

return [
   ['180d-1pc', '6m-1pc'],
]

and test:

public function  test_convert($title, $expected)
{
    $uut = new Converter();
    $this->assertEquals($expected, $uut->convertDayTitle($title));
}

(simply put: test if we convert 180d(days) to 6m(months)) as you can see - in data provider there are input data defined and also an expected output.

This works fine in many cases, but I keep having this feeling that maybe it's not the best idea. So I'm wondering if could be considered bad practice. If so - when I will see it was a bad idea to do it?

One example is, when you would like to use the same dataProvider in two tests - should you define two expected values and use one of them?

Quick example (I just made that up, so don't pay attention that I make product object just from title ;)):

public function test_gets_discount_when_licence_period_longer_than_1year($title, $expectedTitle, $expectedDiscount) {
 $prod = new Product($title);
 $this->assertEquals($expectedDiscount, $product->hasDiscount();
}

How to make this more elegant?

459

Answer

Solution:

What you're doing is totally fine. Data providers can, and should, include the expected test result.

About the issue of reusing the same dataProvider for 2 tests, and only using some fields: I'd say that if the fields are related (i.e. they are properties of the same object), it can be acceptable.

If you feel the dataProvider is getting too big and complex because 2 tests must use data from it, just create 2 separate dataProviders, and use another private common method for building the common data.

People are also looking for solutions to the problem: Phalcon PhP - how to use named routes inside a controller

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.