0

I have Autowired a field in Test class

@Autowired
private AbcDAO abcDAO;

and used it like this

doThrow(new RuntimeException()).when(abcDAO).methodName(xyz);

or

doNothing().when(abcDAO).methodName(xyz);

I have mocked this DAO class in spring files like this

<bean id="abcDAO" class="org.mockito.Mockito" factory-method="mock"  >
        <constructor-arg value="a.b.c.abcDAO" />
    </bean>

I get NotAMockException Argument passed to when() is not a mock.

When I use `@Mock annotation like this

@Mock
    private AbcDAO abcDAO;

in the test class directly (instead of @Autowiring it and mocking in spring), it works fine.

Why does it happen?

Edit:

Ok, so let me tell you the reason of doing so.

We have a service X and I want to write junits for the APIs of 'X'. Junits are written in such a way that I create a client and call these APIs. I am not calling the methods directly where @Mock and @Inject mocks can be used.

I am not sure if it is clear but this is the use case when mocking in spring file is required.

instanceOfObject
  • 2,936
  • 5
  • 49
  • 85

1 Answers1

1

See this answer: why-does-mockito-think-this-autowired-bean-is-null

Mockito.mock does not take a String but Class<?>. As it stated in the other question. Is there REALLY a good reason to attempt to create the mock in a Spring context?

Community
  • 1
  • 1
John B
  • 32,493
  • 6
  • 77
  • 98