For main and test dirs:
cp application.properties.dist application.properties
See controller: /src/main/java/hello/controller/single/EmployeeController.java
It should be noted that this controller uses the technique of inserting a successfully created or updated object as a link to the header
JPA Employee:
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
See controllers: /src/main/java/hello/controller/oneToMany
- Create enum for list of errors code:
ErrorCode - Create base exception
BaseExceptionfor customization response data - All exceptions which throw from
serviceorcontrollermust be extended fromBaseException- for correct handle - Create advice for exceptions:
ExceptionControllerAdvice
Example: /test/java/hello/mockMvc/controller/EmployeeControllerTest.java
The disadvantage of this approach is that if we have a global interceptor (EmployeeNotFoundAdvice), we need to manually specify it in MockMvcBuilders
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class EmployeeControllerTest {
private MockMvc mockMvc;
@Autowired
private EmployeeController employeeController;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(employeeController)
.setControllerAdvice(new ExceptionControllerAdvice()) // set advice Exception
.build();
}
}
or more modern way:
@RunWith(SpringRunner.class)
@WebMvcTest(AbstractApiController.class)
@Transactional
public class EmployeeControllerTest {
@Autowired
private MockMvc mockMvc;
}
Example: /test/java/hello/mockMvc/webApplication/EmployeeControllerWebApplicationTest.java
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
For those situations when you don’t need to use a real database (even in-memory), but perform service spoofing
Example: /src/test/java/hello/mockBean/controller/EmployeeControllerMockBeanTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class EmployeeControllerMockBeanTest {
@MockBean
private EmployeeService service;
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private static String employeeRouteWithParam = PATH + "/{id}";
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
...
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
It is important to remember that in this case you need to clean the database
yourself after each method, since the @Transaction does not work here (not rollback).
Example: /test/java/hello/restTemplate/EmployeeRestTemplateTest.java