Java Unit Testing with JUnit 5
Write thorough tests with JUnit 5 parameterized tests, mocks, and integration testing.
JavaJUnit 5MockitoTesting
Overview
Write thorough tests with JUnit 5 parameterized tests, mocks, and integration testing.
Project Structure
text
src/
├── main/
│ ├── java/com/example/
│ │ ├── controller/
│ │ ├── service/
│ │ ├── repository/
│ │ ├── model/
│ │ └── config/
│ └── resources/
│ └── application.yml
└── test/Dependencies
xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>Model
java
@Entity
@Table(name = "resources")
public class Resource {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Name is required")
@Size(max = 255)
private String name;
@Column(columnDefinition = "TEXT")
private String description;
@Enumerated(EnumType.STRING)
private Status status = Status.ACTIVE;
@CreationTimestamp
private LocalDateTime createdAt;
// Getters, setters, constructors
}Service Layer
java
@Service
@Transactional
public class ResourceService {
private final ResourceRepository repository;
public ResourceService(ResourceRepository repository) {
this.repository = repository;
}
public List<Resource> findAll() {
return repository.findAll(Sort.by(Sort.Direction.DESC, "createdAt"));
}
public Resource findById(Long id) {
return repository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Resource not found: " + id));
}
public Resource create(ResourceRequest request) {
Resource resource = new Resource();
resource.setName(request.getName());
resource.setDescription(request.getDescription());
return repository.save(resource);
}
}REST Controller
java
@RestController
@RequestMapping("/api/resources")
public class ResourceController {
private final ResourceService service;
@GetMapping
public ResponseEntity<List<Resource>> getAll() {
return ResponseEntity.ok(service.findAll());
}
@PostMapping
public ResponseEntity<Resource> create(@Valid @RequestBody ResourceRequest request) {
Resource created = service.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(ex.getMessage()));
}
}Key Takeaways
- Follows layered architecture pattern for clean separation of concerns
- Uses Spring validation annotations for input checking
- Exception handling with \@ExceptionHandler\ for consistent error responses
- Java, JUnit 5, Mockito, Testing integration demonstrated
Related Projects
JavaJun 9, 2024
Java Batch Processing with Spring
Process large datasets with Spring Batch job scheduling, chunking, and retry logic.
JavaSpring BatchETLProcessing
Read more → Source
JavaJun 5, 2024
Java Socket Programming
Build networked applications with TCP/UDP sockets, serialization, and protocol design.
JavaSocketsNetworkingTCP
Read more → Source
JavaJun 1, 2024
Java Caching with Redis
Implement distributed caching using Spring Data Redis with TTL, eviction, and pub/sub.
JavaRedisCachingSpring
Read more → Source
Comments (0)
No comments yet. Be the first to comment!