简体   繁体   中英

How to inject Mock after Mockito.Mock()

I've an abstract class with so many methods with business logic. While writing Junits I'm testing abstract class by creating its Mock with Calls to real methods. In my Junit, I don't want to create a concrete class to test abstract class method, because then my Junit test case will get some behavior that I don't want.

I'm using this to achieve a mock to call my abstract class. Mockito.mock(AbstractService.class,Mockito.CALLS_REAL_METHODS)

But my problem is, My abstract class has so many dependencies which are Autowired. Child classes are @component . Now if it was not an abstract class, I would've used @InjectMocks, to inject these mock dependencies. But how to add mock to this instance I crated above.

Simplifies version of code here/

abstract class AbstractService{

       @Autowired
       DependencyOne dp1;
        
       @Autowired
        private DependencyOne dp2;

     
       public void doSometingSpecial(){
          dp1.Dosomething(dp2.dosomethingElse())
         .....
         .....

     }
}

My Junit is

@ExtendWith(SpringExtension.class)
@TestInstance(Lifecycle.PER_CLASS)
class AbstractServiceTest {

        @Mock
        private DependencyOne dp1;
        
        @Mock
        private DependencyOne dp2;

        .....
         .....

        @Test
        void testDirectCall_whenSomething_thenSomerhing(){
               AbstractService service =    Mockito.mock(AbstractService.class,Mockito.CALLS_REAL_METHODS);

        //How to inject dep1 and dp2 mock to write junit for doSometingSpecial()
          }
     }

just add inject mock for parent class alone

@InjectMocks
AbstractService abstractService;

Inside Test method give,

 @Test
 void testDirectCall_whenSomething_thenSomerhing(){
 when(myAbstractClass.doSometingSpecial()).thenReturn("good");
  Assert.assertEquals("good",myAbstractClass.doSometingSpecial());
  }

No need of

AbstractService service =    Mockito.mock(AbstractService.class,Mockito.CALLS_REAL_METHODS);

in import kindly add import static org.mockito.Mockito.*;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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