Spring Boot : Unit Test
Mac
Posted on April 22, 2020
Example of how to write unit test in Spring Boot.
// UserController.java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{id}")
public User findUser(@PathVariable Long id) {
return userService.findById(id);
}
}
// UserService.java
@Service
public class UserService {
@Autowired
private UserRepo userRepo;
public User findById(Long id) {
return userRepo.findById(id);
}
}
// UserRepo.java
@Service
public class UserRepo {
public User findById(Long id) {
return User.builder()
.id(id)
.name("Mac")
.build();
}
}
// User.java
@Data
@Builder
public class User {
private Long id;
private String name;
}
- Test Service class
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@InjectMocks
private UserService userService;
@Mock
private UserRepo userRepo;
@Test
public void testFindById() {
Mockito.when(userRepo.findById(Mockito.anyLong())).thenReturn(User.builder()
.id(1L)
.name("Mac")
.build());
User user = userService.findById(1L);
Assert.assertEquals(1L, user.getId().longValue());
Assert.assertEquals("Mac", user.getName());
Mockito.verify(userRepo, Mockito.times(1)).findById(Mockito.any());
}
}
- Test Controller class
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Autowired
private ObjectMapper objectMapper;
@Test
public void testFindUser() throws Exception {
User user = User.builder()
.id(1L)
.name("Mac")
.build();
Mockito.when(userService.findById(Mockito.any())).thenReturn(user);
mockMvc.perform(MockMvcRequestBuilders.get("/users/1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content()
.json(objectMapper.writeValueAsString(user)));
}
}
Note
-
@RunWith(SpringRunner.class)
is require if you use JUnit 4. - By default,
@SpringBootTest
will not start server but you can configure it withwebEnvironment
attribute.
Reference : https://stackoverflow.com/questions/44200720/difference-between-mock-mockbean-and-mockito-mock
π πͺ π
π©
Mac
Posted on April 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.