使用 Mockito 在其中调用 new() 测试类

Test class with a new() call in it with Mockito(使用 Mockito 在其中调用 new() 测试类)
本文介绍了使用 Mockito 在其中调用 new() 测试类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个包含 new() 调用以实例化 LoginContext 对象的旧类:

I have a legacy class that contains a new() call to instantiate a LoginContext object:

public class TestedClass {
  public LoginContext login(String user, String password) {
    LoginContext lc = new LoginContext("login", callbackHandler);
  }
}

我想使用 Mockito 来模拟 LoginContext 来测试这个类,因为它要求在实例化之前设置 JAAS 安全性内容,但我不确定如何在不更改 code>login() 方法来外部化 LoginContext.

I want to test this class using Mockito to mock the LoginContext as it requires that the JAAS security stuff be set up before instantiating, but I'm not sure how to do that without changing the login() method to externalize the LoginContext.

是否可以使用 Mockito 来模拟 LoginContext 类?

Is it possible using Mockito to mock the LoginContext class?

推荐答案

对于未来我会推荐 Eran Harel 的回答(重构将 new 移动到可以模拟的工厂).但是,如果您不想更改原始源代码,请使用非常方便且独特的功能:sies.来自文档:

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

您可以创建真实对象的间谍.当您使用 spy 时,会调用 real 方法(除非方法被存根).

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

应该小心偶尔使用真正的间谍,例如在处理遗留代码时.

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

在你的情况下,你应该写:

In your case you should write:

TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);

这篇关于使用 Mockito 在其中调用 new() 测试类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)