我要对 service.method()进行单元测试,该测试最后一次调用 dao.method(a,b)返回一个列表。我已经成功设置了模拟dao并注入了 service(选中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
}
}