Я работаю над приложением Spring Batch и реализовал собственный Partitioner, чтобы разделить обработку на несколько потоков. У меня возникли проблемы с написанием теста JUnit 4 для моего partition метод. Я издевался над своим DataSource и JdbcTemplate, но я не уверен, что я утверждаю правильные условия или правильна ли моя настройка. Этот код проверяет количество вхождений чего-либо, что может быть чем угодно, от записей до событий, как указано методом по dto (объекту передачи данных). Вот что делает логика, описанная простыми словами:
Код запрашивает у dto количество вхождений с помощью метода dto.getNumOfOccur().
Если количество вхождений равно нулю (это означает, что вхождений не было), код устанавливает для dto статус «НОВЫЙ», указывая, что все, что проверяется, является новым или не происходило ранее.
Если какое-либо число больше нуля (это означает, что произошло хотя бы одно событие), статус устанавливается на «СУЩЕСТВУЕТ», что указывает на то, что событие не является новым и происходило раньше.
Этот статус устанавливается с помощью метода dto.setNeworexist() с указанием «NEW» или «EXISTS» в качестве
```
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.scope.context.StepContext;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.batch.test.MetaDataInstanceFactory;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
@RunWith(MockitoJUnitRunner.class)
public class LetterAggregatorTaskletTest {
@InjectMocks
private LetterAggregatorTasklet tasklet;
@Mock
private StepContribution stepContribution;
@Mock
private ChunkContext chunkContext;
@Mock
private StepContext stepContext;
@Mock
private ExecutionContext jobExecutionContext;
private static final String SOURCE_DIR = "src/test/resources";
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(chunkContext.getStepContext()).thenReturn(stepContext);
when(stepContext.getStepExecution()).thenReturn(MetaDataInstanceFactory.createStepExecution());
when(stepContext.getStepExecution().getJobExecution().getExecutionContext()).thenReturn(jobExecutionContext);
when(jobExecutionContext.getString("sourceDir")).thenReturn(SOURCE_DIR);
}
@Test
public void testExecuteSuccess() throws Exception {
createTestFiles("NN3Letter1.txt", "Header1\nRecord1\nRecord2\nTrailer1\n");
createTestFiles("NN3Letter2.txt", "Header2\nRecord3\nRecord4\nTrailer2\n");
RepeatStatus status = tasklet.execute(stepContribution, chunkContext);
assertEquals(RepeatStatus.FINISHED, status);
Path outputFile = Paths.get(SOURCE_DIR, "NN3Letter.txt");
assertTrue(Files.exists(outputFile));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter1.txt"));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter2.txt"));
Files.deleteIfExists(outputFile);
}
@Test(expected = IllegalStateException.class)
public void testValidateDirectoryPath_NullPath() {
tasklet.validateDirectoryPath(null);
}
@Test(expected = IllegalStateException.class)
public void testValidateDirectoryPath_EmptyPath() {
tasklet.validateDirectoryPath("");
}
@Test
public void testValidateDirectoryPath_ValidPath() {
tasklet.validateDirectoryPath(SOURCE_DIR);
assertTrue(true); // Forcefully assert true to cover the method
}
@Test
public void testAggregateFilesForLetterType_NoFiles() throws IOException {
Path emptyDir = Paths.get(SOURCE_DIR, "emptyDir");
Files.createDirectories(emptyDir);
tasklet.aggregateFilesForLetterType(emptyDir.toString(), "NN3");
Path outputFile = emptyDir.resolve("NN3Letter.txt");
assertFalse(Files.exists(outputFile));
Files.deleteIfExists(emptyDir);
}
@Test
public void testAggregateFilesForLetterType_WithFiles() throws IOException {
createTestFiles("NN3Letter1.txt", "Header1\nRecord1\nRecord2\nTrailer1\n");
createTestFiles("NN3Letter2.txt", "Header2\nRecord3\nRecord4\nTrailer2\n");
tasklet.aggregateFilesForLetterType(SOURCE_DIR, "NN3");
Path outputFile = Paths.get(SOURCE_DIR, "NN3Letter.txt");
assertTrue(Files.exists(outputFile));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter1.txt"));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter2.txt"));
Files.deleteIfExists(outputFile);
}
@Test
public void testAggregateFilesForLetterType_WithIOException() throws IOException {
createTestFiles("NN3Letter1.txt", "Header1\nRecord1\nRecord2\nTrailer1\n");
createTestFiles("NN3Letter2.txt", "Header2\nRecord3\nRecord4\nTrailer2\n");
// Simulate IOException by attempting to read a file that doesn't exist
Path nonExistentFile = Paths.get(SOURCE_DIR, "NonExistentFile.txt");
try {
tasklet.aggregateFilesForLetterType(nonExistentFile.toString(), "NN3");
} catch (IOException e) {
assertTrue(true); // Forcefully assert true
}
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter1.txt"));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter2.txt"));
}
@Test
public void testWriteOutputFileWithIOException() throws IOException {
createTestFiles("NN3Letter1.txt", "Header1\nRecord1\nRecord2\nTrailer1\n");
createTestFiles("NN3Letter2.txt", "Header2\nRecord3\nRecord4\nTrailer2\n");
Path readOnlyDir = Paths.get(SOURCE_DIR, "readOnlyDir");
Files.createDirectories(readOnlyDir);
readOnlyDir.toFile().setWritable(false);
try {
tasklet.aggregateFilesForLetterType(readOnlyDir.toString(), "NN3");
} catch (IOException e) {
assertTrue(true); // Forcefully assert true
} finally {
readOnlyDir.toFile().setWritable(true);
Files.deleteIfExists(readOnlyDir);
}
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter1.txt"));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter2.txt"));
}
@Test
public void testDeleteFilesWithIOException() throws IOException {
createTestFiles("NN3Letter1.txt", "Header1\nRecord1\nRecord2\nTrailer1\n");
createTestFiles("NN3Letter2.txt", "Header2\nRecord3\nRecord4\nTrailer2\n");
Path undeletableFile = Paths.get(SOURCE_DIR, "NN3Letter1.txt");
undeletableFile.toFile().setReadable(false);
undeletableFile.toFile().setWritable(false);
try {
tasklet.aggregateFilesForLetterType(SOURCE_DIR, "NN3");
} catch (IOException e) {
assertTrue(true); // Forcefully assert true
} finally {
undeletableFile.toFile().setReadable(true);
undeletableFile.toFile().setWritable(true);
}
Files.deleteIfExists(undeletableFile);
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter2.txt"));
Files.deleteIfExists(Paths.get(SOURCE_DIR, "NN3Letter.txt"));
}
private void createTestFiles(String fileName, String content) throws IOException {
Path tempFile = Paths.get(SOURCE_DIR, fileName);
Files.write(tempFile, content.getBytes());
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... better-way