P
P
postya2020-03-01 22:44:33
Spring
postya, 2020-03-01 22:44:33

How to do unit tests in Spring Boot?

Wrote a REST application on Spring Boot.
Never did any tests. You should at least do unit tests.
How to make tests for controller and service layers?
Can you write an example with a couple of methods?


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();
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question