1 year ago

#361649

test-img

N.A

Mockito spy on class variable

I have a weird scenario where I am creating an empty List as a class variable, then I have a scheduler that updates that list. In my tests, I want to be able to see whether or not that List was updated. But from my understanding this isn't possible.

public class Scheduler {

    private List<String> list = new ArrayList<>(); //want to track this variable in my test
    private final ListAccessor listAccessor;

    Scheduler(final ListAccessor listAccessor) {
        this.listAccessor = listAccessor

        scheduler.scheduleAtFixedRate(this::updateString, 1, TimeUnit.HOURS);
    }

    public void updateString() {
        try {
            list = listAccessor.getUpdatedList(someParam); //want to see the value in my test after it gets updated
            log.info("Successfully updated list");
        } catch (final Exception e) {
            log.error("Failed to get updated list", e);
        }
    }

}
    @Test
    public void testCheckForUpdate_listAccessorThrewError() {
        Mockito.when(listAccessor.getUpdatedList(someParam)).thenThrow(Exception.class);
        // assert that the list in my class wasn't updated
    }

Is something like this possible? I don't want to throw any errors when the list fails to update, so it seems the only way is to spy on the list somehow. Any help appreciated

java

junit

mockito

powermockito

0 Answers

Your Answer

Accepted video resources