模拟一个使用另一个类的静态void方法的类

时间:2015-03-27 17:00:20

标签: 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();
    }

如果从myservice调用ProjectIdInitializer.setProjectId(),我如何确保没有任何反应?

1 个答案:

答案 0 :(得分:5)

正如评论中所述,您应该知道,由于PowerMock,许多事情可能会中断。

你需要使用PowerMock runner,类似的东西:

@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();
  }
}

另见this doc.


这个自包含的样本:

@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;
        }
    }
}

输出:

Before
After

正如预期的那样