close jndi context

This commit is contained in:
Loredana Crusoveanu 2021-10-08 11:58:38 +03:00
parent 938983be23
commit eb64f25808
2 changed files with 13 additions and 3 deletions

View File

@ -1,5 +1,6 @@
package com.baeldung.jndi; package com.baeldung.jndi;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.DriverManagerDataSource;
@ -57,4 +58,10 @@ class JndiUnitTest {
assertNotNull(ds.getConnection()); assertNotNull(ds.getConnection());
} }
@AfterAll
static void tearDown() throws Exception {
ctx.close();
}
} }

View File

@ -6,7 +6,6 @@ import javax.naming.InitialContext;
import javax.naming.NameNotFoundException; import javax.naming.NameNotFoundException;
import javax.naming.NoInitialContextException; import javax.naming.NoInitialContextException;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -17,13 +16,16 @@ import org.springframework.mock.jndi.SimpleNamingContextBuilder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class JndiExceptionsUnitTest { public class JndiExceptionsUnitTest {
InitialContext ctx;
@Test @Test
@Order(1) @Order(1)
void givenNoContext_whenLookupObject_thenThrowNoInitialContext() { void givenNoContext_whenLookupObject_thenThrowNoInitialContext() {
assertThrows(NoInitialContextException.class, () -> { assertThrows(NoInitialContextException.class, () -> {
JndiTemplate jndiTemplate = new JndiTemplate(); JndiTemplate jndiTemplate = new JndiTemplate();
InitialContext ctx = (InitialContext) jndiTemplate.getContext(); ctx = (InitialContext) jndiTemplate.getContext();
ctx.lookup("java:comp/env/jdbc/datasource"); ctx.lookup("java:comp/env/jdbc/datasource");
ctx.close();
}).printStackTrace(); }).printStackTrace();
} }
@ -35,8 +37,9 @@ public class JndiExceptionsUnitTest {
builder.activate(); builder.activate();
JndiTemplate jndiTemplate = new JndiTemplate(); JndiTemplate jndiTemplate = new JndiTemplate();
InitialContext ctx = (InitialContext) jndiTemplate.getContext(); ctx = (InitialContext) jndiTemplate.getContext();
ctx.lookup("badJndiName"); ctx.lookup("badJndiName");
ctx.close();
}).printStackTrace(); }).printStackTrace();
} }