gpt4 book ai didi

mockito - 如何使用 Mockito 测试 Java 8 Stream 是否具有预期值?

转载 作者:行者123 更新时间:2023-12-04 01:23:51 33 4
gpt4 key购买 nike

我想测试的交互之一是类 Foo应该通过 Stream<Changes>FooListener.someChangesHappened .是否有 Mockito 成语来验证流是否包含预期的对象?

最佳答案

假设您只是验证模拟实现的参数,而实际上并没有使用它,这里是一个自定义的 Hamcrest Matcher这将完成工作。当您需要阅读 Stream 时,它会变得毛茸茸的不止一次,因为 Stream s 不是为此而构建的。您会注意到该解决方案甚至需要保护自己免受 JUnit 调用 matches 的影响。不止一次。

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class Foo {

@Mock
FooListener fooListener;

@Before
public void happen() {
fooListener.someChangesHappened(Stream.of(Changes.ONE, Changes.TWO, Changes.THREE));
}

@Test
public void contains() {
verify(fooListener).someChangesHappened(argThat(streamThat(hasItem(Changes.TWO))));
}

@Test
public void doesNotContain() {
verify(fooListener).someChangesHappened(argThat(streamThat(not(hasItem(Changes.FOUR)))));
}

private static <T> Matcher<Stream<T>> streamThat(Matcher<Iterable<? super T>> toMatch) {
return new IterableStream<>(toMatch);
}

private interface FooListener {
void someChangesHappened(Stream<Changes> stream);
}

private enum Changes {
ONE, TWO, THREE, FOUR
}

private static class IterableStream<T> extends TypeSafeMatcher<Stream<T>> {

Matcher<Iterable<? super T>> toMatch;
List<T> input = null;

public IterableStream(Matcher<Iterable<? super T>> toMatch) {
this.toMatch = toMatch;
}

@Override
protected synchronized boolean matchesSafely(Stream<T> item) {
// This is to protect against JUnit calling this more than once
input = input == null ? item.collect(Collectors.toList()) : input;
return toMatch.matches(input);
}

@Override
public void describeTo(Description description) {
description.appendText("stream that represents ");
toMatch.describeTo(description);
}
}
}

关于mockito - 如何使用 Mockito 测试 Java 8 Stream 是否具有预期值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37089044/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com