- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在尝试为包验证方法编写 JUnit4 测试。
该方法只是检查调用是否来自正确的包,以确保它不是从外部调用的。方法和RegEx本身可以工作,但是为了安全起见,我想添加一个单元测试。
简单来说,这是包测试:
package foo.bar.lib.util.unsafe;
import java.util.regex.Pattern;
public abstract class UnsafeUtil {
private static final Pattern UNSAFE_PACKAGE_PATTERN =
Pattern.compile("^foo\\.bar\\.lib(?:\\..*)?(?<!unsafe)\\.\\w+$");
protected static void testInternalUse() {
final StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (int i = 2; i < stack.length; ++i) {
if (UNSAFE_PACKAGE_PATTERN.matcher(stack[i].getClassName()).find()) return;
}
throw new IllegalStateException("UnsafeUtil may not be used externally");
}
}
现在我的测试类如下所示:
package foo.bar.lib.util.unsafe;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Thread.class)
public class UnsafeUtilTest {
private static final String expectedError = "UnsafeUtil may not be used externally";
private static void setupStackTrace(String className) {
final Thread fakeThread = Mockito.mock(Thread.class);
final StackTraceElement[] fakeStack =
new StackTraceElement[] {null, null, new StackTraceElement(className, "", "", 0)};
PowerMockito.mockStatic(Thread.class);
Mockito.when(Thread.currentThread()).thenReturn(fakeThread);
Mockito.when(fakeThread.getStackTrace()).thenReturn(fakeStack);
}
@Test
public void correctPackageTest() {
setupStackTrace("foo.bar.lib.Main");
try {
CommonUnsafeUtil.testInternalUse();
} catch (IllegalStateException e) {
if (expectedError.equals(e.getMessage()))
throw new AssertionError("An IllegalStateException should not have been thrown:", e);
}
}
@Test
public void incorrectPackageTest() {
setupStackTrace(String.class.getName());
try {
CommonUnsafeUtil.testInternalUse();
} catch (IllegalStateException e) {
assertEquals(expectedError, e.getMessage());
}
}
}
in CorrectPackageTest
成功,但是 CorrectPackageTest
失败并出现以下错误:
java.lang.AssertionError: An IllegalStateException should not have been thrown:
at foo.bar.lib.util.unsafe.UnsafeUtilTest.correctPackageTest(UnsafeUtilTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:116)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:59)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:39)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: UnsafeUtil may not be used externally
at foo.bar.lib.util.unsafe.UnsafeUtil.testInternalUse(UnsafeUtil.java:17)
at foo.bar.lib.util.unsafe.UnsafeUtilTest.correctPackageTest(UnsafeUtilTest.java:33)
... 56 more
经过进一步检查,我发现 Thread.currentThread().getStackTrace()
调用返回两个调用的真实堆栈跟踪,而不是我创建的模拟堆栈跟踪。
我做错了什么?
最佳答案
PowerMock 将要求您为该模拟准备被测试的类。除非您完全理解将要发生的字节码操作,否则有时可能会很偶然,具体取决于您想要做什么。
来自PrepareForTest
的文档
This includes final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation.
在这种情况下,需要准备UnsafeUtil
。
关于java - Mockito + PowerMock - 模拟 Thread.currentThread().getStackTrace(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783615/
有点不正统的情况 - 基本上我有线程 A 监视线程 B。如果线程 A 检测到线程 B 负责的周期性任务之一(线程 B 不是 ThreadPoolExecutor 的一部分,它是MINA 的线程之一)已
在一个日志系统中,每条日志的输出都是由一个辅助类用这样的方法完成的 public void debug(String message) { Logger logger = Logger.get
使用 Delphi 7,如何从 Exception 中获取表示堆栈跟踪的字符串? try SomethingDodgy(); except on E:Exception do begin
我无法理解这段代码。我很了解语法,但为什么使用 getStackTrace() 和 setStackTrace() ?我的意思是我想知道它在现实世界场景中的实现是什么?即,这段代码的期望输出是什么?
出于日志记录的目的,我创建了一个方法 logTitle(),它打印出 TestNG 测试的调用方法名称。示例代码如下。 @Test public void test1() throws Excepti
本文整理了Java中org.jboss.wsf.spi.WSFException.getStackTrace()方法的一些代码示例,展示了WSFException.getStackTrace()的具体
我目前正在尝试为包验证方法编写 JUnit4 测试。 该方法只是检查调用是否来自正确的包,以确保它不是从外部调用的。方法和RegEx本身可以工作,但是为了安全起见,我想添加一个单元测试。 简单来说,这
这是对 What happens when there's insufficient memory to throw an OutOfMemoryError? 的后续问题 我的问题如下:如果预先分配了
我正在使用 new Throwable().getStackTrace()[1].getMethodName() 一些开发人员认为它价格昂贵。这种方法的成本在哪里?我们应该使用它吗?如果是,那么应该注
我正在使用较旧的 Java 版本进行开发,该版本没有 getStackTrace() 方法。有一个 printStackTrace 方法,但它没有打印在我想要的地方。 有没有办法提取Exception
我是一名优秀的程序员,十分优秀!