简体   繁体   English

Mockito。 如何在被测类中模拟抽象方法调用?

[英]Mockito. How to mock abstract method call in class under test?

I have Test class for controller. 我有控制器的测试类。 I need to inject autowired field. 我需要注入自动接线字段。 And mock method of Controller's super class (I have no possibility to refactor this situation) 和Controller的超类的模拟方法(我无法重构这种情况)

   public class ControllerTest {

        @Mock
        Service service;


        @InjectMocks
        Controller controller;


    @Test
    public vois test() {
      controller.process();

    }
}

In process() method service is called and superclass's method, too. 在process()中,方法服务也被调用,而超类的方法也被调用。

I tried to init my controller in test in this way 我试图以此方式初始化我的控制器

new Controller() {

@Override
superMethod() {
    //do nothing
}
}

But I cannot inject service mock in this case due to setter is missing. 但是由于缺少setter,在这种情况下我无法注入服务模拟。 I can do it with reflection, but maybe someone knows more elegant solution? 我可以反射一下,但是也许有人知道更优雅的解决方案?

If you are using annotations, you must to put @RunWith(MockitoJUnitRunner.class) above the ControllerTest or create setUp method like this: 如果使用批注,则必须将@RunWith(MockitoJUnitRunner.class)放在ControllerTest上方,或创建如下的setUp方法:

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

Hope this help. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 测试摘要 class 和 Mockito。怎么样? - Testing abstract class with Mockito. How? jUnit,Mockito。 如何确保抽象类中的方法(模板方法)调用抽象钩子方法? - jUnit, Mockito. How to ensure a method in abstract class (a templae method) invokes the abstract hook method? 如何使用 Mockito 验证 PreparedStatement 场景。 无法在测试 class 中模拟 PreparedStatement class - How to validate PreparedStatement scenario with Mockito. Unable to mock the PreparedStatement class in test class Java Mockito JUnit测试/模拟类,其构造函数包含抽象的Method调用 - Java Mockito JUnit Test / Mock Class with a constructor that contains a abstract Method call 的Mockito。验证方法参数是否为特定类 - Mockito. Verify method param to be a particular class 如何在Mockito中模拟正在测试的班级中的私人班级成员 - How to mock private class members in a class under test with Mockito 如何模拟在Mockito中的测试类中创建的对象 - How to Mock an object which is created in the class under test in Mockito Mockito。 模拟单个方法抛出异常 - Mockito. Mock single method which throws an exception 如何使用Mockito模拟方法调用 - How to mock a method call with Mockito 如何使用Mockito对依赖equals()的抽象类方法进行单元测试? - How to unit test an abstract class method that depends on equals() with Mockito?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM