Why is Mockito not starting ()?
I need to test the service class, but when I try to mock the dao class it won't start, so it can't use ThenReturn ().
I think the problem is that I am using the interface for my Dao and @Autowired in the service class (Spring MVC 3.1):
Interface:
public interface TestDao {
int createObject(Test test) throws NamingException;
}
Implementation:
@Repository
public class TestDaoImpl implements TestDao {
@Override
public int createObject(Test test) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new InsertNewTest(test), keyHolder);
return ((java.math.BigDecimal)keyHolder.getKey()).intValue();
}
}
Service:
public class RegTest {
@Autowired
TestDao testDao;
public int regTest(int .....) {
.
.
int cabotageId = testDao.createObject(test);
}
}
In a test I have:
@RunWith(MockitoJUnitRunner.class)
public class TestRegService {
@InjectMocks
private RegTest regTest = new RegTest();
@Mock
TestDao testDao;
@Test()
public void test() {
.
when(testDao.createObject(null)).thenReturn(100);
.
}
testDao.createObject (null) returns 0 (due to layout) not 100 as I am trying to achieve.
Can anyone help please?
Problem solved!
It was the passing test object createObject () that didn't match. Using
testDao.createObject(any(Test.class))
did the trick!
source to share
If your test actually passes in a createObject value then when(testDao.createObject(null)
... will never be matched. Instead of mapping null, you can map any instance Test
to testDao.createObject(any(Test.class))
...
Also when you tried adding new Test()
as an argument to match, it will literally try to match that exact instance Test
, but presumably your real code will be new. Therefore, using Matchers.any(Test.class)
as a parameter for matching is the way to go.
source to share
Mockito's injection engine is unaware of Spring @ Automated or CDI @ Introductory annotations. It is just trying to find the best candidate given the type and name of the layout, and it can search for private fields as well. See Javadoc @InjectMocks: http://docs.mockito.googlecode.com/hg/1.9.0/org/mockito/InjectMocks.html
The semantics you are using are correct, although if you are having problems, I prefer to look for incorrect interactions or incorrect arguments.
Are you sure the variable test
in is regTest.regTest(int...)
actually null
passed in testDao.createObject(test)
?
source to share
I don't know if this is the example in the example, but you have a RegTest.regTest()
call createTest()
, not createObject()
. Otherwise, I don't think @Autowired has anything to do with it, as the test itself doesn't work in a container with Spring. If this is not a typo, but createTest
in fact is a real and different method from createObject
, then the default behavior for a mocked object in Mockito is to return the correct numbered number for numeric return types. >
source to share