`我的代码如下:在这里输入代码
public String createDir(String X, String Y){
String dirName = null;
try {
File dir = new File(X+Y);
Path path = FileSystems.getDefault().getPath(X+Y));
File checkPath = new File(path.getParent().toString());
boolean isDirCreated = dir.mkdir();
if(isDirCreated){
dirName = path.getFileName().toString();
}else {
dirName = null;
}
}
catch(SecurityException se){
//message
}
catch(Exception se){
//message
dirName = null;
}
return dirName;
}
`我的JUnit测试用例: 在这个测试用例中,我模拟了path,file的对象。
import static org.junit.Assert.*;
import static org.easymock.EasyMock.expect;
import java.io.File;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.easymock.Mock;
import org.junit.Test;
import com.Users.Folder.Utilities;
public class UtilitiesTest {
@Mock
Utilities Utils;
@Mock
File dir,checkPath;
@Mock
Path path;
@Test
public void testCreateDir() throws Exception {
expect(dir).andReturn(new File("C:\\Users\\sasank\\Desktop\\Docs\\Docs_docready"));
expect(path).andReturn(FileSystems.getDefault().getPath("C:\\Users\\sasank\\Desktop\\Docs\\Docs_docready"));
expect(checkPath).andReturn(new File("C:\\Users\\sasank\\Desktop\\Docs"));
replay(dir,path,checkPath);
assertEquals(true, isDirCreated); //isDirCreated cannot be resolved to a variable
verify(dir,path,checkPath);
assertEquals("Docs_docready", imiUtils.dirName); // dirName cannot be resolved or is not a field
}
`dirName也是一个布尔类型。 我的代码所做的是它在输入目录中创建一个新目录。
答案 0 :(得分:0)
“expect”方法需要从对象调用方法,当调用“andRetuns()”时,该方法将被返回值替换。它用于模拟类/接口行为,不处理普通值。
对于值比较,您应该使用“assertEquals()”,或者在JUnit中使用“assertTrue()”方法。
简单地说:
assertTrue(isDirCreated);
或
assertEquals(true, isDirCreated);
在你的测试中验证病情。
修改: 看到您的代码及其行为,以下是一些评论:
一种更简单的测试方法是(假设“createDir”方法位于名为“Dir”的类中。如果没有,只需将“Dir”替换为您当前的类名称):
@Test
public void testCreateDir() throws Exception {
Dir dir = new Dir();
String directory = dir.createDir("c:/", "test_dir");
assertNotNull(directory); // this one checks if your method returned the correct path
File file = new File(directory);
assertTrue(file.exists()); // this one checks if your method created correctly you directory
}
希望这有帮助。