英文:
Powermockito not mocking a static method
问题
我有这个测试类:
@ExtendWith(SpringExtension.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
public class ClassNameTest {
@InjectMocks
private ClassNameTest classNameTest;
@Mock
private DependencyClass dependencyClass;
/* 其他使用 @Mock 注解的依赖 */
@Test
public void testFunction() {
/* 使用 Mockito.when() 和相关方法对依赖进行模拟。 */
PowerMockito.spy(StaticClass.class);
Powermockito.when(StaticClass.function(Mockito.any())).thenReturn(/* 函数返回的对象 */);
/* 测试代码的其余部分。 */
}
}
我要测试的函数内部有一行代码,类似于:
ReturnObject ro = StaticClass.function(parameter);
显然,我希望阻止调用 StaticClass,并返回一个特制的对象。是的,我知道静态类不是最佳方法,但这超出了我目前问题的范围。
我的问题是,在调试测试代码时,实际上会在调用 Powermockito.when
时进入 StaticClass.function,并且会因为以某种方式以空值进入而失败。
我看过所有的教程和指南,它们都说我基本上需要做的就是这样,所以我完全迷失了。有任何想法吗?
英文:
I got this test class:
@ExtendWith(SpringExtension.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
public class ClassNameTest {
@InjectMocks
private ClassNameTest classNameTest;
@Mock
private DependencyClass dependencyClass;
/* Other dependencies annotated with @Mock */
@Test
public void testFunction() {
/* Mocking of the dependencies using Mockito.when() and friends. */
PowerMockito.spy(StaticClass.class);
Powermockito.when(StaticClass.function(Mockito.any()).thenReturn(/* The object function returns */);
/* Rest of the test code. */
}
}
The function I'm testing has somewhere inside a line that goes like this:
ReturnObject ro = StaticClass.function(parameter);
And obviously, what I want is to prevent StaticClass to be called and return a specially crafted object. Yeah, I know this static class is not the best approach, but that's outside the scope of my current problem.
My problem is that, when debugging the test code, it actually enters into StaticClass.function when calling Powermockito.when
, and it fails there because somehow, enters with a null value.
All tutorials and guides I've seen says that this is basically what I need to do, so I'm completely lost here. Any ideas?
答案1
得分: 2
你是否正在使用JUnit 5或4来运行你的测试?目前不太清楚,因为你同时使用了两者,@ExtendWith(JUnit5注解)和@RunWith(JUnit4)。
- 如果你正在使用JUnit 5,简而言之,PowerMock不受支持。
@RunWith(PowerMockRunner.class)
会被忽略,@PrepareForTest({StaticClass.class})
也不起作用,因此StaticClass
不会被初始化。 - 对于JUnit 4,测试应该按预期工作,尽管
@ExtendWith(SpringExtension.class)
不起作用。
英文:
Are you running your tests with JUnit 5 or 4? It's not clear, as you are using both, @ExtendWith (JUnit5 annotation) and @RunWith (JUnit4).
- if you are using JUnit 5, PowerMock is, shortly speaking, not supported.
@RunWith(PowerMockRunner.class)
is ignored,@PrepareForTest({StaticClass.class})
has no effect, thus
StaticClass
is not initialized. - with JUnit 4 the test should work as expected, although
@ExtendWith(SpringExtension.class)
wouldn't work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论