DEV Community

beatriz gracia
beatriz gracia

Posted on

How to use Junit and Mockito for unit testing in Java

Originally posted on whathebea.github.io on 23/10/2022

I know today is Sunday but I really felt like writing something. It seems like I can't stop thinking about coding and trying to perfect everything that I am learning. This may be personal but, does anyone else feel this way? Before my internship although I was very dedicated it seems that now I am much more focused. Also, I lost two Valorant matches in a row so I'm feeling a bit down. Maybe writing a post is a way of distracting myself from my losses...

Ok, so today I decided to talk about testing. Answering the question "Why is testing so important?" which I asked myself and talking a little bit about tools and some more things.

Why is testing important?

Imagine you wrote some code and then, later, someone changes something on it. If you have tests ready is very easy to know if the code still works as expected. If you don't have tests, you will have to test the code manually. This is very time consuming and it is very easy to miss something, also, it is expensive, especially if you are working on a big project.

Junit

What is Junit? Junit is a unit testing framework for Java. It is used to test the smallest unit of code, which is a method.

Here is an example of a Junit test:

@Test
public void testAdd() {
    int result = calculator.add(1, 2);
    assertEquals(3, result);
}
Enter fullscreen mode Exit fullscreen mode

When you are testing you must use the @Test annotation. The assertEquals method is used to check if the result of the method is the same as the expected result. If the result is not the same as the expected result, the test will fail.
Here is a test that will fail:

@Test
public void testAdd() {
    int result = calculator.add(1, 2);
    assertEquals(4, result);
}
Enter fullscreen mode Exit fullscreen mode

It fails because 1+2 is not equal to 4.

Mockito

What is Mockito? Mockito is a mocking framework for Java. It is used to mock the dependencies of the class that you are testing.

To use Mockito you have to use @Mock and @InjectMocks annotations. The @Mock annotation is used to create a mock object. The @InjectMocks annotation is used to inject the mock object into the class that you are testing. Here is a full example:

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    public void testGetUserById() {
        User user = new User();
        user.setId(1);
        user.setName("Beatriz");

        when(userRepository.findById(1)).thenReturn(Optional.of(user));

        User result = userService.getUserById(1);

        assertEquals(user, result);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example I am testing the getUserById method of the UserService class. I am mocking the UserRepository class because the UserService class depends on the UserRepository class. I am using the when method to mock the findById method of the UserRepository class. I am using the thenReturn method to specify what the findById method will return. In this case it will return an Optional object that contains a User object. I am using the assertEquals method to check if the result of the getUserById method is the same as the expected result, which is the User object that I created manually.

Test Coverage

Test coverage is a measure of how many lines of code are executed during the tests. It is used to measure how much of the code is tested. There are different types of test coverage, but the most common one is the line coverage. It measures how many lines of code are executed during the tests.
IBM has an article talking about how to see your Junit test coverage and you can read it here.

TDD (Test Driven Development)

TDD means Test Driven Development and the name itself is pretty self-explanatory. It is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only.
There are different types of TDD, but the most common one is the Red-Green-Refactor cycle. It is a cycle that consists of three steps:

  1. Write a test
  2. Run the test
  3. Refactor the code

So you pretty much write the test and then you write the code to make the test pass. Then you refactor the code to make it more readable and efficient. IBM has a lot of free content about TDD and you can read it here.

Conclusion

I hope my post was helpful! I feel like it really helps me to write about what I learn. I have to push myself a little bit to make code examples and write about it, but I think it is worth it. I hope you liked it and if you have any questions or suggestions, please let me know in the comments! Thanks for reading!

Resources

Top comments (1)

Collapse
 
khmarbaise profile image
Karl Heinz Marbaise • Edited

Using JUnit Jupiter you can remove the public modifier from the class as well as the methods

public class UserServiceTest..
Enter fullscreen mode Exit fullscreen mode

like:

class UserServiceTest..
Enter fullscreen mode Exit fullscreen mode

Furthermore:

@Test
public void testAdd() {
    int result = calculator.add(1, 2);
    assertEquals(4, result);
}
Enter fullscreen mode Exit fullscreen mode

you can do like this:

@Test
void testAdd() {
    int result = calculator.add(1, 2);
    assertEquals(4, result);
}
Enter fullscreen mode Exit fullscreen mode

also I would suggest to remove the name prefix test...