简体   繁体   English

OSGi R7 - 如何在测试类中实例化配置?

[英]OSGi R7 - How to instantiate a configuration inside a test class?

The configuration class looks like this :配置类如下所示:

@ObjectClassDefinition(name="SampleConfig", description="This is a configuration class for Sample")
public @interface SampleConfig {

@AttributeDefinition(name="username", defaultValue = "username", description = "some sample")
String username() default "username";

}

The main class that uses the configuration looks like this:使用配置的主类如下所示:

@Component(name="Sample", configurationPolicy = ConfigurationPolicy.REQUIRE)
@Designate(ocd = SampleConfig.class)
public class Sample {

@Activate
void activate(final SampleConfig config) {
    String username = config.username();
}

I am working on writing a TestSample JUnit class but not sure how to pass the config parameter to the activate method我正在编写 TestSample JUnit 类,但不确定如何将 config 参数传递给 activate 方法

I would look at the OSGi Converter specification .我会看看OSGi Converter 规范 You can use a converter instance to convert a Map having the desired test values into a SampleConfig instance which can then be passed to the method.您可以使用转换器实例将具有所需测试值的 Map 转换为SampleConfig实例,然后可以将其传递给该方法。 See https://docs.osgi.org/specification/osgi.cmpn/8.0.0/util.converter.html#d0e168444 for some examples.有关一些示例,请参阅https://docs.osgi.org/specification/osgi.cmpn/8.0.0/util.converter.html#d0e168444

See https://search.maven.org/artifact/org.osgi/org.osgi.util.converter/1.0.8/jar for the API jar.有关 API jar,请参阅https://search.maven.org/artifact/org.osgi/org.osgi.util.converter/1.0.8/jar

For this purpose, I created a small utility that allows you to set the configurations in a type safe way based on the configuration annotation (or interface).为此,我创建了一个小实用程序,允许您根据配置注释(或接口)以类型安全的方式设置配置。 It uses the same idea as mocking libraries.它使用与模拟库相同的想法。

https://github.com/aQute-os/biz.aQute.osgi.util/tree/master/biz.aQute.osgi.configuration.util https://github.com/aQute-os/biz.aQute.osgi.util/tree/master/biz.aQute.osgi.configuration.util

@interface FooConfig {
    int port() default 10;
    String host() default "localhost";
}

@Test
public void testSimple() throws Exception {
   ConfigHelper<FooConfig> ch = new ConfigHelper<>(FooConfig.class, cm);
   Map<String, Object> read = ch.read("foo.bar");
   assertEquals(0, read.size());

   assertEquals( 10, ch.d().port());
   assertEquals( "localhost", ch.d().host());

   ch.set( ch.d().port(), 3400);
   ch.set( ch.d().host(), "example.com");
   ch.update();

   Configuration c = cm.getConfiguration("foo.bar");
   Dictionary<String,Object> properties = c.getProperties();
   assertEquals( 3400, properties.get("port"));
   assertEquals( "example.com", properties.get("host"));
}

Maven coordinate: biz.aQute:biz.aQute.osgi.configuration.util:1.7.0 Maven 坐标: biz.aQute:biz.aQute.osgi.configuration.util:1.7.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM