Unit testing – an example

Let's look at an example and build a unit test for a controller class of an ACCOUNT-SERVICE. We will take a simplified version of the AccountController class with a single method, as demonstrated here:

@RestController
public class AccountController {
@Autowired
AccountRepository accountRepository;
public AccountController(AccountRepository accountRepository) {
super();
this.accountRepository = accountRepository;
}
...
@GetMapping(value = "/account/{accountId}")
public Account findByAccountId (@PathVariable Integer accountId){
return accountRepository.findAccountByAccountId(accountId);
}
...
}

The preceding class has many methods, but in this chapter I will unit-test the findByAccountId(accountId) method, which could look like this:

package com.dineshonjava.bookshop.accountservice;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import com.dineshonjava.bookshop.accountservice.controller.AccountController;
import com.dineshonjava.bookshop.accountservice.domain.Account;
import com.dineshonjava.bookshop.accountservice.repository.AccountRepository;
public class AccountControllerTest {
AccountController accountController;
@Mock
AccountRepository accountRepository;
@Before
public void setUp() throws Exception {
initMocks(this);
accountController = new AccountController(accountRepository);
}
@Test
public void findByAccountId (){
Account account = new Account();
given(accountRepository.findAccountByAccountId(1000)).willReturn(account);
Account acct = accountController.findByAccountId(1002);
assertThat(acct.getName(), is("Arnav Rajput"));
}
}

In the preceding test, the class has a test method that uses junit. We have used Mockito to replace the real AccountRepository class with a stub object. A stub object is a fake object—stubbing makes our unit testing simple. In the preceding test class, we have one test method for the findByAccountId() method. This test method tests the findByAccountId() method of the AccountController class.

In this application, we use the Spring Boot test library by adding the following Maven dependency:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

The preceding Maven dependency adds a Spring testing module to your application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.199.250