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')
})
})
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.
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.
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.
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:
With independent tests, you can add tests at any place, delete tests, re-order tests without unexpected impacts on other tests.
You can improve tests individually without having to think about impact on other tests, for example simplifying the internal working of a test.
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.
Independent tests succeed and fail individually. With dependent tests, if one test fails, subsequent tests likely also fail.
You can execute your tests selectively, for example to save time during test case execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With