JUnit 中的 PowerMock

PowerMock in JUnit

能否请您帮我定义该代码的 PowerMock:

    String role = "ROLE_WARP_PUBLISH_PRIVATE";

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

    for (GrantedAuthority auth : authorities)
    {
        if(auth.getAuthority().equals(role))
        {
            if (publishCheckbox == true)
            {
                getScenarioService().makePublic(scenarioVersionId);
            }
        }

    }

所以我知道我必须如何模拟 getContext() 但是当调用此方法时我不能 return 某些东西所以我完全不知道如何模拟那几行。

感谢您的帮助

我的建议:忘记 使用 PowerMock。

如果您必须模拟静态方法,请围绕它构建您自己的小包装器 class。然后,为了测试,您的包装器可以 return 某些东西 控制;并用于生产用途;你的包装器只是调用静态方法。

PowerMock 看起来像是许多问题的解决方案;但迟早会导致 更多 问题。

说真的:如果您的设计只能使用 PowerMock 进行测试,这通常表明您的设计 糟糕 。所以:专注于重新编写被测代码;而不是将时间花在像 PowerMock 这样弊大于利的工具上。

我花了无数时间试图解决 PowerMock 问题;自从开始编写 "better to test" 生产代码...我已经编写了数百或数千个测试,而不再需要 PowerMock。