unit-testing - 带有任何参数的 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
}
}
解决方案
推荐阅读
- python - Pytest + Coverage 生成错误的覆盖率
- java - 无法在 WebSphere Application Server 8.5.5 中运行 JSF 1.1 应用程序
- firebase - 项目 A 中的 Google App Engine 无法使用项目 B 中的 Firebase 云消息传递
- typescript - 如何更新 Firestore 数据库中的大量文档?
- machine-learning - 如何在这个 grad cam 代码中使用现有的 ckpt 文件?
- python - 根据条件重新运行某些成功的气流任务
- netsuite - 使用客户外部 ID 创建联系人
- python - 线程中的生成器
- java - Java 中的 LinkedList 等价于 C++ 代码
- php - 如何在前端使用 Select 通过 ACF 字段运行 Wordpress 查询