Home > Net >  Can't use 2 Mocks from the same class with different diamond operator classes
Can't use 2 Mocks from the same class with different diamond operator classes

Time:04-21

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:

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, i.e. the variable from the mock a instead of mock b. Therefore, I get a ClassLoadException doing some work afterwards.

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? 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!

CodePudding user response:

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);
   }
}
  • Related