java - 继承抽象类的抽象类中的 Mock 方法

标签 java spring mockito

我有一个在我的 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/

相关文章:

java - java中没有 vector 的动态数组

java - 如何在Spring中注册FactoryBeans集合

java - 是否可以在没有 @DirtiesContext 的情况下测试 Spring REST Controller ?

Java:在finalize()中抛出异常的影响

java - java.io.File length() 可以锁定文件并阻止 File.delete() 工作吗?

java - HBase:什么是 NotServingRegionException?

java - 创建ApplicationContext后@Autowired Spring NullPointerException Null Beans

java - Spring Boot测试java.lang.IllegalStateException : Failed to load ApplicationContext and missing bean

java - 被测类模拟课

java - Mockito 具有静态类和返回 void 的方法