当前位置: 首页 > 知识库问答 >
问题:

模拟试验错误。需要但未调用的异常

吕鹏
2023-03-14

我是摩基托的新手,不明白这是什么问题。而且你能不能说我,如何做Mockito单位正确,因为我真的不能理解他们!更新的错误和测试类

我有下一个例外:

下面是我的DAO类:

  public class MySqlUsersDao implements UsersDao {
        /** Logger. */
        private static final Logger LOG = Logger.getLogger(MySqlUsersDao.class);

        /*
         * (non-Javadoc)
         * 
         * @see
         * ua.khpi.shapoval.autostation.dao.UsersDao#getUserIdByLogin(java.lang.
         * String)
         */
        @Override
        public int getUserIdByLogin(String login) {
            Connection connection = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            try {
                connection = DbConnector.getConnection();
                stmt = connection.prepareStatement(Constants.UsersDao.SELECT_USER_ID_BY_LOGIN);
                stmt.setString(1, login);
                rs = stmt.executeQuery();
                while (rs.next()) {
                    return rs.getInt(1);
                }

            } catch (SQLException e) {
                LOG.error(e.getMessage());
                return 0;
            } finally {
                DbConnector.close(connection, stmt, rs);
            }
            return 0;
        }


    }
   public class MySqlUsersService implements UsersService {

    private UsersDao usersDao;
    private TransactionManager transactionManager;

    public MySqlUsersService(UsersDao usersDao, TransactionManager transactionManager) {
        this.usersDao = usersDao;
        this.transactionManager = transactionManager;
    }

    @Override
    public int getUserIdByLogin(String login) {
        return this.transactionManager.execute(() -> this.usersDao.getUserIdByLogin(login));
    }

}
public class UsersServiceTest {
    @InjectMocks
    private MySqlUsersService mockedUsersService;

    @Mock
    private static TransactionManager transactionManager;

    @Mock
    private static UsersDao usersDao;

    @Mock
    private static Users user1;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);

    }

    @Test public void testGetUserByLogin() {
        when(usersDao.getUserByLogin("user1")).thenReturn(user1);
        assertEquals(user1, mockedUsersService.getUserIdByLogin("user1")); 
        verify(transactionManager).execute(()->usersDao.getUserIdByLogin("user1"));

    }
}

共有1个答案

戚侯林
2023-03-14

如果我能正确理解你的问题

verify(transactionManager).execute(()->usersDao.getUserByLogin("user1"));

它的发生是因为函数是通过引用进行比较的,并且在测试中通过的函数和在实现中通过的函数是不同的实例。

我建议您使用argumentcaptor捕获函数。调用捕获的函数并验证它执行了您期望的操作。

 类似资料: