我有以下代码:
public class FolderServiceImpl implements FolderService {
private static final Logger L = LoggerFactory.getLogger(FolderServiceImpl.class);
public int getStatus(String folderPath) {
int status = 0;
File folderStatusFile = new File(folderPath, ".folderstatus");
if (folderStatusFile.exists()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(folderStatusFile));
String line = br.readLine();
status = Integer.parseInt(line);
} catch (Exception e) {
L.error("can't read file " + folderStatusFile.getAbsolutePath(), e);
status = 4;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
L.warn("could not close reader ", e);
}
}
}
} else {
status = 3;
}
return status;
}
}
我想测试此方法,而无需为每种情况创建实际文件。我应该使用Java 1.7,Junit 4,Mockito和/或PowerMockito。
关于如何做的任何想法?
我正在谈论嘲笑数据源或简单地更改方法的输入。
我的测试看起来像这样:
`@rule public temeraryFolder文件夹= new temoraryFolder();
private FolderServiceImpl serviceToTest = new FolderServiceImpl();
private String folderPath;
@Before
public void setUp() {
folderPath = folder.getRoot().getAbsolutePath();
try {
folder.newFile(".folderstatus");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void shouldReturnFolderStatus3WhenFolderStatusIsNotFound() {
// given
deleteFolderStatusFile();
// actual
int status = serviceToTest.getFolderStatus(folderPath);
// expected
assertEquals(3, status);
}
@Test
public void shouldReturnFolderStatus4WhenTheStatusIsUnreadable() {
// given
writeStatusToTestFile("Test");
// actual
int status = serviceToTest.getFolderStatus(folderPath);
// expected
assertEquals(4, status);
}
@Test
public void shouldReturnFolderStatusInTheFile() {
// given
writeStatusToTestFile("1");
// actual
int status = serviceToTest.getFolderStatus(folderPath);
// expected
assertEquals(1, status);
}
private void writeStatusToTestFile(String status) {
Path file = Paths.get(folder.getRoot().getAbsolutePath(), ".folderstatus");
try {
Files.write(file, status.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private void deleteFolderStatusFile() {
Path file = Paths.get(folder.getRoot().getAbsolutePath(), ".folderstatus");
try {
Files.delete(file);
} catch (IOException e) {
e.printStackTrace();
}
}`
尽管@benheid的答案可能会更改为不同的方法。
IMHO每当我使用PowerMock(-ito)时,这都是不良设计的投降。此外,PowerMock解决方案将混淆测试覆盖工具,因为它在启动覆盖范围测量后更改了应用程序代码。
所以我宁愿使用的方法是坚持清洁代码和OOP规则。
其中之一是关注点的分离。
在您的情况下,该方法创建了一些基础架构类(依赖项),即FileReader
和BufferedReader
。
但是(直接)依赖关系的实例化不是包含业务逻辑的类的责任。
因此,我建议将代码重构为单独的类:
class ReaderFactory {
public BufferedReader createFor(File file) throws FileNotFoundException {
return new BufferedReader(new FileReader(file));
}
}
您的班级会更改为:
class FolderServiceImpl {
private static final Logger L = LoggerFactory.getLogger(FolderServiceImpl.class);
private final ReaderFactory readerFactory;
FolderServiceImpl(ReaderFactory readerFactory) {
this.readerFactory = readerFactory;
}
public int getStatus(String folderPath) {
int status = 0;
File folderStatusFile = new File(folderPath, ".folderstatus");
// try "with resource" takes care of closing the reader
try (BufferedReader br = readerFactory.createFor(folderStatusFile);) {
String line = br.readLine();
status = Integer.parseInt(line);
} catch (IOException e) {
status = 3;
} catch (Exception e) {
L.error("can't read file " + folderStatusFile.getAbsolutePath(), e);
status = 4;
}
return status;
}
}
您的测试就是这样:
public class FolderServiceImplTest {
private static final String ANY_FILE_NAME = "";
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private ReaderFactory readerFactory;
@InjectMocks
FolderServiceImpl sut;
@Test
public void getStatus_FileNotExisting_returnStatus3() throws Exception {
// arrange
Mockito.doThrow(new FileNotFoundException("UnitTest")).when(readerFactory).createFor(Mockito.any(File.class));
// act
int status = sut.getStatus(ANY_FILE_NAME);
// assert
Assert.assertThat("status",status,CoreMatchers.equalTo(3));
}
@Test
public void getStatus_ValidFile_returnFileContentAsInt() throws Exception {
// arrange
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.doReturn(bufferedReader).when(readerFactory).createFor(Mockito.any(File.class));
Mockito.doReturn("4711").when(bufferedReader).readLine();
// act
int status = sut.getStatus(ANY_FILE_NAME);
// assert
Assert.assertThat("status",status,CoreMatchers.equalTo(4711));
}
}
您必须使用类似的东西:
@RunWith(PowerMockRunner.class)
@PrepareForTest(tests.class)
public class test {
@Test
public void test() throws Exception {
File fileMock = Mockito.mock(File.class);
PowerMockito.whenNew(File.class).withArguments(Mockito.anyString(), Mockito.anyString()).thenReturn(fileMock);
FolderServiceImpl sut = new FolderServiceImpl sut ();
Mockito.when(fileMock.exists()).thenReturn(true);
sut.getStatus("");
// Your verifications..
}
}
PowerMock将模拟在类的方法GetStatus中创建的文件对象。使用Mockito。当您可以说出代码中folderstusfile.exists()的返回值时。
编辑
我已经在Maven中包括了以下两个罐子,但是您不需要使用maven:https://mvnrepository.com/artifact/org.powermock/powermock/powermock-mock-module-junit4/1.4.6 and https://https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito/1.4.9和https://mvnrepository.com/artifact/artifact/org.mockito/mockito/mockito-mockito-10.10.10.19