有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java监视实例变量并在实例函数get调用时返回值

我试图模拟类实例,然后在调用实例函数时返回模拟对象,但结果是,它实际调用了函数

这是我的代码:

AuthenticationSessionModel authSessionCookie =
    new AuthenticationSessionManager(session)
       .getCurrentAuthenticationSession(realm, client, tabId);

我的测试代码是:

AuthenticationSessionManager spyAuthSessionManager =
    Mockito.spy(new AuthenticationSessionManager(session));
        
doReturn(authenticationSessionModel)
    .when(spyAuthSessionManager)
    .getCurrentAuthenticationSession(any(), any(), anyString());

它实际调用getCurrentAuthenticationSession(),并返回Null指针异常


共 (1) 个答案

  1. # 1 楼答案

    在测试中,你创建了一个间谍,并截获了一些行为。 但是你不能在测试代码中使用间谍

    相反,在测试代码中创建一个新的AuthenticationSessionManager

    您需要重新构造代码,并:

    • 在测试对象外部创建AuthenticationSessionManager
    • 将其传递给被测对象。构造函数是首先想到的

    有了这些变化,在测试中用间谍代替真实的AuthenticationSessionManager就变得微不足道了