I'm writing unit tests for a use case that basically creates a file with the contents of an InputStream.
However, with the lines:
val path = context.filesDir.path + "/issues.csv"
val fos = FileOutputStream(path)
I'm having trouble, as the when trying to create the FileOutputStream from the path it always results in a FileNotFoundException.
This is the complete code:
class SaveFileUseCase @Inject constructor(
private val context: Context,
@DefaultCoroutineDispatcher private val defaultCoroutineDispatcher: CoroutineDispatcher
) {
suspend operator fun invoke(body: ResponseBody) =
withContext(defaultCoroutineDispatcher) {
saveFile(body)
}
private fun saveFile(body: ResponseBody?) {
if (body == null) {
return
}
var input: InputStream? = null
try {
input = body.byteStream()
val path = context.filesDir.path + "/issues.csv"
val fos = FileOutputStream(path)
fos.use { output ->
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int
while (input.read(buffer).also { read = it } != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
} catch (e: Exception) {
Log.e("Error saving file", e.toString())
} finally {
input?.close()
}
}
}
How can I test this?