【问题标题】:reason: no instance(s) of type variable(s) T exist so that void conforms to using mockito原因:不存在类型变量 T 的实例,因此 void 符合使用 mockito
【发布时间】:2020-07-13 14:03:30
【问题描述】:

我想在运行 void 方法时抛出异常

when(booking.validate(any())).thenThrow(BookingException.builder().build());

但我有一个编译错误:

Required type: T
Provided: void
reason: no instance(s) of type variable(s) T exist so that void conforms to T

【问题讨论】:

    标签: java spring spring-boot junit mockito


    【解决方案1】:

    只是补充@Shane 的评论,这是一个救命稻草,但不是很清楚。

    如何从存储库方法中抛出 PersistenceException 的示例:

    doThrow(new PersistenceException())
                .when(outboxRepository)
                .delete(isA(WorkersEphemeralOutboxEntry.class));
    

    当您有重载方法并且编译器无法确定使用 any() 调用哪个方法时,我发现这特别有用,并且 any(Class.class) 会给您带来编译错误。

    【讨论】:

      【解决方案2】:

      我找到了正确的语法。

      Service mockedService = new DefaultServie();
      doNothing().when(mockedService).sendReportingLogs(null);
      

      希望这能回答问题

      【讨论】:

      • 这把我绊倒了,这有帮助。谢谢。
      • brh,这应该只是在文档中,而不是他们现在拥有的
      【解决方案3】:
      /**
       * Use <code>doThrow()</code> when you want to stub the void method with an exception.
       * <p>
       * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
       * does not like void methods inside brackets...
       * <p>
       * Example:
       *
       * <pre class="code"><code class="java">
       *   doThrow(new RuntimeException()).when(mock).someVoidMethod();
       * </code></pre>
       *
       * @param toBeThrown to be thrown when the stubbed method is called
       * @return stubber - to select a method for stubbing
       */
      @CheckReturnValue
      public static Stubber doThrow(Throwable... toBeThrown) {
          return MOCKITO_CORE.stubber().doThrow(toBeThrown);
      }
      

      【讨论】:

      • 虽然 doThrow 是处理问题的校正函数,但也请提供一些代码来展示如何使用它,以便您提供问题的具体答案。
      【解决方案4】:

      对于 void 方法,我认为你需要使用doThrow 语法。

      所以你的情况是:

      doThrow(BookingException.builder().build())
            .when(booking)
            .validate(any());
      

      我希望这会有所帮助。

      【讨论】:

      • 上帝想象一下,如果这个 mockito 错误只是提供了一个提示,那么可以节省多少人!我越来越讨厌java了……
      猜你喜欢
      • 2019-12-16
      • 2017-04-22
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 2018-07-31
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多