Unit Testing - 101

Tere Bentikh
Feb 25, 2017 · 2 min read

Unit Testing is a practice where we create tests (Test Class) that validates our code (original classes)

As per #TDD we should first create a test class before creating our original code, which is another subject, but here we will talk about testing your code in general

To create a test class in intelliJ, click on the class name, press Alt + Enter, then select “create test”

After creating your test class you can create a test method with a descriptive name that indicates what exactly this test method validates and what is the expected result ... Like :

@Test
public void addPositiveNumber_returnTrue() throws Exception{...}

Then you put your validation code inside this method in a three steps process … #AAA :

Arrange :

prepare the instances to be used in testing the actual logic

Act :

perform operation that uses the original code to return the expected result

Assert :

assert / validate the result of the operation done … which is the ending result of your test methods … the simplest way is using :

Assert.assertTrue(…)

Notice that for each test method it should be testing one thing only, holding one Assert statement only, and its name describes what are the parameters of the test, and what is the expected return value.

Also test methods are meant to be simple and readable.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade