gpt4 book ai didi

testing - PowerMockito.whenNew 不工作

转载 作者:行者123 更新时间:2023-11-28 20:03:16 29 4
gpt4 key购买 nike

更新。最后检查工作示例。


我有一个类:

package test;

public class ClassXYZ {
private final String message;

public ClassXYZ() {
this.message = "";
}

public ClassXYZ(String message) {
this.message = message;
}

@Override
public String toString() {
return "ClassXYZ{" + message + "}";
}
}

和一个测试:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
public class MockClassXYZ {

@Test
public void test() throws Exception {
PowerMockito.whenNew(ClassXYZ.class).withNoArguments().thenReturn(new ClassXYZ("XYZ"));

System.out.println(new ClassXYZ());
}
}

但它仍然创建一个真正的类并打印:

ClassXYZ{}

我做错了什么?

P.S. Maven 部门:

<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
</dependencies>

工作示例:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassXYZ.class)
public class MockClassXYZ {
@Test
public void test() throws Exception {
ClassXYZ mockXYZ = mock(ClassXYZ.class);
when(mockXYZ.toString()).thenReturn("XYZ");

PowerMockito.whenNew(ClassXYZ.class).withNoArguments().thenReturn(mockXYZ);

ClassXYZ obj = new ClassXYZ();
System.out.println(obj);
}
}

最佳答案

您的测试类中缺少 @PrepareForTest(ClassXYZ.class),请参阅文档 herehere .从第一个链接:

Mock construction of new objects

Quick summary

  1. Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
  2. Use the @PrepareForTest(ClassThatCreatesTheNewInstance.class) annotation at the class-level of the test case.

[...]


另请注意,如果您要求模拟框架返回模拟类的真实实例,则模拟构造函数没有意义。

关于testing - PowerMockito.whenNew 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31682448/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com