Junit设置方法测试状态变量最佳实践

发布于 2025-01-27 17:30:35 字数 1393 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

欲拥i 2025-02-03 17:30:35

这是我认为的最佳实践:

  1. 没有设置方法。如果您使用@before注释(JUNIT 4),则方法名称应在之前为。如果使用@BeForeEach注释(Junit 5),则方法名称shold be之前。
  2. 通过@Mock注释创建所有模拟对象。
  3. 如果使用Junit 4,请调用mockitoAntoNotations.openmocks(this)作为方法之前的中的第一个“事物”。
  4. 如果可以的话,不要使用Junit 4。而是使用junit 5。
  5. 如果使用junit 5,请用@extendwith(mockitoextension.class)注释类
  6. 命名为“ clasStototest”的事物。
  7. 如果不使用@InjectMocks,请在方法之前在中实例化classtotest对象。
  8. 在方法之前,在中执行手动模拟注入(例如,模拟未注射的记录器)。
  9. 使用doreturn(xxx)。(xxx).xxx()
  10. 避免(xxx.xxx())。
  11. 如果您的测试方法的100%将“使用”一种固定方法,请将其存根于之前的方法中。
  12. 对于所有其他固执,请在每个测试中进行固执。
  13. 如果许多(确定数字)测试需要相同的固执,请创建一种私人方法来执行固执并在需要此类固执的测试中调用它。

Here are my opinionated best practices:

  1. There is no setUp() method. If you use the @Before annotation (junit 4), the method name should be before. If you use the @BeforeEach annotation (junit 5), the method name shold be beforeEach.
  2. Create all mock objects via the @Mock annotation.
  3. If using Junit 4, call MockitoAnnotations.openMocks(this) as the first "thing" in the before method.
  4. Don't use Junit 4, if you can. Instead use Junit 5.
  5. If using Junit 5, annotate the class with @ExtendWith(MockitoExtension.class)
  6. Name the thing-that-is-being-tested "classToTest".
  7. If not using @InjectMocks, instantiate the classToTest object in the before method.
  8. Perform manual mock injection (for example, mock a non-injected logger) in the before method.
  9. Use doReturn(xxx).when(xxx).xxx().
  10. Avoid when(xxx.xxx()).thenReturn(xxx).
  11. If 100% of your test methods will "use" one stubbed method, stub it in the before method.
  12. For all other stubbing, perform stubbing in each test.
  13. If many (you determine the number) tests require the same stubbing, create a private method to perform the stubbing and call it in the tests where such stubbing is required.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文