1

我似乎无法弄清楚我在这里做错了什么:

这是我正在测试的方法:

public List<Mo> filterDuplicatesByName(List<Mo> dbMos) {
    List<String> names = Lists.newArrayList();
    for(Mo mo : dbMos) {
        try {
            String name = mo.getName();
            if(names.contains(name)) {
                dbMos.remove(mo);
            } else {
                names.add(name);
            }
        } catch (DataLayerException ex) {
            dbMos.remove(mo);
        }
    }
    return dbMos;
}

这是我的测试课:

package com.rondavu.wt.service.recommendations;

import com.google.common.collect.Lists;
import com.rondavu.data.api.Mo;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class RecommendationsUtilsTest  {

    Mockery context = new Mockery();

    RecommendationsUtils recommendationsUtils = new RecommendationsUtils();

    final Mo mo = context.mock(Mo.class);

    @Test
    public void testFilterDuplicatesByName_oneMo() throws DataLayerException {
        List<Mo> input = Lists.newArrayList(mo);
        List<Mo> expected = Lists.newArrayList(mo);

        context.checking(new Expectations() {{
            oneOf (mo).getName(); will(returnValue("Mo 1"));
        }});

        List<Mo> actual = recommendationsUtils.filterDuplicatesByName(input);

        context.assertIsSatisfied();

        assertEquals(expected, actual);
    }
}

当我运行测试时,我得到这个输出:

unexpected invocation: mo.getName()
no expectations specified: did you...
 - forget to start an expectation with a cardinality clause?
 - call a mocked method to specify the parameter of an expectation?
what happened before this: nothing!
    [stack trace]

我对 jMock 还是很陌生,一般来说 Java 不是我最强大的语言,但我认为我oneOf (mo).getName()会让它期待这种调用。我在这里做错了什么?

4

1 回答 1

3

虽然目前尚不清楚为什么,但与您定义期望的那个相比,Mockery 似乎正在检查一个不同的 mo 实例。尝试context.mock(Mo.class)在与测试用例相同的本地范围内插入(或在 @Before 方法中),看看是否能解决问题。

于 2013-03-20T23:29:13.107 回答