Reputation: 49
I am using the Spring Test framework along with Junit. I have a spring context file which i use for the test cases:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/restTestContext.xml",
"classpath:spring/webserviceContext.xml" })
@PrepareForTest(User.class)
public class RestTestsIT {
// This is a mock
@Autowired private AWSMailService mailService;
...
}
Within the restTestContext.xml I am creating a bean of type AWSMailService (which is actually a mock):
<bean id="mailService" name="mailService" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.acme.utils.email.AWSMailService" />
</bean>
Within the test I am trying to verify that the sendEmail() method was called on the mailService mock but I am getting a NotAMockException although calling toString() on the object tells me it is a mock:
public void testEmailSent() {
...
// Results in "Mock for AWSMailService, hashCode: 31777764"
System.out.println(mailService.toString());
// Results in NotAMockException
verify(mailService).sendEmail(any(String.class), ...);
}
Does anyone have any ideas what could be causing this?
Thanks
Upvotes: 2
Views: 2153
Reputation: 221
I had the same problem, I was using mockito 1.8.1, in version 1.9.0 the issue has been fixed.
Now Mockito's valid mock algorithm has changed and has not conflict with spring proxied beans.
Upvotes: 1
Reputation: 49
Fixed it :)
The problem was that Mockito was indeed creating a Mock but Spring was then proxying it and Mockito isn't intelligent enough to work out that the there is a proxy around the mock.
I'm now manually creating the mocks in the unit test and wiring them up:
@Mock private AWSMailService mailService;
@Autowired private UserService userService;
@Before
public void setup() {
((UserServiceImpl) userService).setMailService(mailService);
}
Upvotes: 0
Reputation: 61705
Is Spring creating a Proxy for this object, so that Mockito thinks it's not a mock, because youre getting a Proxy$34 class as an intermediate between the caller and your mock object?
Upvotes: 1