Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay if unit tests depend on each other?

Tags:

unit-testing

What if tests share and mutate some common state, and their logic depends on previous tests? Is it acceptable practice? Simple code for example (js):

describe('Some tests', () => {
  const state = {
    value: 'test'
    addMe() {
      this.value = this.value + ' me'
    }
    addPlease() {
      this.value = this.value + ', please'
    }
  }

  it('Some test', () => {
    state.addMe()
    expect(state.value).toBe('test me')
  })

  it('Another test', () => {
    state.addPlease()
    expect(state.value).toBe('test me, please')
  })
})
like image 988
heleg Avatar asked Oct 22 '18 15:10

heleg


People also ask

Should unit tests depend on each other?

Tests should never depend on each other. If your tests have to be run in a specific order, then you need to change your tests. Instead, you should make proper use of the Setup and TearDown features of your unit-testing framework to ensure each test is ready to run individually.

Should each unit test be independent?

Good unit tests should be reproducible and independent from external factors such as the environment or running order. Fast. Developers write unit tests so they can repeatedly run them and check that no bugs have been introduced.

What are two limitations of unit testing?

Limitations of Unit Testing Unit testing cannot detect integration or interfacing issues between two modules. It cannot catch complex errors in the system ranging from multiple modules. It cannot test non-functional attributes like usability, scalability, the overall performance of the system, etc.


1 Answers

Typically, tests should be designed not to depend on each other. This is certainly not a law, but a good practice, because it gives your test suite a number of nice properties:

  1. With independent tests, you can add tests at any place, delete tests, re-order tests without unexpected impacts on other tests.

  2. You can improve tests individually without having to think about impact on other tests, for example simplifying the internal working of a test.

  3. Every test can be understood without looking at other tests, and in case of failing tests the reason for the failure is easier to find.

  4. Independent tests succeed and fail individually. With dependent tests, if one test fails, subsequent tests likely also fail.

  5. You can execute your tests selectively, for example to save time during test case execution.

like image 163
Dirk Herrmann Avatar answered Oct 19 '22 05:10

Dirk Herrmann