jeudi 24 août 2017

Is this practice good on phpunit?

when I'm coding I see often stuff like this:

     testMyMethod() {
        ....
        $mockMyServiceB
            ->expects($this->once())
            ->method('myMethodA')
            ->with(myvalue1, myvalue2, myvalue3)
            ->willReturn($someMockResult);

        $myServiceA = new ServiceA($mockMyServiceB)
        $results = $myServiceA->something(); // this produce a call to myMethodA()

        $this->assertEquals(['resultA', 'resultB'], $myServiceA->something());            
     }

Not sure, but I think that as you write more and more tests, this make them to loose readability quickly and so easy. You just put too much info (expects mixed with returns).

I was thinking to move the code to something where you just test the correct use of myMethodA, and later another test where you can focus only on results, like this:

  testMyMethodUseServiceBCorrectly() {
    ....
    // this time no WillReturn, just focus on how is used
    $mockMyServiceB
        ->expects($this->once())
        ->method('myMethodA')
        ->with(myvalue1, myvalue2, myvalue3);

    $myServiceA = new ServiceA($mockMyServiceB)
    $myServiceA->something(); 
 }


  testMyMethodUseServiceResults() {
    ....
    // this time no Expects() or With(), just focus on results
    $mockMyServiceB
        ->method('myMethodA') 
        ->willReturn(myvalue1, myvalue2, myvalue3);

    $myServiceA = new ServiceA($mockMyServiceB)
    $this->assertEquals(['resultA', 'resultB'], $myServiceA->something());
 }

I think this makes clear what you are testing, and also produce smaller tests. But not sure if is also usual.....is a recommended practice?

Aucun commentaire:

Enregistrer un commentaire