简体   繁体   中英

how to verify void method in junit

Im pretty new with the tests. Just because it looks like Ive got issues with mock I decided to ask you guys for help. Can you tell how correctly tests for those methods should looks like, please? This is what ive got:

class for test:

public class EnhancedJwtCache extends TimerTask { ConcurrentHashMap<String, EJwt> cache = new ConcurrentHashMap<>();

public void init() {
    
    new Timer().scheduleAtFixedRate(this, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));
}

@Override
public void run() {
    log.debug("Checking enhanced token cache for expired entries.");

    // Remove any eJWT's from the cache that have expired.
    Iterator<String> iterator = cache.keySet().iterator();
    
    while (iterator.hasNext()) {
        String key = iterator.next();
        if (cache.get(key).isExpired()) {
            log.debug("Removing expired token from cache for user {}", cache.get(key).getUsername());
            iterator.remove();
        }
    }
}

}

and my test so far which returns me error because its not mock:

class EnhancedJwtCacheTest {

    ConcurrentHashMap<String, EJwtAuthenticationToken.EJwt> cache;

    @Mock
    EnhancedJwtCache underTest;

    EJwtAuthenticationToken.EJwt ejwt;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void runTest(){

        List<String> roles= Arrays.asList("Roles1");
        ejwt = new EJwtAuthenticationToken.EJwt(
                "encodedJwt",
                Instant.now().plus(10, ChronoUnit.DAYS),
                "name",
                "username",
                roles
        );

        cache = new ConcurrentHashMap<>();
        cache.put("cache", ejwt);

        verify(underTest,times(1)).run();

You don't want to mock the class that you're testing in the test. Then you would be testing the mock, not the class.

To test a void method, it needs to have some observable side-effect that you can verify in the test. In this case, you'd want the test to add a mix of expired and non-expired entries to the cache, then call run , then check the list of cache entries again to be sure the expired ones are absent and the non-expired ones are present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM