简体   繁体   English

JUnit简易模拟中的InvocationTargetException

[英]InvocationTargetException in Easy mock of JUnit

I am facing an issue while running JUnit using EasyMock . 使用EasyMock运行JUnit时遇到问题。 Please find below the source files - UserTest.java (JUnit file) and UserFinder.java (Application file to be unit tested). 请在下面找到源文件UserTest.java (JUnit文件)和UserFinder.java (要进行单元测试的应用程序文件)。

UserTest.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 UserFinder.java

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

In JUnit, I have created a mock object daoMock and added below expect behavior. 在JUnit中,我创建了一个模拟对象daoMock并添加了以下expect行为。

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

In the below line of UserFinder.java , I need to pass daoMock as the class is already existing and designed in that way. UserFinder.java的 daoMock行中,我需要传递daoMock因为该类已经存在并且已经通过这种方式进行了设计。 When the below line is executed through JUnit, I am getting java.lang.reflect.InvocationTargetException . 通过JUnit执行下面的行时,我正在获取java.lang.reflect.InvocationTargetException

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

I am new to EasyMock and I thought setting expect adds to the behavior of the daoMock object but it is not. 我是EasyMock新手,我认为设置expect会增加daoMock对象的行为,但事实并非如此。 Please help me about how to call dao.findUser line as I cannot mock this line since it is in application file. 请帮助我有关如何调用dao.findUser行,因为该行位于应用程序文件中,因此我无法模拟此行。 How can I mock and run the JUnit for this case in EasyMock . EasyMock如何为这种情况模拟并运行JUnit。 Thanks. 谢谢。

You must mock the method 您必须模拟该方法

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

instead of 代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM