简体   繁体   English

不能使用来自同一个 class 的 2 个具有不同钻石运算符类的模拟

[英]Can't use 2 Mocks from the same class with different diamond operator classes

I have the following classes structure.我有以下类结构。

public interface Foo<T extends Bar>{
   Optional<T> find();
}

public class A extends Bar{}

public class B extends Bar{}

@Service
@RequiredArgsConstructor
public class C{
  Foo<A> a;
  Foo<B> b;

  B bInstance = b.find();
}

public class CTest{
   @Mock
   Foo<A> a;

   @Mock
   Foo<B> b;

   @InjectMocks
   C c;

   @Test
   public void testSomething(){
      when(a.someMethod()).thenReturn(someVariable);
      when(b.someMethod()).thenReturn(someOtherVariable);
   }
}

Then maybe I have some code in class C like:那么也许我在 class C 中有一些代码,例如:

B bInstance = b.find();

And the problem here is that when find is called, it returns a new instance from class A instead of B, ie the variable from the mock a instead of mock b.而这里的问题是,当调用 find 时,它从 class A 而不是 B 返回一个新实例,即来自 mock a 而不是 mock b 的变量。 Therefore, I get a ClassLoadException doing some work afterwards.因此,之后我得到一个 ClassLoadException 做一些工作。

Is this supposed to work as expected or is it a problem caused by mocking 2 variables from the same class (Foo) of 2 different diamond operator classes (how is this called?) (A and B) that Mockito can't interprete?这应该按预期工作还是由 mocking 来自 2 个不同钻石运算符类的相同 class (Foo) 的 2 个变量引起的问题(这怎么称呼?)(A 和 B)Mockito 无法解释? Am I missing something else here?我在这里还缺少其他东西吗? This may not be enough information to do the follow-up but hopefully there is some concept misunderstanding that I have and can be fixed easily.这可能没有足够的信息来进行后续操作,但希望我有一些概念上的误解并且可以轻松解决。

Thanks in advance!提前致谢!

I would create test subject myself then然后我会自己创建测试对象

public class CTest{
   @Mock
   Foo<A> a;

   @Mock
   Foo<B> b;

// @InjectMocks  since it is not working for you, lets skip it
   C service;

   @Before
   public void setup(){
       service=new C(a,b);
   }

   @Test
   public void testSomething(){
      when(a.someMethod()).thenReturn(someVariable);
      when(b.someMethod()).thenReturn(someOtherVariable);
   }
}

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

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