Reputation: 1426
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()
}
}
Upvotes: 1
Views: 1298
Reputation: 368
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.*;
Upvotes: 0