File tree Expand file tree Collapse file tree 2 files changed +45
-1
lines changed
main/java/com/iluwatar/servicelocator
test/java/com/iluwatar/servicelocator Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change @@ -32,7 +32,9 @@ public static Service getService(String serviceJndiName) {
3232 */
3333 InitContext ctx = new InitContext ();
3434 serviceObj = (Service ) ctx .lookup (serviceJndiName );
35- serviceCache .addService (serviceObj );
35+ if (serviceObj != null ) { // Only cache a service if it actually exists
36+ serviceCache .addService (serviceObj );
37+ }
3638 return serviceObj ;
3739 }
3840 }
Original file line number Diff line number Diff line change 1+ package com .iluwatar .servicelocator ;
2+
3+ import org .junit .Test ;
4+
5+ import static org .junit .Assert .*;
6+
7+ /**
8+ * Date: 12/29/15 - 19:07 PM
9+ *
10+ * @author Jeroen Meulemeester
11+ */
12+ public class ServiceLocatorTest {
13+
14+ /**
15+ * Verify if we just receive 'null' when requesting a non-existing service
16+ */
17+ @ Test
18+ public void testGetNonExistentService () {
19+ assertNull (ServiceLocator .getService ("fantastic/unicorn/service" ));
20+ assertNull (ServiceLocator .getService ("another/fantastic/unicorn/service" ));
21+ }
22+
23+ /**
24+ * Verify if we get the same cached instance when requesting the same service twice
25+ */
26+ @ Test
27+ public void testServiceCache () {
28+ final String [] serviceNames = new String []{
29+ "jndi/serviceA" , "jndi/serviceB"
30+ };
31+
32+ for (final String serviceName : serviceNames ) {
33+ final Service service = ServiceLocator .getService (serviceName );
34+ assertNotNull (service );
35+ assertEquals (serviceName , service .getName ());
36+ assertTrue (service .getId () > 0 ); // The id is generated randomly, but the minimum value is '1'
37+ assertSame (service , ServiceLocator .getService (serviceName ));
38+ }
39+
40+ }
41+
42+ }
You can’t perform that action at this time.
0 commit comments