Я строю весенний ботинок для управления организациями клиентов и тестирую ее с помощью JUNIT. Тем не менее, я получаю предупреждение о форматировании при публикации моего кода в переполнении стека.// CustomerController.java
package az.ac.cput.controller;
import az.ac.cput.domain.Customer;
import az.ac.cput.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerController {
private CustomerService service;
@Autowired
public CustomerController(CustomerService service) {
this.service = service;
}
@PostMapping("/create")
public Customer create(@RequestBody Customer customer) {
return service.create(customer);
}
@GetMapping("/read/{id}")
public Customer read(@PathVariable String id) {
return service.read(id);
}
@PutMapping("/update")
public Customer update(@RequestBody Customer customer) {
return service.update(customer);
}
@DeleteMapping("/delete/{id}")
public boolean delete(@PathVariable String id) {
return service.delete(id);
}
@GetMapping("/getAll")
public List getAll() {
return service.getall();
}
}
< /code>
Это для теста < /p>
// CustomerControllerTest.java
package az.ac.cput.controller;
import az.ac.cput.domain.Customer;
import az.ac.cput.factory.CustomerFactory;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CustomerControllerTest {
private static Customer customer;
@Autowired
private TestRestTemplate restTemplate;
public static String BASE_URL = "http://localhost:8080/myWebsite/customer";
@BeforeAll
public static void setUp() {
customer = CustomerFactory.createCustomer1("Engetelo", "Mathebane",
"0781234567", "Enge2@gmail.com", "10",
"Dorset street", "Woodstock", "Cape Town",
"Western Cape", "South Africa", 8001);
}
@Test
@Order(1)
void create() {
String url = BASE_URL + "/create";
ResponseEntity postResponse = this.restTemplate.postForEntity(url, customer, Customer.class);
assertNotNull(postResponse);
Customer created = postResponse.getBody();
assertEquals(customer.getCustomerId(), created.getCustomerId());
System.out.println("Created: " + created);
}
@Test
@Order(2)
void read() {
String url = BASE_URL + "/read/" + customer.getCustomerId();
ResponseEntity response = this.restTemplate.getForEntity(url, Customer.class);
assertEquals(customer.getCustomerId(), response.getBody().getCustomerId());
System.out.println("Read: " + response.getBody());
}
@Test
@Order(3)
void update() {
Customer updatedCustomer = new Customer.Builder().copy(customer).setFirstName("Siyaaa").build();
String url = BASE_URL + "/update";
this.restTemplate.put(url, updatedCustomer);
ResponseEntity response = restTemplate.getForEntity(BASE_URL + "/read/" + updatedCustomer.getCustomerId(), Customer.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
assertNotNull(response.getBody());
assertEquals(updatedCustomer.getFirstName(), response.getBody().getFirstName());
System.out.println("Updated: " + response.getBody());
}
@Test
@Order(4)
void delete() {
String url = BASE_URL + "/delete/" + customer.getCustomerId();
this.restTemplate.delete(url);
ResponseEntity response = this.restTemplate.getForEntity(BASE_URL + "/delete" + customer.getCustomerId(), Customer.class);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
System.out.println("Deleted: " + response.getBody());
}
@Test
@Order(5)
void getAll() {
String url = BASE_URL + "/getAll";
ResponseEntity response = this.restTemplate.getForEntity(url, Customer[].class);
assertNotNull(response.getBody());
System.out.println("Get All: ");
for (Customer customer : response.getBody()) {
System.out.println(customer);
}
}
}
< /code>
Это для фабрики < /p>
// CustomerFactory.java
package az.ac.cput.factory;
import az.ac.cput.domain.Customer;
import az.ac.cput.domain.HomeAddress;
import az.ac.cput.util.Helper;
import java.util.Random;
public class CustomerFactory {
public static Customer createCustomer1(String firstName, String lastName, String mobile, String email,
String streetNumber, String streetName,
String suburb, String city, String province, String country,
int postalCode) {
String customerId = Helper.generateId();
Long addressId = new Random().nextLong();
HomeAddress homeAddress = new HomeAddress.Builder()
.setAddressId(addressId)
.setStreetNumber(streetNumber)
.setStreetName(streetName)
.setSuburb(suburb)
.setCity(city)
.setProvince(province)
.setCountry(country)
.setPostalCode(postalCode)
.build();
return new Customer.Builder()
.setCustomerId(customerId)
.setFirstName(firstName)
.setLastName(lastName)
.setMobile(mobile)
.setEmail(email)
.setHomeAddress(homeAddress)
.build();
}
public static Customer createCustomer(String firstName, String lastName, String mobile, String email, HomeAddress homeAddress) {
String customerId = Helper.generateId();
Long addressId = new Random().nextLong();
if (Helper.isNullOrEmpty(firstName) || Helper.isNullOrEmpty(lastName)
|| Helper.isNullOrEmpty(mobile) || Helper.isNullOrEmpty(email))
return null;
return new Customer.Builder()
.setCustomerId(customerId)
.setFirstName(firstName)
.setLastName(lastName)
.setMobile(mobile)
.setEmail(email)
.setHomeAddress(homeAddress)
.build();
}
}
< /code>
// CustomerFactoryTest.java
package az.ac.cput.factory;
import az.ac.cput.domain.Customer;
import az.ac.cput.domain.HomeAddress;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CustomerFactoryTest {
public static Customer customer1 = CustomerFactory.createCustomer("Engetelo", "SIa", "0604182462", "engetelo@gmail.com", new HomeAddress());
public static Customer customer2 = CustomerFactory.createCustomer("", "Nathasha", "0738400964", "nathasha.com", new HomeAddress());
@Test
void testCreateCustomer() {
assertNotNull(customer1);
System.out.println(customer1.toString());
}
@Test
void testCreateCustomerThatFails() {
assertNull(customer2);
System.out.println("Failed because of null name");
}
@Test
void testNotImplementedYet() {
fail("Not yet implemented");
}
}
< /code>
Customer Service
// CustomerService.java
package az.ac.cput.service;
import az.ac.cput.domain.Customer;
import az.ac.cput.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CustomerService implements ICustomerService {
private CustomerRepository repository;
@Autowired
CustomerService(CustomerRepository repository) {
this.repository = repository;
}
@Override
public Customer create(Customer customer) {
return this.repository.save(customer);
}
@Override
public Customer read(String email) {
return this.repository.findByEmail(email).orElse(null);
}
@Override
public Customer update(Customer customer) {
return this.repository.save(customer);
}
@Override
public boolean delete(String id) {
this.repository.deleteById(id);
return true;
}
@Override
public List getall() {
return this.repository.findAll();
}
}
< /code>
this block is for the service test
// CustomerServiceTest.java
package az.ac.cput.service;
import az.ac.cput.domain.Customer;
import az.ac.cput.domain.HomeAddress;
import az.ac.cput.factory.CustomerFactory;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CustomerServiceTest {
@Autowired
private ICustomerService service;
private Customer customer = CustomerFactory.createCustomer("Engetelo",
"Engetelo",
"Sia", "enge@gmail.com", new HomeAddress());
@Test
@Order(1)
void create() {
Customer created = service.create(customer);
assertNotNull(created);
System.out.println("Created: " + created);
}
@Test
@Order(2)
void read() {
Customer read = service.read(customer.getCustomerId());
assertNotNull(read);
System.out.println(read);
}
@Test
@Order(3)
void update() {
Customer newCustomer = new Customer.Builder().copy(customer).setFirstName("Engetelo")
.setLastName("Sia").build();
Customer updated = service.update(newCustomer);
assertNotNull(updated);
System.out.println(updated);
}
@Test
@Order(4)
void getAll() {
System.out.println(service.getall());
}
}
< /code>
I'm building a Spring Boot RESTful service for managing Customer entities. The service exposes CRUD operations and follows typical REST principles. I'm using Spring Data JPA to handle database interactions, and I have a Customer entity with fields like id, name, and email.
To ensure quality and reliability, I am writing JUnit tests to cover the controller layer, service layer, and repository layer. My test setup uses @SpringBootTest and @AutoConfigureMockMvc annotations to initialize the context and test the endpoints with mock requests.
However, when I try to post my code on Stack Overflow, I receive formatting warnings that make it difficult to read the code and for others to help me efficiently. The warnings mention improper code block usage or missing triple backticks, which affects how the code is rendered.
Here is my current implementation and the test setup that I am working with. I would appreciate any suggestions on improving the code formatting for Stack Overflow, as well as feedback on my code itself if you see any issues or best practices I might be missing.
Подробнее здесь: https://stackoverflow.com/questions/796 ... lationship