I want to unit test service.method(), which in its last calls dao.method (a, b) to return a list. I have successfully setup mock dao and injected into service (checked service.dao == dao).
Then I try
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();
I get aList == myList as expected, but bList!= myList and always is an empty list (myList
is not empty).
Is this behavior expected? If not, where I do wrong?
Service Class
@Service
public class Service{
@Autowired
Dao dao;
@Transactional
public List method() {
...
A a = ...;
B b = ...;
return dao.method(a, b);
}
}
Unit Test Class
@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
}
}