下面的代码是将内容写入到文件中。
public String saveSecretToFile() {
File file = new File("test.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(secretValue);//secretValue is the content
} catch (IOException e) {
LOGGER.error("Error writing to file: {}", e.getMessage());
}
}
JUnit 测试用例中未涵盖 catch 块。
@InjectMocks
private MyHelper myHelper;
try (MockedStatic<FileOutputStream> mockedStatic = Mockito.mockStatic(FileOutputStream.class)) {
FileWriter mockFile = mock(FileWriter.class);
OutputStream mockFileWriter = Mockito.spy(new FileOutputStream(String.valueOf(mockFile)));
doThrow(new IOException("IO error")).when(mockFileWriter).write(anyString().getBytes());
IOException thrown = assertThrows(IOException.class, () -> myHelper.saveToFile("secretName"));
}
我读过,模拟 BufferedWriter 不起作用,因为应该模拟 FileWriter 的内部 OutputStream。 unitest 情况的预期结果是抛出异常。但是,结果显示为 java.lang.AssertionError:预期抛出 java.io.IOException,但没有抛出任何内容
我会做这样的事情:
1- 首先实现写入模拟。
public class MyHelper {
private final BufferedWriter writer;
// Constructor for dependency injection
public MyHelper(BufferedWriter writer) {
this.writer = writer;
}
public void saveSecretToFile(String secretValue) {
try {
writer.write(secretValue);
writer.flush();
} catch (IOException e) {
LOGGER.error("Error writing to file: {}", e.getMessage());
throw new RuntimeException("Error writing to file", e); // Throw to signify error
}
}
}
2- 使用我以前的服务的模拟,使用 IOException 将测试写入快乐路径和不快乐路径,并检查该方法是否被调用。
有一个验证检查该方法是否已被调用。
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.BufferedWriter;
import java.io.IOException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
class MyHelperTest {
@Mock
private BufferedWriter mockWriter;
@InjectMocks
private MyHelper myHelper;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void testSaveSecretToFile_Success() throws IOException {
// Arrange
String secretValue = "secret";
// Act
myHelper.saveSecretToFile(secretValue);
// Assert
verify(mockWriter, times(1)).write(secretValue);
verify(mockWriter, times(1)).flush();
}
@Test
void testSaveSecretToFile_ThrowsException() throws IOException {
// Arrange
String secretValue = "secret";
doThrow(new IOException("IO error")).when(mockWriter).write(anyString());
// Act & Assert
Exception exception = assertThrows(RuntimeException.class, () -> myHelper.saveSecretToFile(secretValue));
assertTrue(exception.getCause() instanceof IOException);
assertEquals("Error writing to file", exception.getMessage());
verify(mockWriter, times(1)).write(secretValue); // Verify write was called before exception
}
}