使用Mockito在其中调用new()调用的测试类 [英] Test class with a new() call in it with Mockito

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

问题描述

我有一个遗留类,它包含一个new()调用来实例化LoginContext():

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

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

我想用Mockito测试这个类来模拟LoginContext因为它要求在实例化之前设置JAAS安全性东西,但是我不知道如何在不更改login()方法来外化LoginContext的情况下如何做到这一点。是否可以使用Mockito来模拟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. Is it possible using Mockito to mock the LoginContext class?

推荐答案

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

For the future I would recommend Eran Harel 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:


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

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()调用的测试类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆