本文介绍了Mockito:带有界限通配符的归类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑下面的代码:

  public class DummyClass {
public List< ;?扩展Number> dummyMethod(){
返回新的ArrayList< Integer>();


$ / code $ / pre

  public class DummyClassTest {
public void testMockitoWithGenerics(){
DummyClass dummyClass = Mockito.mock(DummyClass.class);
列表< ;?扩展Number> someList = new ArrayList< Integer>();
Mockito.when(dummyClass.dummyMethod())。thenReturn(someList); //编译器抱怨这个


编译器抱怨该行试图为 dummyMethod()存根行为。任何关于如何使用有界通配符返回类型的stubbing方法的指针?

您也可以使用非类型安全方法为此目的,

  @Test 
public void testMockitoWithGenerics()
{
DummyClass dummyClass = Mockito.mock(DummyClass.class);
列表< ;?扩展Number> someList = new ArrayList< Integer>();

Mockito.doReturn(someList).when(dummyClass).dummyMethod();

Assert.assertEquals(someList,dummyClass.dummyMethod());
}

为 Mockito的谷歌组。

尽管这比 thenAnswer 简单,但请注意它不是类型安全的。如果您担心类型安全,Millhouse的是正确的。

其他详细信息



要清楚,以下是观察到的编译器错误,

我相信编译器已经分配了第一个通配符类型在调用,然后无法确认 thenReturn 调用中的第二个通配符类型是否相同。

它看起来像 thenAnswer 不会遇到这个问题,因为它接受通配符类型,而然后返回采用一个非通配符类型,必须被捕获。从Mockito的,

  OngoingStubbing< T> thenAnswer(Answer<?> answer); 
OngoingStubbing< T>然后返回(T值);


Consider this code:

public class DummyClass {
    public List<? extends Number> dummyMethod() {
        return new ArrayList<Integer>();
    }
}
public class DummyClassTest {
    public void testMockitoWithGenerics() {
        DummyClass dummyClass = Mockito.mock(DummyClass.class);
        List<? extends Number> someList = new ArrayList<Integer>();
        Mockito.when(dummyClass.dummyMethod()).thenReturn(someList); //Compiler complains about this
    }
}

The compiler complains about the line that's trying to stub the behavior for dummyMethod(). Any pointers on how one goes about stubbing methods that return a type with bounded wild-cards?

解决方案

You can also use the non-type safe method doReturn for this purpose,

@Test
public void testMockitoWithGenerics()
{
    DummyClass dummyClass = Mockito.mock(DummyClass.class);
    List<? extends Number> someList = new ArrayList<Integer>();

    Mockito.doReturn(someList).when(dummyClass).dummyMethod();

    Assert.assertEquals(someList, dummyClass.dummyMethod());
}

as discussed on Mockito's google group.

While this is simpler than thenAnswer, again note that it is not type safe. If you're concerned about type safety, millhouse's answer is correct.

Additional Details

To be clear, here's the observed compiler error,

I believe the compiler has assigned the first wildcard type during the when call and then cannot confirm that the second wildcard type in the thenReturn call is the same.

It looks like thenAnswer doesn't run into this issue because it accepts a wildcard type while thenReturn takes a non-wildcard type, which must be captured. From Mockito's OngoingStubbing,

OngoingStubbing<T> thenAnswer(Answer<?> answer);
OngoingStubbing<T> thenReturn(T value);

这篇关于Mockito:带有界限通配符的归类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 07:02