Mutable static variables are bad, let me explain..

I was sitting at my desk in the late evening, writing tests. After a few hours every single test was passing and it seemed there were no bugs. Right before heading to bed I ran all the tests together to make sure it’s alright. Then this happend:

Each test passes on its own but not together

I was pretty confused. Every test succeed before. Sure enough, when I ran those two tests by themselves, they worked as expected. But when running all tests together the last two failed. WTF.

The first reaction was obviously: “My code must be working, it has to do something with the way tests are executed! Maybe tests are playing in parallel and thus interfering with each other? Maybe it is because I used the same keys?”.

Brian Egan point out to me that deleting one particular test fixed the bug and moving it to the top made all other tests fail too. If that doesn’t scream “SHARED DATA” then I don’t know what does.

When I found out what the problem was I just couldn’t stop laughing. It was exactly the reason why using static variables are considered bad in certain situations.

Basically, the predefined animations were all static. I was too lazy to write a method for each animation taking all the parameters that a VillainAnimation needs. So I made the VillainAnimation mutable (bad idea). This way I didn’t have to explicitly write all the necessary parameters into the method. This looked like this when using it:

Villain(

villainAnimation: VillainAnimation.fromBottom(0.4)

..to = Duration(milliseconds: 150),

child: Text("HI"),

)

The test which broke everything was supposed to test villain transitions starting after the page transition finished. It set the starting point of the animation to 1 second. Because it was setting it on a static reference, the test after that used that as the default. The tests failed because an animation can’t run from 1 second to 750 milliseconds.

The fix was pretty easy (making everything immutable and passing the arguments in the method) but I still found this little bug quite entertaining.