-2

I'm having a problem. I have a unit test that is trying to access methods from a class. My unit test is as follows

public function testReverseArraySuccess()
    {
        $data = "This is a test.";

        $output = (new Reverse)
            ->setInput($data)
            ->get();

        $this->assertEquals(['test', 'a', 'is', 'This'], $output);
    }

My class is a follows

class Reverse
{
    public $input;

    /**
     *
     * @param $data
     */
    public function setInput($data) {
        $this->input = $data;
    }

    /**
     *
     *@return void
     */
    public function get()
    {
        return $this->input;
    }
}

How can I setup my class so that my Test will pass? The error I get when I run the test is.

Error : Call to a member function get() on null

Eric Evans
  • 640
  • 2
  • 13
  • 31
  • I just want to know how to set my class so that I can access the class and methods of the class like it does in the test. @hakre – Eric Evans Jul 10 '21 at 22:30
  • Yes it gives my the error that's in my question. – Eric Evans Jul 10 '21 at 22:32
  • When I run the test it gives me this error. "Call to a member function get() on null" – Eric Evans Jul 10 '21 at 22:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234732/discussion-between-eric-evans-and-hakre). – Eric Evans Jul 10 '21 at 22:34
  • possible duplicate: https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php - OPs problem has been solved. – hakre Jul 10 '21 at 22:46

2 Answers2

0

setInput isn't chainable since it's not returning an instance of itself. It's a void function that returns null by default that's why you're getting that error message. Update setInput to return an instance of the class to make it chainable.

public function setInput($data) {
    $this->input = $data;
    
    return $this;
}

Now get will return whatever value is passed to the input property, here's a working demo.

Then it's a matter of reversing the input, but I'll leave that up OP.

Kim Hallberg
  • 1,165
  • 1
  • 9
  • 18
0

You need to call get data directly after set data by instance of Reverse class.

public function testReverseArraySuccess() {

   $data = "This is a test."; 

   $output = new Reverse;
   $output->setInput($data);

   $this->assertEquals(['test', 'a', 'is', 'This'], $output->get());
}