Skip to content
Advertisement

PHPUnit tests isolation and how to write a test where expected value depends on some value in method that changes often

So I am coding in PHP and am writing tests with PHPUnit. I have this method convertCashAmountToMainCurrency that i want to test:

JavaScript

And i have the Constants that are being used here:

JavaScript

I am testing the method like this:

JavaScript

And the tests passes just fine when the expected value and the currency rate are stated in fixed size. But the problem is that i need them to pass every time, regardless of the currency convertion rate value, so i would not need to rewrite the tests every time the rate changes. Because now, if i change the RATE (or even the PRECISION, for instance) value, the tests will not pass due to assertion failure.

Since I was told that I need to isolate my tests to solve this issue, can anyone confirm this and get me on a right path with solving the issue? Thanks in advance for any help!

Advertisement

Answer

The problem is that convertCashAmountToMainCurrency is relying on global state. There are ways to handle this in tests, but to me that’s not good practice. My suggestion is to extract the conversion into a new class that gets all required information passed in. That way it does not depend on global state and can be tested easily in isolation.

This could look something like this:

JavaScript
JavaScript
JavaScript

If you can’t get rid of the existing static method, just create a converter with the configuration from the global state.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement