1
+ package com.baeldung.renameFile
2
+
3
+ import org.assertj.core.api.Assertions.assertThat
4
+ import org.assertj.core.api.Assertions.fail
5
+ import org.junit.jupiter.api.Test
6
+ import java.nio.file.Files
7
+ import java.nio.file.Paths
8
+ import java.nio.file.StandardCopyOption
9
+
10
+ class RenameFileUnitTest {
11
+
12
+ @Test
13
+ fun `when using renameTo, then file is renamed` () {
14
+ val oldFilePath = Paths .get(" src/test/resources/oldFile.txt" )
15
+ val newFilePath = Paths .get(" src/test/resources/newFile.txt" )
16
+
17
+ val oldFile = oldFilePath.toFile()
18
+ oldFile.writeText(" Hello Kotlin" )
19
+
20
+ val newFile = newFilePath.toFile()
21
+
22
+ if (oldFile.renameTo(newFile)) {
23
+ assertThat(newFile.exists()).isTrue()
24
+ } else {
25
+ fail(" Failed to rename file." )
26
+ }
27
+ // cleanup
28
+ newFile.delete()
29
+ }
30
+
31
+ @Test
32
+ fun `when renaming, checks on files succeed` () {
33
+ val oldFilePath = Paths .get(" src/test/resources/oldFile.txt" )
34
+ val newFilePath = Paths .get(" src/test/resources/newFile.txt" )
35
+
36
+ val oldFile = oldFilePath.toFile()
37
+ oldFile.writeText(" Hello Kotlin" )
38
+
39
+ val newFile = newFilePath.toFile()
40
+
41
+ if (oldFile.exists()) {
42
+ if (newFile.exists()) {
43
+ fail(" A file with the new name already exists." )
44
+ } else {
45
+ if (oldFile.renameTo(newFile)) {
46
+ assertThat(newFile.exists()).isTrue()
47
+ } else {
48
+ fail(" Fail rename failed" )
49
+ }
50
+ }
51
+ } else {
52
+ fail(" The old file does not exist." )
53
+ }
54
+ // cleanup
55
+ newFile.delete()
56
+ }
57
+
58
+ @Test
59
+ fun `when using move, then file is renamed` () {
60
+ val oldFilePath = Paths .get(" src/test/resources/oldFile.txt" )
61
+ val newFilePath = Paths .get(" src/test/resources/newFile.txt" )
62
+
63
+ val oldFile = oldFilePath.toFile()
64
+ oldFile.writeText(" Hello Kotlin" )
65
+
66
+ Files .move(oldFilePath, newFilePath, StandardCopyOption .REPLACE_EXISTING )
67
+ val newFile = newFilePath.toFile()
68
+ assertThat(newFile.exists()).isTrue()
69
+ // cleanup
70
+ newFile.delete()
71
+ }
72
+
73
+ }
0 commit comments