Написал REST приложение на Spring Boot.
Тесты ни разу не делал. Нужно хотя бы сделать юнит тесты.
Как сделать тесты для controller и service слоев?
Можете пример написать с парой методов?
Model:
@Entity
@Table(name = "test")
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private String beginDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private String endDate;
@Pattern(regexp = "yes|no", message = "activity should be yes or no")
private String activity;
}
Repository:
@Repository
public interface TestRepository extends JpaRepository<Test, Integer> {
List<Test> findAllByOrderByNameAsc();
}
Service:
@Service
public class TestService {
@Autowired
private final TestRepository testRepository;
public TestService(TestRepository testRepository) {
this.testRepository = testRepository;
}
public List<Test> getAllTests() {
return testRepository.findAllByOrderByNameAsc();
}
public Test saveTest(Test test) {
return testRepository.save(test);
}
}
Controller Interface:
public interface TestController {
//create test
@PostMapping("test")
public Test createTest(@RequestBody Test test);
//get all tests
@GetMapping("test/all")
public List<Test> getAllTests();
}
Controller Implementation:
@RestController
@RequestMapping("/api/v1/")
public class TestControllerImpl implements TestController {
@Autowired
private final TestService testService;
public TestControllerImpl(TestService testService) {
this.testService = testService;
}
//create test
@Override
public Test createTest(@RequestBody Test test) {
return testService.saveTest(test);
}
//get all tests
@Override
public List<Test> getAllTests() {
return testService.getAllTests();
}
}