Skip to content

Commit a375b2d

Browse files
committed
Added tests for service-locator pattern
Fix NPE when requested service is unknown
1 parent fcfdbe7 commit a375b2d

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff 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
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)