3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertNotNull;
5 import static org.junit.Assert.assertNotSame;
6 import static org.junit.Assert.assertSame;
7 import static org.junit.Assert.assertTrue;
8 import static org.junit.Assert.fail;
10 import java.util.Collections;
11 import java.util.List;
13 import org.junit.Before;
14 import org.junit.FixMethodOrder;
15 import org.junit.Test;
16 import org.junit.runners.MethodSorters;
18 import dst.ass2.di.type.Container;
19 import dst.ass2.di.type.SimpleSingleton;
21 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
22 public class TransparentInjectionTest {
24 protected IInjectionController ic;
27 public void before() {
28 ic = InjectionControllerFactory.getTransparentInstance();
32 * Injecting prototypes and singletons into an object.
35 public void test_01_inject() {
36 Container container = new Container();
38 assertNotNull("'timestamp' must not be null.", container.timestamp);
39 Long timestamp = container.timestamp;
41 assertSame("Initial timestamp was modified.", timestamp, container.timestamp);
42 assertNotNull("'id' must not be null.", container.id);
43 assertNotNull("'first' must not be null.", container.first);
44 assertNotNull("'second' must not be null.", container.second);
45 assertNotNull("'component' must not be null.", container.component);
46 assertNotNull("'anotherComponent' must not be null.", container.anotherComponent);
48 assertSame("Singletons must be the same object instance.", container.first, container.second);
49 assertNotSame("Prototype references must not be the same object instance.", container.component, container.anotherComponent);
51 List<Long> ids = InjectionUtils.getIds(container);
52 Collections.sort(ids);
53 assertEquals("Initialized object graph with 4 components.", 4, ids.size());
55 for (long i = ids.get(0); i < ids.get(0) + ids.size(); i++) {
56 assertTrue("There is no component with ID " + i + ".", ids.contains(i));
61 * Injecting components into hierarchies.
64 public void test_02_hierarchy() throws IllegalAccessException {
65 Container container = new Container();
66 Long oldId = container.id;
68 SimpleSingleton singleton = ic.getSingletonInstance(SimpleSingleton.class);
69 assertNotNull("'id' must not be null.", singleton.id);
71 // Check that the same singleton is used
72 assertSame("Singletons must be the same object instance.", container.first, singleton);
74 // Verify that exactly 4 new component IDs where used
75 assertEquals("More than 4 components were instantiated with the container.", oldId + 3L, new Container().id.longValue());
78 new SimpleSingleton();
79 fail(InjectionException.class.getSimpleName() + " expected");
80 } catch (InjectionException e) {