Category Archives: TDD

Post navigation

Testing for exceptions in JUnit is something we have to deal with! We want to test if an exception occurs in a particular situation, or even if the exception contains a particular message. The question is: How to test for an exception in Junit? Continue reading →

Mockito is a mock framework which you can use to write simple and clean tests. One of it’s nice features is the ArgumentMatcher. With the ArgumentMatcher you can determine the outcome of your mocked service or repository based on any condition you want.

Imagine we have a CandyService which can get a list of candies which are liked by a specific customer. This service uses the external ChocalateService which specifically checks if the customer likes chocolate. Continue reading →

While writing unit tests, you often have to mock dependencies like services or controllers. Often a constructor is used to autowire the dependencies as shown in the example below. In the Test class I instantiated the ContactService using a contactRepository Mock object

In the previous example you always have to Autowire the constructor and bind the dependencies to the class variables. In the next example the code is cleaner by autowiring the mocking objects, so you don’t have to create a custom constructor or setters to set the dependencies, which makes your code more concise and easier to read.

1

2

3

4

5

6

7

8

9

10

@Service

publicclassContactServiceImplimplementsContactService{

@Autowired

privatefinalContactRepository contactRepository;

publicvoidsaveContact(finalContact contact){

contactRepository.save(contact);

}

}

The test class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@RunWith(MockitoJUnitRunner.class)//will initiate and inject the mocks

publicclassContactServiceTest{

@Mock

privateContactRepository contactRepository;//Note the variable name must be exactly the same as used in ContactService

@InjectMocks

privatefinalContactService contactService=newContactServiceImpl();

@Test

publicvoidtestSaveContact(){

Contact contact=newContact();

contactService.saveContact(contact);

//validate contactRepository.save is called

verify(contactRepository).save(contact);

}

}

Take a note of the “RunWith(MockitoJUnitRunner.class)” annotation. This annotation will initialize the annotated mock objects. An alternative is to use “MockitoAnnotations.initMocks(this)” in a setup method to initalize the annotated mock objects.