2

I'm starting to wrap my head around PHPunit.

My questions is the following.

Whenever I use variables that do not change within my range of test methods I can initialize them within my setUp() method. Otherwise, if they do change, I should rather put them directly in my test methods.

Is my assumption more or less right?

  • I put the username into the setUp() method because it will not change.
  • The password comes directly into the functions because it needs to be changed in order to fail the test.

Example:

protected $username;

protected function setUp()
{
    $this->username = "Bob";
}

public function testUserCanLogInSuccessfully()
{
    $password = "Right_Password";   
    // code
}

public function testUserCanNotLogInSuccessfully()
{
    $password = "Wrong_Password";
    //code
} 
Magiranu
  • 33
  • 1
  • 3
  • 1
    @the downvoter (and close voter): I don't think this question is that bad. It's a question of how to best utilize the setup of a unit test, not "how do I use the setup". – Greg Burghardt Nov 17 '17 at 12:42

2 Answers2

1

The test setup is used to create the common initial state of all the unit tests in the current scope (in this case, a class).

The data in the variables can change as part of the test. If you find yourself copying and pasting code that comes before the assertion in every test method in the class, that is a good indicator it should go in the setup.

Likewise, if you find yourself copying and pasting code in each test after the assertions, then that code could be put in the teardown of your test class as well.

I like to think of the "setup" as a constructor-ish kind of method run before each test, and the "teardown" as a destructor-ish (or finalizer-ish) kind of method run after each test.

Greg Burghardt
  • 34,276
  • 8
  • 63
  • 114
0

In xUnit style tests a test class represents a test scenario, with each test method asserting something within that scenario. If you think of your tests in a “Given … When … Then …” scheme, the test class would represent the “Given” scenario.

The setUp() and tearDown() methods set up and destroy that scenario, so that each test method is isolated from the other test methods.

However, this test organization scheme is rarely used. More often, one test class would be used per tested unit, and there is not necessarily any shared setup between two test methods. So in the vast majority of cases, setUp() and teardown() will remain empty.

In your case, you do seem to have a kind of scenario along the lines “Given my name is Bob any my password is Right_Password …”, and your test methods are:

  • … When I log in with Right_Password Then I am logged in successfully.
  • … When I log in with Wrong_Password Then my login is rejected.

So that is a very good usage of the setUp() functionality.

amon
  • 132,749
  • 27
  • 279
  • 375