Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit tests sometimes failing, sometimes passing

I have a mocha unit test suite.

When I run them locally, everything works fine. When I run them on our Jenkins CI server, they sometimes fail, sometimes pass.

I'm just not able to reproduce why they fail. What might cause this behavior?

like image 495
Sebastian Hoitz Avatar asked Sep 27 '12 14:09

Sebastian Hoitz


People also ask

Should all unit tests pass?

If the unit test doesn't work, it should be fixed or removed. If the SUT doesn't work, it means that you have a defect in your system. In that case, your highest priority should be to address the defect. At each check-in, all tests should pass.

Are unit tests a waste of time?

Unit testing is a waste of time, but it's a good way to test your code. You'll have to do it manually, and it's not always easy to fix problems. Testing is a way of getting things right, but you'll get stuck in testing time and have to deal with the problem.

Why are unit tests so hard?

Developers experience Unit Testing as difficult when they run into these kinds of problems: Classes are tightly coupled to other classes, which makes it hard to test because you need to control those other classes as well when you are writing your tests. This is very, very difficult and very error prone.


2 Answers

Tests can fail intermittently for a number of reasons and identifying why they fail is often revealing about your codebase and environment.

Here are a few possible causes:

• Shared objects - singletons that hold state can cause problems between tests if the test environment isn't reset to a well known state. if if your test runner executes tests in a non-deterministic order you may see random errors that are actually exposing corrupted state issues

• Environmental and external dependencies - any external object that can hold state can cause unpredictable results

• Timing - sometimes tests are written with timeouts or thread sleeps that are too specific. If the build server is operating under heavy load these timeouts may not be long enough

As general guidance, tests must be:

  • isolated: tests focus on one unit at a time
  • repeatable: produces the same results each time
  • independent: the order in which tests are executed should not matter
like image 136
bryanbcook Avatar answered Oct 09 '22 03:10

bryanbcook


I would try to narrow down the problem by reducing the number of executors to 1. If the tests are still failing intermittently, then you have a Test Run War, otherwise (given they run fine locally) it looks like a Resource Leakage.

More info at http://xunitpatterns.com/Erratic%20Test.html

like image 31
Tom Howard Avatar answered Oct 09 '22 03:10

Tom Howard