DEV Community

David Lartey
David Lartey

Posted on Edited on

Dynamic Config Values for Each PHPUnit Test Case in Laravel

This was originally posted on my blog

Problem:

I am currently working on a USSD application that supports switching between different gateway providers at runtime by changing a configuration value.

Testing each provider test case was simple and straight forward. I would update the value in my phpunit.xml file and off I go. However, I ran into problems when I wanted to run my entire test suite.

Solution:

It turns out the solution is quite a simple one: Facades. Laravel allows one to mock any Facade when writing your tests. The documentation however, discourages from mocking the Config facade. Instead one should use the Config::set method.

So, I did something along the lines of the code below.

<?php
// define your namespace and dependencies here

use Illuminate\Support\Facades\Config;

class GatewayProviderOneTest extends TestCase
{
    public function setUp ()
    {
        parent::setUp();
        Config::set("defaultGatewayProvider", "firstProvider");
    }

    // ... your test methods come here
}
Enter fullscreen mode Exit fullscreen mode

That’s all I needed. Now GatewayProviderOneTest will run its assertions against the value set as the defaultGatewayProvider: firstProvider.

Additionally, you can revert this to a default value every time in your tearDown method. I however didn’t need to do this.

Top comments (8)

Collapse
 
espiramarvin profile image
Marvin Espira •

I'm curious to know how you implemented your USSD

Collapse
 
dbilovd profile image
David Lartey •

Hi Marvin,

USSD use to also sound complex for me but after a while, I noticed it was just APIs. So if you can build APIs, you can build a USSD application.

If you're just getting started I built a Laravel (Package) to make it really to build USSD applications. You can find it here: github.com/dbilovd/php-ussd.

It was actually when I was building this package that I learnt the issue I wrote about in the post.

If you need any help, do let me know.
Thanks

Collapse
 
espiramarvin profile image
Marvin Espira •

okay thank you..lemme try it out

Collapse
 
kennankole profile image
Kennedy •

Do you also write tests for the USSD requests???

Thread Thread
 
dbilovd profile image
David Lartey •

Hi @kennankole

I do by simulating a few things. One is the external API responses and another, the session states, especially for subsequent screens.

Collapse
 
derdusm profile image
Derdus Mosoti •

USSD is all APIs, but you need to understand a thing or 2 in the GSM network.

There is a very comprehensive course on USSD and SMS featuring the Africa's Talking #USSD gateway here skillsday.co/courses/building-and-...

It can be very helpful @espiramarvin

Collapse
 
espiramarvin profile image
Marvin Espira •

Thank you so much

Some comments may only be visible to logged-in visitors. Sign in to view all comments.