1

我有一个像下面这样的类:

class A
{
   public method doSomething()
   {
      //....

      DAO dataAccessor = new DAO();
      List<Object> result1 = dataAccessor.getData(dataAccessor.getSql1());
      List<Object> result2 = dataAccessor.getData(dataAccessor.getSql2());

      //.. do some stuff with the results

}

现在,我使用 jMockit 通过模拟类来测试上述功能DAO

这就是我的测试类的样子:

class A_Test
{
    private A myAClass;

    @Mocked DAO mockedDAO;

    List<Object> resultToSql1, resultToSql2;

    // ... Some initializations...

    @Test
    public void testDoSomething()
    {
        new NonStrictExpectations()
        {
                mockedDAO.getSql1(); result = "SQL1";
                mockedDAO.getData(withEqual("SQL1")); result = resultToSql1;

                mockedDAO.getSql2(); result = "SQL2";
                mockedDAO.getData(withEqual("SQL2")); result = resultToSql2;
        };

        myAClass.doSomething(); 
    }
}

现在,似乎关于getData()掩盖第一个期望的第二个期望,即模拟对象的行为就好像我从未在期望中声明第一行(处理的那些sql1):

第一次调用getData()返回空集合,而不是我初始化的值resultToSql1。第二次调用resultToSql2按预期返回。

如果我评论以下行:

mockedDAO.getData(withEqual("SQL2")); result = resultToSql2;

第一个调用返回我定义的 - resultToSql1,第二个返回空集合。这是有道理的。

那么,我做错了什么??如何getData()根据调用的参数定义两个不同的返回值?

任何帮助,将不胜感激。

谢谢!

4

1 回答 1

3

So, After digging more deeply inside the manual, I found that:

...But what if a test needs to decide the result of a recorded invocation based on the arguments it will receive at replay time? We can do it through a mockit.Delegate instance ...

So, in order to solve the above problem, the expectations block should look like this:

    new NonStrictExpectations()
    {
            mockedDAO.getSql1(); result = "SQL1";
            mockedDAO.getSql2(); result = "SQL2";

            mockedDAO.getData(anyString);
            result = new mockit.Delegate()
            {
                List<Object> getData(String sql)
                {
                    if (sql.equals("SQL1"))
                        return resultToSql1;
                    if (sql.equals("SQL2"))
                        return resultToSql2;
                    return null;
                }
            }
    };
于 2011-06-01T18:08:43.380 回答