我正在使用一个 API,该 API 具有从远程服务器获取一些数据的方法。方法用法如下:
Attribute a = obj.getRemoteAttribute();
Attribute
类是这样的
package a.package.outside.my.project;
import java.util.Date;
public class Attribute {
private String id;
private String name;
private Date modifiedAt;
private String metadata;
Attribute(String id, String name, Date modifiedAt, String metadata) {
this.id = id;
this.name = name;
this.modifiedAt = modifiedAt;
this.metadata = metadata;
}
public String getId() {
return id;
}
public Date getModifiedAt() {
return modifiedAt;
}
public String getMetadata() {
return metadata;
}
public String getName() {
return name;
}
}
我正在尝试创建一个单元测试,模拟此方法。我支持 Mockito
。测试是这样的:
@Test
public void getAttributeShouldWork() throws Exception {
Storage mockStorage = Mockito.mock(Storage.class);
Attribute attribute = new Attribute("fake", "fakeName", new SimpleDateFormat("dd/MM/yyyy").parse("21/08/2019"), "fake Metadata");
Mockito.when(storage.getAttribute()).thenReturn(attribute);
// some other stuff
}
但是,测试无法编译 - Attribute
的构造函数(4° 行)是包私有(private)的,我无法在测试中使用它。我也无法扩展该类 - 没有默认构造函数。没有工厂来创建属性,没有可访问的构建器类。我也无法更改 Attribute
的代码。
所以,我的问题是 - 如何创建一个假对象以在该测试中使用模拟?我不希望我的单元测试取决于网络或远程服务器的可用性...
最佳答案
在紧要关头,你可以使用反射:
private static Attribute createAttributeStub() {
try {
Constructor<Attribute> constructor =
Attribute.class.getDeclaredConstructor(String.class, String.class,
Date.class, String.class);
constructor.setAccessible(true);
return constructor.newInstance("fake", "fakeName",
new SimpleDateFormat("dd/MM/yyyy").parse("21/08/2019"), "fake Metadata");
}
catch( ReflectiveOperationException | ParseException e ) {
throw new RuntimeException(e);
}
}
关于java - 无法为单元测试创建属性实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57596851/