1

I'm writing unit tests for a project I'm working on and I'm trying to figure out how to effectively write tests to test this.

I currently have the following methods:

  • Object::createNew()
  • Object->delete()

My concern is how do I write unit tests to properly test this effectively because I'm having a hard time thinking about how to "tie" these functions together. So for example,

<?php

public function testObjectCreation() {
    $object = Object::createNew("my parameters");

    // ... asserts

    // I don't want to keep the object so I delete it
    // but I don't want test that deleting works here too, I want to separate it
    $object->delete();
}

// Where would I get an object to test that deleting works?
public function testObjectDeletion() {
    // ...stuff
    $object->delete();
}

public function testUnrelatedObjectFunctions () {}

So my question is, how could I feed one object to the other function. Would I have to make testObjectCreation() be static and then feed it to testObjectDeletion() with @dataProvider or would I have to store $object in a private/protected variable that would only be used in these two functions? If I make it static, wouldn't I lose access to the assert functions provided by PHPUnit?

1 Answer 1

1

This looks like a good case for the @depends annotation. This allows you to return something in one test and use it as a parameter in another.

Here is an example from the phpunit docs:

public function testEmpty()
{
    $stack = array();
    $this->assertEmpty($stack);

    return $stack;
}

/**
 * @depends testEmpty
 */
public function testPush(array $stack)
{
    array_push($stack, 'foo');
    $this->assertEquals('foo', $stack[count($stack)-1]);
    $this->assertNotEmpty($stack);

    return $stack;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for! Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.