3 回答
TA贡献1836条经验 获得超3个赞
将 DriverFactory 中的 devConfig 设为私有。为它提供 getter 和 setter。如果您需要它特定于线程,请将其设为 threadlocal。
public class DriverFactory {
// holds the device config
private static final ThreadLocal<Map<String, String>> devConfig = ThreadLocal
.withInitial(ConcurrentHashMap::new);
public static String getDevConfig(String key) {
return this.devConfig.get().get(key);
}
public static void setDevConfig(Map<String, String> config) {
this.devConfig.get().putAll(config);
}
}
TA贡献1812条经验 获得超5个赞
您可以将 devConfig 包装到 ConcurrentHashMap 中:
public class DriverFactory {
//holds the device config
private static final String CONFIG_KEY = "config_key";
private static final ConcurrentHashMap<String, Map<String, String>> devConfig = new ConcurrentHashMap<>();
public static Map<String, String> setDevConfig(Map<String, String> devConfig) {
return DriverFactory.devConfig.putIfAbsent(CONFIG_KEY, devConfig);
}
public static Map<String, String> getDevConfig() {
return DriverFactory.devConfig.get(CONFIG_KEY);
}
//other lines of code follow
}
@RunWith(ConcurrentTestRunner.class)
public class MyTestRunner{
static final int THREAD_COUNT = 1;
@ThreadCount(THREAD_COUNT) @Override @Test
public void run(){
// Devices class returns config for the device
DriverFactory.setDevConfig(Devices.getConfig())
//other lines of code to perform execution
}
}
public class MobileActions{
public void swipe(){
String pf = DriverFactory.getDevConfig().get("Platform");
//other lines of code
}
}
但是如果你想执行Devices.getConfig()一次,你应该尝试java.util.concurrent.ConcurrentHashMap#computeIfAbsent或自定义锁定。就像是:
public static Map<String, String> getDevConfig() {
return DriverFactory.devConfig
.computeIfAbsent(CONFIG_KEY, s -> Devices.getConfig());
}
添加回答
举报