Добавил API счетов с ответами 201, 404 и 400 и тестами контроллера

This commit is contained in:
Kashey committed 2026-10-21 23:00:28 +03:00
1 parent cd404fae0b
commit 6dec1fe840
13 files changed
+196 -6

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ public class Account {
public void setName(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Не указано имя счёта");
throw new InvalidAccountNameException("Не указано имя счёта");
}
this.name = name;
}
+22
View File
@@ -0,0 +1,22 @@
package model;
import java.util.HashMap;
import java.util.Map;
public class AccountJournal {
private final Map<Long, Account> accounts = new HashMap<>();
public void saveAccount(Account account) {
if (account == null) {
throw new IllegalArgumentException("Не указан счёт для сохранения в журнал");
}
accounts.put(account.getId(), account);
}
public Account getAccountById(Long id) {
if (id == null) {
throw new IllegalArgumentException("Не указан ID счёта");
}
return accounts.get(id);
}
}
@@ -0,0 +1,8 @@
package model;
public class InvalidAccountNameException extends RuntimeException {
public InvalidAccountNameException(String message)
{
super(message);
}
}
@@ -16,6 +16,9 @@ public class OperationJournal {
}
public Operation getOperationById(Long id) {
if (id == null) {
throw new IllegalArgumentException("Не указан ID операции");
}
return operations.get(id);
}
@@ -0,0 +1,34 @@
package net.sytes.kashey.easymoney.api;
import model.Account;
import org.jspecify.annotations.NonNull;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import service.AccountService;
import java.net.URI;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService service;
public AccountController(AccountService service) {
this.service = service;
}
@GetMapping("/{id}")
public AccountResponse getById(@PathVariable("id") Long id) {
Account account = service.getById(id);
return new AccountResponse(account.getId(), account.getName());
}
@PostMapping
public ResponseEntity<@NonNull AccountResponse> saveAccount(@RequestBody CreateAccountRequest request) {
Account account = service.create(request.name());
AccountResponse response = new AccountResponse(account.getId(), account.getName());
URI location = URI.create("/api/accounts/" + account.getId());
return ResponseEntity.created(location).body(response);
}
}
@@ -0,0 +1,4 @@
package net.sytes.kashey.easymoney.api;
public record AccountResponse(Long id, String name) {
}
@@ -1,10 +1,12 @@
package net.sytes.kashey.easymoney.api;
import model.InvalidAccountNameException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import service.AccountNotFoundException;
import service.OperationNotFoundException;
@RestControllerAdvice
@@ -14,4 +16,14 @@ public class ApiExceptionHandler {
public ProblemDetail handleOperationNotFound(OperationNotFoundException exception) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, exception.getMessage());
}
@ExceptionHandler(AccountNotFoundException.class)
public ProblemDetail handleAccountNotFound(AccountNotFoundException exception) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, exception.getMessage());
}
@ExceptionHandler(InvalidAccountNameException.class)
public ProblemDetail handleInvalidAccountName(InvalidAccountNameException exception) {
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, exception.getMessage());
}
}
@@ -0,0 +1,4 @@
package net.sytes.kashey.easymoney.api;
public record CreateAccountRequest(String name) {
}
@@ -1,6 +1,8 @@
package net.sytes.kashey.easymoney.config;
import model.AccountJournal;
import model.OperationJournal;
import service.AccountService;
import service.Ledger;
import service.OperationService;
@@ -27,4 +29,14 @@ public class AccountingConfig {
) {
return new OperationService(journal, ledger);
}
@Bean
public AccountJournal accountJournal() {
return new AccountJournal();
}
@Bean
public AccountService accountService(AccountJournal accountJournal) {
return new AccountService(accountJournal);
}
}
@@ -0,0 +1,8 @@
package service;
public class AccountNotFoundException extends RuntimeException {
public AccountNotFoundException(Long accountId) {
super("Счет не найден: " + accountId);
}
}
+28
View File
@@ -0,0 +1,28 @@
package service;
import model.Account;
import model.AccountJournal;
public class AccountService {
private Long counterId = 0L;
private final AccountJournal accountJournal;
public AccountService(AccountJournal accountJournal) {
this.accountJournal = accountJournal;
}
public Account create(String name) {
Account newAccount = new Account(counterId++, name);
accountJournal.saveAccount(newAccount);
return newAccount;
}
public Account getById(Long id) {
Account account = accountJournal.getAccountById(id);
if (account == null) {
throw new AccountNotFoundException(id);
}
return account;
}
}
@@ -49,11 +49,6 @@ public class OperationService {
}
private Operation requiredOperation(Long operationId) {
if (operationId == null) {
throw new IllegalArgumentException("Не указан ID операции");
}
Operation operation = journal.getOperationById(operationId);
if (operation == null) {
@@ -0,0 +1,60 @@
package net.sytes.kashey.easymoney.api;
import net.sytes.kashey.easymoney.config.AccountingConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AccountController.class)
@Import(AccountingConfig.class)
class AccountControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void creatingAccountReturnsCreatedAccountAndLocation() throws Exception {
// When / Then
mockMvc.perform(post("/api/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"name":"Карта"
}
"""))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"))
.andExpect(jsonPath("$.id").isNumber())
.andExpect(jsonPath("$.name").value("Карта"));
}
@Test
void gettingUnknownAccountReturnsNotFound() throws Exception {
// When / Then
mockMvc.perform(get("/api/accounts/999"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status").value(404))
.andExpect(jsonPath("$.detail").value("Счет не найден: 999"));
}
@Test
void creatingAccountWithInvalidNameReturnsBadRequestAnswer() throws Exception {
mockMvc.perform(post("/api/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"name":""
}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.status").value(400))
.andExpect(jsonPath("$.detail").value("Не указано имя счёта"));
}
}