adifaidz's avatar

How should I test this method

Hi I'm quite new to testing and I want to know what kind of testing should I do with this piece of code

public function setCountry($data)
{
    //Some checks..
    
    //Get country
    $cc = array_get($data, 'data.country_code');
    $country = Country::where('cc', $cc)->first()->name;

    $this->country = $country;
}

Should I unit test or integration test this? Or even both? If so, how ?

0 likes
2 replies
bobbybouwmann's avatar
Level 88

In this case you are making a database call, because you fetch a model from the database. So it looks like an integration test. Your test might look like this:

Note that I assume your method is inside a controller

class SomeController extends Controller
{
    protected $country = null;

    public function setCountry($data)
    {
        $cc = array_get($data, 'data.country_code');
        $country = Country::where('cc', $cc)->first();

        $this->country = $country->name;
    }

    public function getCountry()    
    {
        return $this->country;
    }
}

In your test you can simply call this method and be done with it

class SomeControllerTest extends TestCase
{
    public function testSetCountryMethod()
    {
        $country = factory(App\Country::class)->create([
            'country_code' => 'nl',
        ]);

        $controller = new SomeController();
        $controller->setCountry([
            'data' => [
                'country_code' => 'nl',
            ],
        ]);

        // Here is your assertion
        $this->assertEquals('nl', $controller->getCountry());
    }
}

See here for the factory method that I'm using: https://laravel.com/docs/5.5/database-testing#introduction

If you want to unit test this you need to split your controller methods into smaller methods. For example

class SomeController extends Controller
{
    protected = $country = null;

    public function setCountry($data)
    {
        // Do your magic here

        $cc = array_get($data, 'data.country_code');
        $country = Country::where('cc', $cc)->first();

        $this_>setCountryCode($country->name);
    }

    public function setCountryCode($countryCode)
    {
        $this->countryCode = $countryCode;
    }

    public function getCountryCode()
    {
        return $this->countryCode;
    }
}

Now that you have split it up you can write a unit test for that specific method. That's homework for now ;)

adifaidz's avatar

Thanks for the quick reply, do I need to create a new record too for the unit test? Cause I've read somewhere that its not good to do that or is it just me overthinking it?

Please or to participate in this conversation.