vendredi 16 novembre 2018

Laravel Unit Test Alwalys Return OK

I am new on PHPUnit testing, and I need some help if posible. I am trying to write unit test for my controller and service. My controller;

public function addToBasket(Request $request){

    $data = $this->mapRequest($request);
    return $this->service->addToBasket($data);
}

And my service is;

public function addToBasket($data){

    $validatedData = Validator::make($data, array(
        'customerid' => 'required',
        'productid' => 'required',
        'total' => 'required',
        'attid' => 'required'));
    try {

        $validatedData->validate();
    } catch (\Exception $e){
        return array(
            'status' => false,
            'code' => 9,
            'message' => config('exception_codes.9').'<br/>'.$validatedData->errors(),
            'data' => []
        );
    }
    try {

        $cart = new Basket();
        foreach ($data as $key => $val) {
            $methodName = "set" . ucfirst($key);
            $cart->$methodName($val);
        }
        $cartProductId = $this->cartRepository->addToCart($cart);
        return array(
            'status' => true,
            'code' => 0,
            'message' => config('exception_codes.0'),
            'data' => [
                'cartProductId' => $cartProductId
            ]
        );
    } catch (\Exception $e){
        return array(
            'status' => false,
            'code' => 10,
            'message' => config('exception_codes.10'),
            'data' => []
        );
    }
}

My unit test for these;

class testCartService extends TestCase { public $SUT;

public function setUp()
{
    parent::setUp();
    $this->SUT = new CartService();

}

public function testAddToBasket()

{
    $mock = \Mockery::mock(\Illuminate\Http\Request::class)->makePartial();

    $mock->shouldReceive('addToBasket')->andReturn(['includes' => ['customerid', 'productid', 'total', 'attid']]);

    $result_actual = $this->SUT->addToCart($mock);


    $result_expected = array([
        'status' => true,
        'code' => 0,
        'message' => config('exception_codes.10'),
        'data' => ['cartProductId' => 25455
        ]]);
    $this->assertSame($result_expected, $result_actual);
}

}

message that I always receive when I run;

OK (2 tests, 2 assertions).

If there is a mistake in the service or other error, I always turn OK.Can you help me please?

Aucun commentaire:

Enregistrer un commentaire