模拟一个 class,它使用另一个 class 的 static void 方法

Mocking a class which uses static void method of another class

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(),我如何确保没有任何反应?

如评论中所述,您应该知道许多事情可能会因为 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

符合预期