From a758fd9cef9fb4ad945d623eab443e0bd1bfd901 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Sun, 14 Jan 2018 22:50:55 +0100 Subject: [PATCH] BAEL-1402 code for the article: Try-with-resources in Kotlin --- core-kotlin/pom.xml | 5 ++ .../kotlin/com/baeldung/kotlin/UseTest.kt | 67 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index b511f0dd7b..2cd5275eeb 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -44,6 +44,11 @@ kotlin-stdlib ${kotlin-stdlib.version} + + org.jetbrains.kotlin + kotlin-stdlib-jre8 + ${kotlin-stdlib.version} + org.jetbrains.kotlin kotlin-test-junit diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt new file mode 100644 index 0000000000..15bdfcafd8 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/UseTest.kt @@ -0,0 +1,67 @@ +package com.baeldung.kotlin + +import org.junit.Test +import java.beans.ExceptionListener +import java.beans.XMLEncoder +import java.io.* +import java.lang.Exception +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.test.fail + +class UseTest { + + @Test + fun givenCloseable_whenUseIsCalled_thenItIsClosed() { + val stringWriter = StringWriter() + val writer = BufferedWriter(stringWriter) //Using a BufferedWriter because after close() it throws. + writer.use { + assertEquals(writer, it) + + it.write("something") + } + try { + writer.write("something else") + + fail("write() should have thrown an exception because the writer is closed.") + } catch (e: IOException) { + //Ok + } + + assertEquals("something", stringWriter.toString()) + } + + @Test + fun givenAutoCloseable_whenUseIsCalled_thenItIsClosed() { + val baos = ByteArrayOutputStream() + val encoder = XMLEncoder(PrintStream(baos)) //XMLEncoder is AutoCloseable but not Closeable. + //Here, we use a PrintStream because after close() it throws. + encoder.exceptionListener = ThrowingExceptionListener() + encoder.use { + assertEquals(encoder, it) + + it.writeObject("something") + } + try { + encoder.writeObject("something else") + encoder.flush() + + fail("write() should have thrown an exception because the encoder is closed.") + } catch (e: IOException) { + //Ok + } + } + + @Test + fun whenSimpleFormIsUsed_thenItWorks() { + StringWriter().use { it.write("something") } + } +} + +class ThrowingExceptionListener : ExceptionListener { + override fun exceptionThrown(e: Exception?) { + if(e != null) { + throw e + } + } +} \ No newline at end of file