簡體   English   中英

如何驗證 junit 中的 void 方法

[英]how to verify void method in junit

我對測試很陌生。 只是因為看起來我在模擬方面遇到了問題,所以我決定向你們尋求幫助。 你能說出這些方法的正確測試應該是什么樣子嗎? 這就是我得到的:

class 用於測試:

公共 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();
        }
    }
}

}

到目前為止,我的測試返回了錯誤,因為它不是模擬的:

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();

您不想模擬您在測試中測試的 class。 然后您將測試模擬,而不是 class。

要測試void方法,它需要有一些可以在測試中驗證的可觀察到的副作用。 在這種情況下,您希望測試將過期和未過期條目的混合添加到緩存中,然后調用run ,然后再次檢查緩存條目列表以確保過期條目不存在且未過期有的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM