我有一个Firebase管理员帮助程序类,我正在使用Spock进行测试。该类的构造函数将调用类中的另一个方法来初始化某些字段(如果必须),如下所示:
public class FirebaseUtility {
private static FirebaseDatabase db = null;
public FirebaseUtility() throws IOException {
if (db == null) {
initializeFirebase();
}
}
public void initializeFirebase() throws IOException {
InputStream serviceAccount = ClassLoader.getSystemResourceAsStream("serviceAccount.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("<my_database_url>").build();
FirebaseApp.initializeApp(options);
db = FirebaseDatabase.getInstance();
}
}
基本上,如果已经设置了FirebaseDatabase,则无需执行所有初始化代码。
我尝试过这样做,但它似乎不起作用:
class FirebaseUtilitySpec extends Specification {
def "instantiating FirebaseUtility should run initialization code"() {
given:
def f
when:
f = new FirebaseUtility()
then:
1 * f.initializeFirebase()
}
}
答案 0 :(得分:1)
首先,您无法检查原始对象上的交互,您需要使用模拟或间谍。此外,这些类型的对象不能拦截静态方法或构造函数上的交互。为此,您必须添加Mockito甚至PowerMock。但基本上,静态方法无论如何都是丑陋的,并且在构造函数调用中初始化静态成员是没有必要的。只需对数据库对象使用惰性getter并拦截其行为。
我稍微简化了您的示例,删除了外部依赖项,只是模拟了Firebase,以便更轻松地使用MCVE回答:
package de.scrum_master.stackoverflow;
public class FirebaseDatabase {
private static FirebaseDatabase instance;
public static FirebaseDatabase getInstance() {
if (instance == null)
instance = new FirebaseDatabase();
return instance;
}
}
package de.scrum_master.stackoverflow;
public class FirebaseUtility {
private static FirebaseDatabase db = null;
public FirebaseDatabase getDb() {
if (db == null)
initializeFirebase();
return db;
}
protected void initializeFirebase() {
db = FirebaseDatabase.getInstance();
}
}
package de.scrum_master.stackoverflow
import spock.lang.Specification
class FirebaseUtilitySpec extends Specification {
def "instantiating FirebaseUtility runs initialization code exactly once"() {
given:
FirebaseUtility f = Spy()
when:
f.getDb()
then:
1 * f.initializeFirebase()
when:
f.getDb()
then:
0 * f.initializeFirebase()
}
}