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


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运行器,就像这样:

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

另请参阅此文档。


此自包含示例:

@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

不出所料

相关内容

  • 没有找到相关文章

最新更新