Skip to content

Commit b7d6487

Browse files
yasin3061maibin
authored andcommitted
BAEL-88 Testing in Spring Boot (eugenp#1653)
* yasin.bhojawala@gmail.com Evaluation article on Different Types of Bean Injection in Spring * Revert "yasin.bhojawala@gmail.com" This reverts commit 963cc51. * Fixing compilation error and removing unused import * Introduction to Java9 StackWalking API - yasin.bhojawala@gmail.com Code examples for the article "Introduction to Java9 StackWalking API" * BAEL-608 Introduction to Java9 StackWalking API * BAEL-608 Introduction to Java9 StackWalking API changing the test names to BDD style * BAEL-608 Introduction to Java9 StackWalking API correcting the typo * BAEL-608 Introduction to Java9 StackWalking API improving method names * BAEL-608 Introduction to Java9 StackWalking API test method names improvements * BAEL-718 Quick intro to javatuples * merging pom from master * BAEL-722 Intro to JSONassert * BAEL-722 Intro to JSONassert Updated to 1.5.0 * BAEL-745 Quick Math.pow example * BAEL-729 Adding custom info to actuator's /info endpoint * BAEL-88 Testing in Spring Boot * BAEL-88 Testing in Spring Boot
1 parent 5e0d1e8 commit b7d6487

11 files changed

Lines changed: 553 additions & 0 deletions
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import javax.persistence.Entity;
4+
import javax.persistence.GeneratedValue;
5+
import javax.persistence.GenerationType;
6+
import javax.persistence.Id;
7+
import javax.persistence.Table;
8+
import javax.validation.constraints.Size;
9+
10+
@Entity
11+
@Table(name = "person")
12+
public class Employee {
13+
14+
public Employee() {
15+
}
16+
17+
public Employee(String name) {
18+
this.name = name;
19+
}
20+
21+
@Id
22+
@GeneratedValue(strategy = GenerationType.AUTO)
23+
private Long id;
24+
25+
@Size(min = 3, max = 20)
26+
private String name;
27+
28+
public Long getId() {
29+
return id;
30+
}
31+
32+
public void setId(Long id) {
33+
this.id = id;
34+
}
35+
36+
public String getName() {
37+
return name;
38+
}
39+
40+
public void setName(String name) {
41+
this.name = name;
42+
}
43+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
6+
import javax.transaction.Transactional;
7+
8+
import org.springframework.data.jpa.repository.JpaRepository;
9+
import org.springframework.stereotype.Repository;
10+
11+
@Repository
12+
@Transactional
13+
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
14+
15+
public Optional<Employee> findByName(String name);
16+
17+
public Optional<Employee> findById(Long id);
18+
19+
public List<Employee> findAll();
20+
21+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import java.util.List;
4+
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.http.HttpStatus;
7+
import org.springframework.http.ResponseEntity;
8+
import org.springframework.web.bind.annotation.RequestBody;
9+
import org.springframework.web.bind.annotation.RequestMapping;
10+
import org.springframework.web.bind.annotation.RequestMethod;
11+
import org.springframework.web.bind.annotation.RestController;
12+
13+
@RestController
14+
@RequestMapping("/api")
15+
public class EmployeeRestController {
16+
17+
@Autowired
18+
EmployeeService employeeService;
19+
20+
@RequestMapping(value = "/employees", method = RequestMethod.POST)
21+
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
22+
HttpStatus status = HttpStatus.CREATED;
23+
Employee saved = employeeService.save(employee);
24+
return new ResponseEntity<>(saved, status);
25+
}
26+
27+
@RequestMapping(value = "/employees", method = RequestMethod.GET)
28+
public List<Employee> getAllEmployees() {
29+
return employeeService.getAllEmployees();
30+
}
31+
32+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
6+
public interface EmployeeService {
7+
8+
public Optional<Employee> getEmployeeById(Long id);
9+
10+
public Optional<Employee> getEmployeeByName(String name);
11+
12+
public List<Employee> getAllEmployees();
13+
14+
public boolean exists(String email);
15+
16+
public Employee save(Employee employee);
17+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
6+
import javax.transaction.Transactional;
7+
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.stereotype.Service;
10+
11+
@Service
12+
@Transactional
13+
public class EmployeeServiceImpl implements EmployeeService {
14+
15+
@Autowired
16+
EmployeeRepository employeeRepository;
17+
18+
@Override
19+
public Optional<Employee> getEmployeeById(Long id) {
20+
return employeeRepository.findById(id);
21+
}
22+
23+
@Override
24+
public Optional<Employee> getEmployeeByName(String name) {
25+
return employeeRepository.findByName(name);
26+
}
27+
28+
@Override
29+
public boolean exists(String name) {
30+
if (employeeRepository.findByName(name) != null) {
31+
return true;
32+
}
33+
return false;
34+
}
35+
36+
@Override
37+
public Employee save(Employee employee) {
38+
return employeeRepository.save(employee);
39+
}
40+
41+
@Override
42+
public List<Employee> getAllEmployees() {
43+
return employeeRepository.findAll();
44+
}
45+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import java.util.List;
6+
import java.util.NoSuchElementException;
7+
import java.util.Optional;
8+
9+
import org.baeldung.boot.boottest.Employee;
10+
import org.baeldung.boot.boottest.EmployeeRepository;
11+
import org.junit.Test;
12+
import org.junit.runner.RunWith;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
15+
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
16+
import org.springframework.test.context.junit4.SpringRunner;
17+
18+
@RunWith(SpringRunner.class)
19+
@DataJpaTest
20+
public class EmployeeRepositoryTest {
21+
22+
@Autowired
23+
TestEntityManager entityManager;
24+
25+
@Autowired
26+
EmployeeRepository employeeRepository;
27+
28+
@Test
29+
public void whenFindByName_thenReturnEmployee() {
30+
Employee emp = new Employee("test");
31+
entityManager.persistAndFlush(emp);
32+
33+
Optional<Employee> fromDb = employeeRepository.findByName(emp.getName());
34+
assertThat(fromDb.get()
35+
.getName()).isEqualTo(emp.getName());
36+
}
37+
38+
@Test(expected = NoSuchElementException.class)
39+
public void whenInvalidName_thenNoSuchElementException() {
40+
Optional<Employee> fromDb = employeeRepository.findByName("doesNotExist");
41+
fromDb.get();
42+
}
43+
44+
@Test
45+
public void whenFindById_thenReturnEmployee() {
46+
Employee emp = new Employee("test");
47+
entityManager.persistAndFlush(emp);
48+
49+
Optional<Employee> fromDb = employeeRepository.findById(emp.getId());
50+
assertThat(fromDb.get()
51+
.getName()).isEqualTo(emp.getName());
52+
}
53+
54+
@Test(expected = NoSuchElementException.class)
55+
public void whenInvalidId_thenNoSuchElementException() {
56+
Optional<Employee> fromDb = employeeRepository.findById(-11L);
57+
fromDb.get();
58+
}
59+
60+
@Test
61+
public void givenSetOfEmployees_whenFindAll_thenReturnAllEmployees() {
62+
Employee alex = new Employee("alex");
63+
Employee ron = new Employee("ron");
64+
Employee bob = new Employee("bob");
65+
66+
entityManager.persist(alex);
67+
entityManager.persist(bob);
68+
entityManager.persist(ron);
69+
entityManager.flush();
70+
71+
List<Employee> allEmployees = employeeRepository.findAll();
72+
73+
assertThat(allEmployees).hasSize(3)
74+
.extracting(Employee::getName)
75+
.containsOnly(alex.getName(), ron.getName(), bob.getName());
76+
}
77+
78+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package org.baeldung.boot.boottest;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.hamcrest.CoreMatchers.is;
5+
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
6+
import static org.hamcrest.Matchers.hasSize;
7+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
8+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
9+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
10+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
11+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
12+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
13+
14+
import java.io.IOException;
15+
import java.util.List;
16+
17+
import org.baeldung.boot.DemoApplication;
18+
import org.junit.After;
19+
import org.junit.Test;
20+
import org.junit.runner.RunWith;
21+
import org.springframework.beans.factory.annotation.Autowired;
22+
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
23+
import org.springframework.boot.test.context.SpringBootTest;
24+
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
25+
import org.springframework.http.MediaType;
26+
import org.springframework.test.context.TestPropertySource;
27+
import org.springframework.test.context.junit4.SpringRunner;
28+
import org.springframework.test.web.servlet.MockMvc;
29+
30+
@RunWith(SpringRunner.class)
31+
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class)
32+
@AutoConfigureMockMvc
33+
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
34+
public class EmployeeRestControllerIntTest {
35+
36+
@Autowired
37+
MockMvc mvc;
38+
39+
@Autowired
40+
EmployeeRepository repository;
41+
42+
@After
43+
public void resetDb() {
44+
repository.deleteAll();
45+
}
46+
47+
@Test
48+
public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
49+
Employee bob = new Employee("bob");
50+
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
51+
.content(JsonUtil.toJson(bob)));
52+
53+
List<Employee> found = repository.findAll();
54+
assertThat(found).extracting(Employee::getName)
55+
.containsOnly("bob");
56+
}
57+
58+
@Test
59+
public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception {
60+
61+
createTestEmployee("bob");
62+
createTestEmployee("alex");
63+
64+
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
65+
.andDo(print())
66+
.andExpect(status().isOk())
67+
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
68+
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
69+
.andExpect(jsonPath("$[0].name", is("bob")))
70+
.andExpect(jsonPath("$[1].name", is("alex")));
71+
}
72+
73+
private void createTestEmployee(String name) {
74+
Employee emp = new Employee(name);
75+
repository.saveAndFlush(emp);
76+
}
77+
78+
}

0 commit comments

Comments
 (0)