title: Testing private methods in Kotlin
body: <p>How to test private methods in Kotlin? I tried to add <code>@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)</code> from <code>androidx.annotation.VisibleForTesting</code> but it doesn’t make my function private</p>
  
  <p>This is how I’m using it</p>
  
  <pre><code>@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
  fun doSomething() {}
  </code></pre>
  
  <p>[EDIT]</p>
  
  <p>I understand that I shouldn't test <code>private</code> methods, but it's now always trivial. What about below case.</p>
  
  <p>I have a CsvReader class</p>
  
  <pre><code>class CsvReader(private val inputStream: InputStream, private val separator: String = "\t") {
      fun read(): List&lt;String&gt; {
          return read(inputStream.bufferedReader())
      }
      private fun read(bufferedReader: BufferedReader): List&lt;String&gt; {
          val line = bufferedReader.use { it.readLine() } // `use` is like try-with-resources in Java
          return parse(line)
      }
      private fun parse(line: String): List&lt;String&gt; {
          return line.split(separator)
      }
  }
  </code></pre>
  
  <p>And I wrote tests for it</p>
  
  <pre><code>class CsvReaderTest {
      private val stream = mock&lt;InputStream&gt;()
      private val reader = CsvReader(stream)
      private val bufferedReader = mock&lt;BufferedReader&gt;()
      @Test
      fun read() {
          whenever(bufferedReader.readLine()).thenReturn("Jakub\tSzwiec")
          reader.read(bufferedReader) shouldEqual listOf("Jakub", "Szwiec")
      }
      @Test
      fun readWhenEmpty() {
          whenever(bufferedReader.readLine()).thenReturn("")
          reader.read(bufferedReader) shouldEqual listOf("")
      }
      @Test
      fun throwIOExceptionWhenReadingProblems() {
          whenever(bufferedReader.readLine()).thenThrow(IOException::class.java)
          val read = { reader.read(bufferedReader) }
          read shouldThrow IOException::class
      }
  }
  </code></pre>
  
  <p>Unfortunately, for tests I need to call private function <code>fun read(bufferedReader: BufferedReader): List&lt;String&gt;</code> because when mocking <code>File</code>, <code>file.bufferedReader</code> gives <code>NullPointerException</code> <a href="https://stackoverflow.com/questions/27915552/unable-to-mock-bufferedwriter-class-in-junit">Unable to mock BufferedWriter class in junit</a></p>