[英]mocking final class with junit fail
I am trying to write junit using Powermock for below scenario. 我正在尝试使用Powermock在以下情况下编写junit。 I have tried to write sample code instead of copying exact code which is not allowed to post here.
我尝试编写示例代码,而不是复制不允许在此处发布的确切代码。
class MainClass{
First.getC().setStr("abc");
}
final class First{
public static ClassC getC() {
return c;
}
}
class ClassC{
private String str;
//getter/setter for str
}
Its always failing. 它总是失败。 My junit is as follow:
我的junit如下:
@RunWith(SpringJUnit4ClassRunner.class)
public class MainClassTest {
@Spy MainClass;
@Mock
private ClassC classc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(First.class);
}
@Test
public void myTest(){
when(First.getC()).thenReturn(classc);
Mockito.doCallRealMethod().when(classc).setStr(Mockito.any(String.class))
}
}
There is a detailed explanations about the steps required to mock static methods. 有关模拟静态方法所需步骤的详细说明 。
You are missing the crucial 您错过了关键
Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.
在测试用例的类级别使用@PrepareForTest(ClassThatContainsStaticMethod.class)批注。
Beyond that: I think that it still will not work, because step one says: 除此之外:我认为它仍然行不通,因为第一步说:
Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
在测试用例的类级别使用@RunWith(PowerMockRunner.class)批注。
Which would prevent you from using the Spring runner. 这将阻止您使用SpringRunner。
So, my suggestion here: forget about using static methods that require mocking in test cases. 因此,我的建议是: 忘记使用需要在测试用例中进行模拟的静态方法。 Keep in mind that static is an abnormality in good OOP anyway.
请记住,无论如何, 静态是良好OOP中的异常。 So instead of "fixing" behavior in static methods - denote the functionality in an interface.
因此,不是在静态方法中“修复”行为,而是在接口中表示功能。 Worst case you can still implement the interface in some class that has a static "singleton" instance which you then pass to the code that needs to use the interface.
最坏的情况是,您仍然可以在具有静态“单例”实例的某些类中实现接口,然后将该实例传递给需要使用该接口的代码。
Because then you can use plain Mockito to mock that interface and pass the mock around! 因为这样您可以使用普通的Mockito模拟该接口并传递模拟!
Long story short: you wrote hard to test code, forcing you to think about PowerMock - which would force you to abandon the Spring test runner - which would make your life 10 times harder. 长话短说:您编写了很难测试的代码,迫使您考虑使用PowerMock-这将迫使您放弃Spring测试运行器-这会使您的生活变得困难10倍。 So change your code to be easy to test and forget about PowerMock.
因此,更改代码以使其易于测试,而无需考虑PowerMock。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.