Writing good unit tests is an important part of software development. You can drastically decrease the number of bugs by writing tests correctly. However, not all unit tests are good. Badly written unit tests can be a big problem and will slow you down.


What Is a Unit?

You will first need to decide what you see as a unit. Is it one method? Is it a module? Or maybe a certain flow?

Not every unit is the same. For example, it might be a good idea to create a couple of unit tests for a method if it contains business logic. But when your method just passes some data from one class to another, that might not be necessary. In that case, it would be a better idea to test the whole module.

Let’s go over a couple of examples to demonstrate the different approaches.


Testing Methods With Business Logic

Let’s say that we have a Story class with a publish method. We are only allowed to publish a story if it has the DRAFT status.

class Story {
	    public constructor(private status: string) {}

	    public publish() {
	        if (this.status !== 'DRAFT') {
	            throw new Error('Failed to publish story');
	        }

	        this.status = 'PUBLISHED';
	    }

	    public getStatus(): string {
	        return this.status;
	    }
	}

In this case, it would make sense to write a unit test for the method, as it contains an important business rule. To completely cover this rule, we would need to create two unit tests:

  • Test if an Error is thrown when the status is notDRAFT.
  • Test if the status is changed to PUBLISHED when the status is DRAFT.
describe('Story business logic test', () => {
	    test('Publish method throws error if status is not DRAFT', () => {
	        const story = new Story('PUBLISHED');

	        expect(story.publish()).toThrow('Failed to publish story')
	    });

	    test('Draft story can be published', () => {
	        const story = new Story('DRAFT');
	        story.publish();

	        expect(story.getStatus()).toEqual('PUBLISHED');
	    });
	});
view raw
story.test.ts hosted with ❤ by GitHub

By only testing the method, we can keep our unit tests small. This is especially useful when testing difficult business logic. Try to always cover every branch of your business logic.

It can be a good idea to use a code coverage reporter to see which part of the code is tested.

#programming #learning #software-development #unit-testing #tdd

How to Write Good Unit Tests
1.10 GEEK