I have a service that extends abstract class in my spring-boot project
public class TestService extends AbstractTest1Service {
// some methods
}
public abstract class AbstractTest1Service extends AbstractTest2Service {
public String doSomething() {
return writeText();
}
}
public abstract class AbstractTest2Service {
String writeText() {
return "text";
}
}
Is there any way to mock writeText()
method when i want to test TestService
:
Your TestService
class:
public class TestService extends AbstractTest1Service {
AbstractTest2Service abstractTest2Service;
public String doSomething() {
abstractTest2Service.writeText();
System.out.println("Passed!");
return "All Checked";
}
}
Your TestServiceTest
class should be like:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TestServiceTest {
@InjectMocks
TestService testService;
@Mock
AbstractTest2Service abstractTest2Service;
@Test
public void testService(){
Assert.assertEquals("All Checked",testService.doSomething());
}
}
Note: Do not use
@Spy
instead of@Mock
, Spy will try to check the actual implementation of the abstract class methods which is not there , so your test will be ignored. Just use@Mock
.
Using @Spy will give error:
Cannot instantiate a
@Spy
for 'abstractTest2Service
' field. You haven't provided the instance for spying at field declaration so I tried to construct the instance. However, I failed because: the type 'AbstractTest2Service
is an abstract class.
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.