JUnit 的 Easy mock 中的 InvocationTargetException
InvocationTargetException in Easy mock of JUnit
我在 运行宁 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
,因为 class 已经存在并以这种方式设计.通过 JUnit 执行以下行时,我得到 java.lang.reflect.InvocationTargetException
.
User resultUser = UserFinder.findUser(userFirstName, daoMock);
我是 EasyMock
的新手,我认为设置 expect
会增加 daoMock
对象的行为,但事实并非如此。请帮助我了解如何调用 dao.findUser
行,因为我无法模拟此行,因为它在应用程序文件中。对于 EasyMock
中的这种情况,我如何模拟和 运行 JUnit。谢谢。
你必须模拟这个方法
EasyMock.expect(dao.findUser(userFirstName).andReturn(user);
而不是
EasyMock.expect(daoMock.userExists(user)).andReturn(true);
我在 运行宁 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
,因为 class 已经存在并以这种方式设计.通过 JUnit 执行以下行时,我得到 java.lang.reflect.InvocationTargetException
.
User resultUser = UserFinder.findUser(userFirstName, daoMock);
我是 EasyMock
的新手,我认为设置 expect
会增加 daoMock
对象的行为,但事实并非如此。请帮助我了解如何调用 dao.findUser
行,因为我无法模拟此行,因为它在应用程序文件中。对于 EasyMock
中的这种情况,我如何模拟和 运行 JUnit。谢谢。
你必须模拟这个方法
EasyMock.expect(dao.findUser(userFirstName).andReturn(user);
而不是
EasyMock.expect(daoMock.userExists(user)).andReturn(true);