[英]best location to write a unit-test (java)?
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)? 在与被测方法相同的类中编写单元测试,或在另一个类(相同的包或extern包)中编写单元测试,有什么区别? 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
. 常见的做法是将源代码放在
src/main/java
,将测试放在src/tests/java
。
Advantages of writing in separated classes is that you can separate your tests from your code. 在分离的类中编写的好处是可以将测试与代码分离。 For example with maven :
例如,使用maven:
1. Build everything 1.建立一切
2. Executes the classes including the **/*Test*.java pattern
2.执行包括
**/*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.
将它们放在经过测试的类中会使该类的API混乱,并使该类的字节码和依赖性更大。
If I want to use your Calculator class, I don't need the testPlusWorks()
and testMinusWorks()
test methods. 如果要使用您的Calculator类,则不需要
testPlusWorks()
和testMinusWorks()
测试方法。 I just need plus()
and minus()
. 我只需要
plus()
和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. 而且,如果
testPlusWorks
依赖于JUnit或Mockito库中的某个类,那么我不希望这些依赖在生产环境中起作用:它们仅在测试类时有用。
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. 我发现最好将单元测试完全写在不同的源文件夹中,但是将它们保留在同一程序包中,因为您仍然可以访问打包的(默认)范围内的方法和变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.