简体   繁体   中英

How to start writing Unit Tests for SpringBoot(The proper way)?

I'm new to the world of unit testing in Spring and with some research I think I'll be using Junit5 with mockito and AssertJ library for the same. I am just starting out and it does look really confusing.

1st Question: Do we write our units first?? meaning our controller methods or service methods or any unit.. Do we write those firsts and then write tests for them or Do we first design our tests thinking ok, this methods needs to do this so I'll be writing my tests and then actually implement what I have to implement? I know this a bit silly of a question but I want to know how people go about it this in their work.

2nd Question: Suppose we write our tests, it fails for a certain unit. After it fails, what should be my first approach ie should I be thinking that the way I wrote the test was bad, so I need to properly write the test in order for the test to pass, or should I be like, ok my unit must have been bad, I'll change or refactor my code right away and then again test it after the refactoring? What is the 'thing' to do just after your test fails for some unit?

3rd Question/Help: Testing simple CRUD methods seems okayish and there are a lot of resources for it although it's still confusing.. Could someone recommend me a github repo or a link or any source where unit tests have been written for some complex functions with some actual logic inside it and not only CRUD operations? I want to see how tests are written for the logic inside the code and how things are actually tested.

Any help would be highly valued. Thank-you, Have a good day.

  1. You are asking if you should to "Test Driven Development" (TDD for short) , where writing test first is the basic idea. But since you did not write any tests yet, start small, write the test afterwards, and as soon you feel comfortable writing tests, write all test before implementing. And read more about "TDD", google is you friend.

  2. this depends if you trust the test code more than the production code or vice versa. Of cause, test code can also be buggy. But test code should actually be easier to understand, so it should be easier to decide who much you can trust it.

  3. See https://medium.com/@sheikarbaz5/spring-boot-with-tdd-test-driven-development-part-i-be1b90da51e or https://livebook.manning.com/book/spring-boot-in-action/chapter-4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM