What is the difference between writing a unit test in the same class as the tested method or writing it in another class (of the same package or extern package)? What are the advantages or disadvantages of these test-locations?
If you have your tests in separate class(es), you can
The best practice is separate tests from the code they are validating. The reason is simple: you do not want to package tests with your application. Application should be clean. Tests should validate functionality from outside.
Tests often have additional dependencies (eg testing framework, mockup library etc).
Common practice is to put source code under src/main/java
and tests under src/tests/java
.
Advantages of writing in separated classes is that you can separate your tests from your code. For example with maven :
1. Build everything
2. Executes the classes including the **/*Test*.java pattern
I don't even know how you can unit test in the same class than your code...
Test methods are there to test your code. Putting them in the tested class clutters the API of the class, and makes the bytecode and dependencies of the class larger than necessary.
If I want to use your Calculator class, I don't need the testPlusWorks()
and testMinusWorks()
test methods. I just need plus()
and minus()
. And if testPlusWorks
depends on some class from the JUnit or Mockito library, I don't want these dependencies in the production environment: they're only useful when testing the class.
There is not "right" answer for this question.
Writing in the same class: Allows you to test private methods but mess up the code.
Writing in the same project: Allows you to test internal methods/logics but mess up the project and extends your compilation time.
Writing externally: Prevents you from testing project internal methods/classes but keeps the tests clean and external to your "production" coder.
I find it best to write unit tests in a different source folder altogether, but keep them in the same package as you can still access packaged(default) scoped methods and varialble.
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.