Skip to content

Commit 322ac5b

Browse files
Update AbstractFileItemWriter deletion test
1 parent d9a91ce commit 322ac5b

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/support/AbstractFileItemWriterTest.java

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616

1717
package org.springframework.batch.infrastructure.item.support;
1818

19-
import static org.junit.jupiter.api.Assertions.assertEquals;
20-
import static org.junit.jupiter.api.Assertions.assertNotNull;
21-
import static org.junit.jupiter.api.Assertions.assertThrows;
19+
import static org.junit.jupiter.api.Assertions.*;
2220
import static org.mockito.Mockito.when;
2321

2422
import java.io.File;
23+
import java.io.IOException;
24+
import java.io.RandomAccessFile;
2525

2626
import org.junit.jupiter.api.Test;
2727
import org.mockito.Mockito;
@@ -39,24 +39,32 @@
3939
class AbstractFileItemWriterTests {
4040

4141
@Test
42-
void testFailedFileDeletionThrowsException() {
42+
void testFailedFileDeletionThrowsException() throws Exception {
43+
4344
File outputFile = new File("target/data/output.tmp");
44-
File mocked = Mockito.spy(outputFile);
45+
outputFile.getParentFile().mkdirs();
4546

4647
TestFileItemWriter writer = new TestFileItemWriter();
47-
48-
writer.setResource(new FileSystemResource(mocked));
48+
writer.setResource(new FileSystemResource(outputFile));
4949
writer.setShouldDeleteIfEmpty(true);
5050
writer.setName(writer.getClass().getSimpleName());
51+
5152
writer.open(new ExecutionContext());
5253

53-
when(mocked.delete()).thenReturn(false);
54+
// Keep the file open so Files.delete(...) cannot delete it (Windows)
55+
RandomAccessFile lock = new RandomAccessFile(outputFile, "rw");
5456

55-
ItemStreamException exception = assertThrows(ItemStreamException.class, writer::close,
56-
"Expected exception when file deletion fails");
57+
try {
58+
ItemStreamException exception = assertThrows(ItemStreamException.class, writer::close);
5759

58-
assertEquals("Failed to delete empty file on close", exception.getMessage(), "Wrong exception message");
59-
assertNotNull(exception.getCause(), "Exception should have a cause");
60+
assertEquals("Failed to delete empty file on close", exception.getMessage());
61+
62+
assertNotNull(exception.getCause());
63+
assertTrue(exception.getCause() instanceof IOException);
64+
}
65+
finally {
66+
lock.close();
67+
}
6068
}
6169

6270
private static class TestFileItemWriter extends AbstractFileItemWriter<String> {

0 commit comments

Comments
 (0)