Pregunta

I discovered that stub and mock are very helpful in testing. But I wondering about one thing. I think an example will show it clearly.

Class A {
    public function isOk() {
        // some work
    }

    public function iAmDepend() {
        if ($this->isOk()) {
            // do work
        }
    }
}

class TestA {
    public function testIsOk() {
        // Test itOk here
    }

    public function testIAmDepend() {
        mock(A)->method(isOk)->return(true);
        // tests for iAmDepend
    }

}

It wise to do something like this? Stub method of tested class. Or maybe it breaks some rules?

PS. I can't refactore code

¿Fue útil?

Solución

Your examples are correct, i.e. testIsOk tests only IsOk, and testIAmDepend only IAmDepend.

But there is important difference between mock and stub that you have to understand: difference between mock and stub.

In your example, if testIAmDepend is verifying that isOk has been called with some arguments and this is part of your assertion for unittest, this is mock. Otherwise this is stub, and you aren't going to verify that it has been called or not.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top