Easy mock of JUnit中的InvocationTargetException

时间:2015-05-21 10:31:00

标签: java unit-testing junit easymock

使用JUnit运行EasyMock时遇到问题。请在下面找到源文件 - UserTest.java(JUnit文件)和UserFinder.java(要进行单元测试的应用程序文件)。

UserTest.java

Class UserTest
{
  ...
  @Test
  public void testFindUserFunction() throws Exception {


    DAO daoMock = EasyMock.createMock(DAO.class);       
    User user = new User("john", "stephen", "city street", "bangalore");
    EasyMock.expect(daoMock.userExists(user).andReturn(true);
    EasyMock.replay(daoMock);       
    String userFirstName = user.getFirstName();
    User resultUser = UserFinder.findUser(userFirstName, daoMock);      
    PowerMock.verify(daoMock);      
    Assert.assertEquals(user, resultUser);
  }
}

UserFinder.java

Class UserFinder {
...
...
public User findUser(String userFirstName, DAO dao)
{
return dao.findUser(userFirstName);
}
...
...
}

在JUnit中,我创建了一个模拟对象daoMock并添加了expect行为。

EasyMock.expect(daoMock.userExists(user).andReturn(true);

UserFinder.java 的下一行中,我需要传递daoMock,因为该类已经存在并以此方式设计。当通过JUnit执行以下行时,我得到java.lang.reflect.InvocationTargetException

User resultUser = UserFinder.findUser(userFirstName, daoMock);

我是EasyMock的新手,我认为设置expect会增加daoMock对象的行为,但事实并非如此。请帮助我如何调用dao.findUser行,因为我无法模拟这一行,因为它在应用程序文件中。如何在EasyMock中为此案例模拟和运行JUnit。感谢。

1 个答案:

答案 0 :(得分:0)

你必须嘲笑方法

<cfset result= REfindNoCase('-[A-Z]{3}$', variables.textBeforeFirstName, 1, "true")>


<cfoutput>
    #result.pos[1]#
</cfoutput>

而不是

EasyMock.expect(dao.findUser(userFirstName).andReturn(user);