Java 试图模拟我的静态方法,需要返回一个对象,但它总是返回null

Java 试图模拟我的静态方法,需要返回一个对象,但它总是返回null,java,junit,mocking,Java,Junit,Mocking,这是我的密码 @Test public void testProcess() throws Exception { GenericResults result = new GenericResults(); result.setCount(2); result.setSuccess(true); result.setTarget((Integer)100); PowerMockito.when(PrcssDAO.createProcess(Matchers.

这是我的密码

@Test

public void testProcess() throws Exception {

    GenericResults result = new GenericResults();
    result.setCount(2);
    result.setSuccess(true);
    result.setTarget((Integer)100);

PowerMockito.when(PrcssDAO.createProcess(Matchers.anyString(), Matchers.anyString())).thenReturn(result);

}

返回的
结果
对象始终为空。这是为什么?

您是否在测试类中考虑了以下步骤:

  • 使用
    @RunWith(PowerMockRunner.class)
    注释 测试用例的类级别
  • 使用
    @PrepareForTest(包含staticmethod.class的类)
    测试用例的类级别上的注释
  • 使用
    PowerMock.mockStatic(包含staticmethod.class的类)
    模拟这个类的所有方法
  • 使用
    PowerMock.replay(包含staticmethod.class的类)
    更改 将类设置为重播模式
  • 使用
    PowerMock.verify(包含staticmethod.class的类)
    进行更改 要验证模式的类

  • 这里是

    好的,我在本地复制了您的代码来解决它,您需要将上述答案中的选项三添加到您的代码中,这样测试代码就会变成:

    @Test
    public void testProcess() throws Exception {
        GenericResults result = new GenericResults();
        result.setCount(2);
        result.setSuccess(true);
        result.setTarget(100);
            // The next line is the one you're missing
        PowerMockito.mockStatic(PrcssDAO.class);
        Mockito.when(PrcssDAO.createProcess(Matchers.anyString(), Matchers.anyString())).thenReturn(result);
        assertNotNull(PrcssDAO.createProcess("any", "argument"));
    }
    

    你在课堂上加入了正确的注释吗?特别是@RunWith(PowerMockRunner.class)和@PrepareForTest(PrcssDAO.class)。基本上,您可以向我们展示您的其余代码。@RunWith(PowerMockRunner.class)@PrepareForTest({PrcssDAO.class,SysParamDAO.class})公共类svscommevntmanagest{@Test public void testProcess()抛出异常{genericsults result=new genericsults();result.setCount(2);result.setSuccess(true);result.setTarget((整数)100);PowerMockito.when(PrcssDAO.createProcess(Matchers.anyString(),Matchers.anyString()))。然后返回(result);}是的,我使用了上述所有内容。我在问题中没有提到