首页 > 解决方案 > 带有任何参数的 Mockito when() 无法按预期工作

问题描述

我想对service.method()进行单元测试,它最后调用dao.method (a, b)来返回一个列表。我已成功设置模拟 dao 并注入服务 (checked service.dao == dao)

然后我尝试

Mockito.when(dao.method(Mockito.any(A.class), Mockito.any(B.class)))
    .thenReturn(myList);

List aList = dao.method(new A(), new B());

List bList = service.method();

我按预期得到aList == myList,但是bList!= myList并且始终是一个空列表(myList不为空)。

这种行为是预期的吗?如果没有,我哪里做错了?

服务等级

@Service
public class Service{
    @Autowired
    Dao dao;

    @Transactional
    public List method() {
        ...
        A a = ...;
        B b = ...;
        return dao.method(a, b);
    }
}

单元测试类

@RunWith(SpringJUnit4ClassRunner.class)
public class ServiceTest {
    @Autowired
    @InjectMocks
    Service service;

    @Mock
    Dao dao;

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

    @Test
    public void testMethod() throws Exception {
        List<A> myList = Lists.newArrayList();
        myList.add(Mockito.mock(A.class));
        Mockito.when(dao.method(Mockito.any(A.class), Mockito.any(B.class))).thenReturn(myList);
        List<A> aList = dao.method(new A(), new B());
        List<A> bList  = service.method();
        List<A> cList = service.method();
        System.out.println("dao=" + (dao == service.dao)); // true
        System.out.println("aList=" + (aList == myList)); // true
        System.out.println("bList=" + (bList == myList)); // false
        System.out.println("cList=" + (bList == cList)); // false
    }
}

标签: unit-testingmockito

解决方案


推荐阅读