如何模拟 System 类?

Din*_*lae 1 java aspectj aspect

我正在尝试更改 System.currentTimeMillis() 方法的行为以进行测试。我找到了下面的方法,但我不能在代码中使用 aspect 关键字。我真的不明白如何使用这种方法。有什么建议?

public aspect CurrentTimeInMillisMethodCallChanger {
    long around():
        call(public static native long java.lang.System.currentTimeMillis()) 
               && within(user.code.base.pckg.*) {
            return 0; // provide your own implementation returning a long
        }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅包含上述代码来源的相关答案

And*_*ner 7

别。System.currentTimeMillis()如果您需要使用特定时间进行测试,请不要在您的代码中使用,Clock而是使用:

这种抽象的主要目的是允许在需要时插入备用时钟。应用程序使用对象而不是静态方法来获取当前时间。这可以简化测试。