Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

junit - 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()
          }
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.*;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...