Spring Boot Unit Test Annotations with Junit 5 -Service Layer -doReturn , whenReturn , @Before, @Spy

Kubra Ozer
3 min readOct 15, 2020

--

This article is all about unit test by using junit for service layer. I explained the controller layer unit test in my first article. You can see the following link, if you need.

I will explain all method about unit test that is used in my code . Let’s get started.

Firstly, I want to show you some differences about methods that look as if they are same.

Mockito: doReturn vs thenReturn

These methods specify what to return when a method is called. In most cases , when-thenReturn is preferred because of readability. However, they have some differences

  • doReturn is not type safety.Unlike the doReturn , thenReturn checks method return types and if there is an unsafe type , it raises compile error.
  • doReturn is no side effect. This is an advantage, although there is no type safety. If you use spied object that is annotated with @Spy doReturn doesn’t call the method at all .
  • thenReturn calls the real method and you need to handle exceptional case, you need to mock the throw maybe.
  • If there is no side effect you can use thenReturn for a spied object, although this can be risky . You need to be sure about that :)

What about Spy ?

A spy in mockito is a partial mock. So If you use objects methods , it is a real method invocation for spied object. So as i mentioned above , this can cause some side effects

This link is good explanation about their differences and you can see the usage of doReturn in the example of that article.

@BeforeEach vs @BeforeAll

Lastly, I want to tell you about @BeforeEach and @BeforeAll annotations. The method annotated with @BeforeEach is executed before each test , as it is name signifies :) . On the other side , @BeforeAll annotation provides runs once before the entire test class.

Generally , if multiple tests share same code you can use @BeforeAll (in Junit 4 @BeforeClass) .Establishing database connection can be example for this annotation. You can do some object initializations in the method that is annotated with @BeforeEach (in Junit 4 @Before ) , as you can see in my example code.

In addition , you can think same logic for @AfterEach and @AfterAll. This time , these method runs after the test execution :)

Conclusion

I explained the main differences about some unit test metrics that can cause some troubleshoots when we don’t know what exactly they mean ,as much as I can. I hope that will helpful for you.

Thank you for your reading :)

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response