Junit Unit Test For a Method That Includes TransactionTemplate
Asked Answered
R

2

0

I have a method that includes transactionTemplate in it. My test works when I run debug mode but not when executed directly.

My test works when I run debug mode because I think transactional operation is done while working debug mode. But when I just run it works wrong. How can I overcome this problem?

This is my method:

@Override
public void saveAndUpdate(DataDictionaryDTO input) {
    try {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                DataDictionaryEntity ent = null;
                if (NullUtils.isNotNullOrZero(input.getId())) {
                    ent = dataDictionaryRepository.findById(input.getId()).orElse(null);
                }
                dataDictionaryRepository.save(dataDictionaryDTOMapper.map(input, ent));
            }
        });
    }
    catch (DataIntegrityViolationException e) {
        throw new UserFriendlyException("there.is.already.such.a.value");
    }
}
Rubricate answered 18/8, 2023 at 15:16 Comment(2)
pls show us your testBourgeon
And please explain what you mean by your test does not work.Wilbertwilborn
G
0

Try this mock code

when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
        TransactionCallbackWithoutResult transactionCallbackWithoutResult = (TransactionCallbackWithoutResult)invocation.getArguments()[0];
        transactionCallbackWithoutResult.doInTransaction(new SimpleTransactionStatus());
        return null;
    });
Guttapercha answered 24/10, 2023 at 8:58 Comment(0)
S
0

You can try this, it works on me.

doAnswer(invocation -> {
    Consumer<TransactionStatus> consumer = invocation.getArgument(0);
    consumer.accept(null);
    return null;
  }).when(transactionTemplate).executeWithoutResult(any(Consumer.class));

If you think null argument to consumer is not a good idea, you can also try this one:

doAnswer(invocation -> {
    Consumer<TransactionStatus> consumer = invocation.getArgument(0);
    consumer.accept(null);
    return null;
  }).when(transactionTemplate).executeWithoutResult(any(Consumer.class));

....

private TransactionStatus newTransactionStatus() {
  return new DefaultTransactionStatus(null, true, false, false, false, null);
}
Sort answered 29/4 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.