使用Easymock进行JAVA JUnit测试

时间:2017-02-24 16:42:11

标签: java junit

`我的代码如下:在这里输入代码

   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也是一个布尔类型。 我的代码所做的是它在输入目录中创建一个新目录。

1 个答案:

答案 0 :(得分:0)

“expect”方法需要从对象调用方法,当调用“andRetuns()”时,该方法将被返回值替换。它用于模拟类/接口行为,不处理普通值。

对于值比较,您应该使用“assertEquals()”,或者在JUnit中使用“assertTrue()”方法。

简单地说:

assertTrue(isDirCreated);

assertEquals(true, isDirCreated);

在你的测试中验证病情。

修改: 看到您的代码及其行为,以下是一些评论:

  1. 我认为你不需要Mocks;
  2. 为了更好地了解Mocks是什么以及它们的行为方式,您应该阅读:http://easymock.org/getting-started.html
  3. “isDirCreated”是一个局部变量,在“createDir”方法之外永远不可见。如果你想让它可见,你应该在你的类中创建一个属性,然后写一个getter;
  4. 一种更简单的测试方法是(假设“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
    }  
    
  5. 希望这有帮助。