Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

java - How to write Junit test case for spring boot:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One of the issues I see here is that your controller is doing all the work - getting a query, setting it up, executing it, and returning the results from the API call. Doing all these things in one place makes it hard to test. That also raises a question - what exactly are you trying to test? And what issues are you running into?

You might want to look at refactoring it to use a layered architecture instead. API -> Service Layer -> Repository layer.

This might be a cleaner structure, and you can then test layers independently:

  1. Check that the API calls the correct service layer method with the correct parameters.
  2. Check that the service layer calls the repository with the correct arguments.
  3. Check that the repository creates the correct query.

Alternatively, you could also do integration testing - just invoke the API and make sure that the correct result is returned.

Also, be wary of using String replacement in your queries. Rather have a look at PreparedStatement (https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...