简体   繁体   English

如何验证 junit 中的 void 方法

[英]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: class 用于测试:

public class EnhancedJwtCache extends TimerTask { ConcurrentHashMap<String, EJwt> cache = new ConcurrentHashMap<>();公共 class EnhancedJwtCache 扩展 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.您不想模拟您在测试中测试的 class。 Then you would be testing the mock, not the class.然后您将测试模拟,而不是 class。

To test a void method, it needs to have some observable side-effect that you can verify in the test.要测试void方法,它需要有一些可以在测试中验证的可观察到的副作用。 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.在这种情况下,您希望测试将过期和未过期条目的混合添加到缓存中,然后调用run ,然后再次检查缓存条目列表以确保过期条目不存在且未过期有的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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