Wil*_*voy 3 java junit mocking powermock
public class ProjectIdInitializer {
public static void setProjectId(String projectId) {
//load spring context which i want to escape in my test
}
}
public class MyService {
public Response create(){
...
ProjectIdInitializer.setProjectId("Test");
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ProjectIdInitializer.class})
public class MyServiceTest{
@InjectMocks
private MyService myServiceMock ;
public void testCreate() {
PowerMockito.mockStatic(ProjectIdInitializer.class);
PowerMockito.doNothing().when(ProjectIdInitializer.class, "setProjectId", Mockito.any(String.class));
// Does not work,still tries to load spring context
Response response=myServiceMock .create();
}
Run Code Online (Sandbox Code Playgroud)
如果从myservice调用ProjectIdInitializer.setProjectId(),我如何确保没有任何反应?
小智 5
正如评论中所述,您应该知道,由于PowerMock,许多事情可能会破坏.
您需要使用PowerMock运行器,类似于:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ProjectIdInitializer.class)
public class MyServiceTest{
private MyService myService = new MyService();
public void testCreate()
{
PowerMockito.mockStatic(ProjectIdInitializer.class);
PowerMockito.doNothing().when(ProjectIdInitializer.class, "setProjectId", Mockito.any(String.class));
Response response=myService.create();
}
}
Run Code Online (Sandbox Code Playgroud)
另见本文档.
这个自包含的样本:
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.ProjectIdInitializer.class)
public class A {
private MyService myService = new MyService();
@Test
public void testCreate() throws Exception {
PowerMockito.mockStatic(ProjectIdInitializer.class);
PowerMockito.doNothing().when(ProjectIdInitializer.class, "setProjectId", Mockito.any(String.class));
System.out.println("Before");
Response response = myService.create();
System.out.println("After");
}
public static class ProjectIdInitializer {
public static void setProjectId(String projectId) {
//load spring context which i want to escape in my test
System.out.println(">>>>>> Game over");
}
}
public static class Response {
}
public static class MyService {
public Response create() {
// ...
ProjectIdInitializer.setProjectId("Test");
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Before
After
Run Code Online (Sandbox Code Playgroud)
正如所料