JUnit 测试返回 Flux<String 的方法>

JUnit testing a method that returns Flux<String>

提问人:unknown1101 提问时间:11/16/2023 最后编辑:Progmanunknown1101 更新时间:11/16/2023 访问量:63

问:

下面正在测试的服务层中的方法...:

@Service 
public class Service{

public Flux<String> methodBeingTested ()  {

Flux<String> fluxOfTypeString = Flux.just("test");

return fluxOfTypeString;
}
}

JUnit 测试:

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

@InjectMocks
Service service;

@Mock
Utility Util;     
      
 @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

   @Test
    public void test() {

        Flux<String> fluxOfTypeString = Flux.just("test"); 

       when(service.methodToTest()).thenReturn(fluxOfTypeString);
}

在调试模式下,我收到以下错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
FluxJust cannot be returned by toString()
toString() should return String

当不在调试模式下时,我收到以下错误:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.

关于可能的解决方法是什么的任何想法?任何帮助将不胜感激。

java mockito flux

评论

0赞 Georgii Lvov 11/16/2023
请添加所有测试类以查看模拟是如何配置的
0赞 unknown1101 11/16/2023
我已经添加了所有测试类。谢谢
1赞 Georgii Lvov 11/16/2023
好的,你有,因为不是模拟,而是测试下的类when(service.methodToTest()).thenReturn(fluxOfTypeString);service
0赞 unknown1101 11/16/2023
好的,那么如何测试该方法呢?

答:

1赞 Dave G 11/16/2023 #1

Mockito正在为您提供问题所在。

在没有任何其他证据的情况下,您似乎试图嘲笑真实物体。

如果你的意图是覆盖和模拟某个特定方法,你可能需要在与该签名匹配的接口上创建模拟,或者在该对象上创建一个。spy

第二部分是它在说什么。when() requires an argument which has to be a method call on a mock

1赞 Georgii Lvov 11/16/2023 #2

你根本不需要测试,因为没有第三方类(比如,你在你的 中嘲笑 )被调用:MockitomethodToTest()UtilityServiceTest

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

class MyTest {

    private Service service = new Service();

    @Test
    void name() {    
        Flux<String> actual = service.methodToTest();

        StepVerifier.create(actual)
                .expectNext("test")
                .verifyComplete();
    }
}

有关测试反应式流的详细信息,请参阅本文:https://www.baeldung.com/reactive-streams-step-verifier-test-publisher