I am trying to Mock this following code with transaction manager. Receiving error below. How can I resolve this?
Code:
DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition(); PlatformTransactionManager transactionManager = new DataSourceTransactionManager(namedParameterJdbcTemplate.getJdbcTemplate().getDataSource()); TransactionStatus status = transactionManager.getTransaction(paramTransactionDefinition);
Test:
@Mock private JdbcTemplate jdbcTemplate; @Mock private PlatformTransactionManager platformTransactionManager; @Mock private DataSource dataSource; @Mock private TransactionStatus transactionStatus; given(namedParameterJdbcTemplate.getJdbcTemplate()).willAnswer(a -> jdbcTemplate); given(namedParameterJdbcTemplate.getJdbcTemplate().getDataSource()).willAnswer(a -> dataSource); platformTransactionManager = Mockito.mock(DataSourceTransactionManager.class, withSettings().useConstructor(dataSource)); given(platformTransactionManager.getTransaction(any())).willAnswer(a -> transactionStatus);
Error:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 0 matchers expected, 1 recorded: -> at given(platformTransactionManager.getTransaction(any())).willAnswer(a -> transactionStatus); This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String");
trying to use this resource: https://stackoverflow.com/a/60429929/15435022
Advertisement
Answer
This will work:
@Mock private JdbcTemplate jdbcTemplate; @Mock private PlatformTransactionManager platformTransactionManager; @Mock private DataSource dataSource; @Mock private TransactionStatus transactionStatus; given(namedParameterJdbcTemplate.getJdbcTemplate()).willAnswer(a -> jdbcTemplate); given(namedParameterJdbcTemplate.getJdbcTemplate().getDataSource()).willAnswer(a -> dataSource); MockedConstruction<DataSourceTransactionManager> mocked = Mockito.mockConstruction(DataSourceTransactionManager.class, (mock, context) -> { when(mock.getTransaction(any())).thenReturn(null); }); given(platformTransactionManager.getTransaction(new DefaultTransactionDefinition())).willAnswer(a -> transactionStatus); mocked.close();
Resource: https://rieckpil.de/mock-java-constructors-and-their-object-creation-with-mockito/