Daniel Hiller

Geek, programmer, father
I'm a software engineer with more than 20 years of work experience.
I transform ☕ into useful stuff for others.

Git aliases, the easy way
All posts
Run multiple Intellij version installations on linux

Don't forget that thenThrow returns an OngoingStubbing instance *sigh*

2016-05-12

java mock spring retry 

I’ve often had the problem that when checking for a working retry mechanism (btw. spring-retry works great) I wanted to first throw an exception and then return a value or whatever else is necessary.

Easy peasy, I thought. Just create an Answer and hold state within the answer i.e. a boolean that gets set to true after it has been called:

@Test
public void queryIsRetried() {
    final Answer objectAnswer = new Answer() {

        boolean called;

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            if(called) {
                return null;
            }

            called = true;
            throw new RuntimeException();
        }
    };
    when(lexdbJdbcTemplate.query(anyString(), any(RowMapper.class)))
            .then(objectAnswer);
    underTest.query("SELECT 1;");
}

And of course there is a much easier way, stupid me:

@Test
public void queryIsRetried() {
    when(lexdbJdbcTemplate.query(anyString(), any(RowMapper.class)))
            .thenThrow(new RuntimeException())
            .thenReturn(null);
    underTest.query("SELECT 1;");
}
Related posts:

Git aliases, the easy way
All posts
Run multiple Intellij version installations on linux

Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Last update on 2024-09-24. Built by dhiller using Atom (editor), Jekyll (site builder), OneDark vivid (syntax highlighting theme), Webjeda (related posts), Disqus (discussions), Github Pages (hosting), Cloudflare (DNS).