简体   繁体   English

Generics 和 mockito 中的 ArgumentCaptor

[英]Generics and ArgumentCaptor in mockito

in mockito's verify i want to capture an argument of type Consumer<String> .在 mockito 的验证中,我想捕获类型为Consumer<String>的参数。 How should i write the line to avoid type erasure?我应该如何写行以避免类型擦除?

I'm reached the this point and it doesn't compile我已经达到了这一点,但无法编译

ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.<Consumer<String>, Consumer<String>>forClass(Consumer<String>.class);

how can i do it?我该怎么做?

As stated in the documentation of ArgumentCaptor although this class is generic, it doesn't perform any validation:正如ArgumentCaptor的文档中所述,尽管此 class 是通用的,但它不执行任何验证:

This utility class don't do any type checks , the generic signatures are only there to avoid casting in your code.这个实用程序 class不做任何类型检查,通用签名只是为了避免在您的代码中强制转换。

Hence, if you make use of row types it wouldn't be less type-safe, but there's a drawback - the compiler will issue a warning.因此,如果您使用行类型,它的类型安全性不会降低,但有一个缺点——编译器会发出警告。

@SuppressWarnings("unchecked")
ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.forClass(Consumer.class);

There's a cleaner option which also mentioned in the documentation linked above, namely to declare the captor as a field and annotate it with @Captor .上面链接的文档中也提到了一个更简洁的选项,即将 captor 声明为一个字段并用@Captor对其进行注释。

@Captor
ArgumentCaptor<Consumer<String>> captor;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM