我有一个在我的 spring-boot 项目中扩展抽象类的服务
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";
}
}
当我想测试 TestService
时,有什么方法可以模拟 writeText()
方法:
最佳答案
您的TestService
类:
public class TestService extends AbstractTest1Service {
AbstractTest2Service abstractTest2Service;
public String doSomething() {
abstractTest2Service.writeText();
System.out.println("Passed!");
return "All Checked";
}
}
<小时/>
你的TestServiceTest
类应该是这样的:
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
.
使用@Spy会报错:
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.
关于java - 继承抽象类的抽象类中的 Mock 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59947461/