[英]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.