【发布时间】:2012-03-12 15:22:59
【问题描述】:
我对这个很迷茫。我有一些基于 Spring 使用 JUnit4 运行的验收测试。现在我还想添加单元测试。为了让它们更快,我跳过上下文并使用 PowerMock 注入 Mocks。 然而,所有突然的反思不再起作用了。
public class TestSomething {
@Test
public void nothingWrongWithThis() {
Class<?> type = Client.class;
type.getDeclaredMethods();
}
}
第二行将返回 null,就像对类型的任何其他方法调用一样,除了 getName()
如果我使用上下文,它会起作用:
@TransactionConfiguration
@ContextConfiguration({ "classpath:dw-product-context-test.xml" })
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
public class TestSomething {
@Test
public void nothingWrongWithThis() {
Class<?> type = Client.class;
type.getDeclaredMethods();
}
}
这里有什么问题?没有任何跑步者或上下文,反射不应该工作吗?
甚至没有添加行
private Client client = new Client();
会改变任何东西(可能需要初始化类以便能够反映它的运行时)
哦,添加
@RunWith(PowerMockRunner.class)
也不会改变任何东西。
有什么想法吗?
谢谢!
PS:从现在开始将出城一天,所以我会在大约 35 小时内阅读任何答案。
编辑
刚刚弄清楚发生了什么:
我从调试器开始,打开Client.class.declaredMethods,它是null。当我运行getDeclaredMethods() 时,它会得到它们。所以看起来好像一切都是空的,这让我很困惑,但调试器只是没有在所有字段上运行get...(),而最初是null
如果我使用 spring 上下文,它将加载所有 bean(Client 是 @Entity)并用软引用填充所有反射字段,就像我在所有这些上调用 get..() 一样。
【问题讨论】:
-
您是否使用任何加载时间编织?您确定两个测试都使用相同的
Client类(相同的包)吗? -
type.getDeclaredMethods();如何返回null,或者你的意思是,它返回的是一个空数组? -
感谢您的 cmets。想通了,检查我的编辑。
标签: java spring reflection null powermock