In this example we'll write test for the Users package
package com.example.blog_app_springboot.users;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
@DataJpaTest
@ActiveProfiles("test")
public class UsersRepoTests {
@Autowired
private UserRepository userRepository;
@Test
@Order(1)
void can_create_user() {
var user = UserEntity.builder()
.username("adminoq")
.password("adminoq")
.email("[email protected]").build();
userRepository.save(user);
}
}
@Configuration
public class JpaTestConfig {
@Bean
@Profile("test")
public DataSource dataSource() {
var dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
return dataSource;
}
}
public class UsersServiceTests {
@Autowired
UserService userService;
@Test
void can_create_users() {
var user = userService.createUser(new CreateUserRequest(
"najat Oracle",
"15062024",
"[email protected]"
));
Assertions.assertNotNull(user);
Assertions.assertEquals("najat Oracle", user.getUsername());
}
}
package com.example.blog_app_springboot.common.dtos;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class ErrorResponse {
private String message;
private String details;
}
@ExceptionHandler({
UserService.UserNotFoundException.class
})
ResponseEntity<ErrorResponse> handleUSerNotFoundException(Exception ex){
String message;
HttpStatus status;
if(ex instanceof UserService.UserNotFoundException){
message = ex.getMessage();
status = HttpStatus.NOT_FOUND;
}else{
message = "Something went wrong";
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
ErrorResponse response = ErrorResponse.builder()
.message(message)
.build();
return ResponseEntity.status(status).body(response);
}
{
"message": "User with Username: saidox not found",
"details": null
}