简体   繁体   中英

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

I would look at the OSGi Converter specification . 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. See https://docs.osgi.org/specification/osgi.cmpn/8.0.0/util.converter.html#d0e168444 for some examples.

See https://search.maven.org/artifact/org.osgi/org.osgi.util.converter/1.0.8/jar for the API 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

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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