是否可以调用模拟对象的方法

是否可以调用模拟对象的方法

本文介绍了是否可以调用模拟对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个类:

public class A {
    private List<String> list;

    public A(B b){
        list = b.getList();
    }

    public List<String> someMethod(){
        return list;
    }
}

我想在不调用构造函数的情况下对 someMethod 进行单元测试.我使用 reflection 来设置 list.

I want to unit test someMethod without invoking constructor. I use reflection to set list.

问题是我不想创建 B 类对象,我不能模拟它,因为它会导致 NPE.

The problem is that I don't want to create B class object and I cannot mock it since it will cause NPE.

所以我的问题是:

如何在不调用A的构造函数的情况下测试someMethod?有没有办法模拟A类并且不失去调用方法的可能性?

How to test someMethod without calling constructor of A? Is there any way to mock class A and doesn't lose posibility to call methods?

创建具有零参数的构造函数不是解决方案.

Creating constructor with zero arguments is not a solution.

注意:不想改变A类的任何部分.我在问是否可以在不添加或更改 A 类中的任何内容的情况下执行此测试.

Note: I don't want to change any part of A class. I'm asking if it is possible to perform this test without adding or changing anything in A class.

推荐答案

您可以测试 A 类,而无需通过 Mockito 调用它的构造函数.不确定我是否真的了解您的要求,但以下代码对我有用.

You can test class A without calling it's constructor by Mockito. Not sure if I really understand your requirement but the following codes work for me.

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ATest {

    @Test
    public void test() {
        A a = mock(A.class);
        when(a.someMethod()).thenCallRealMethod();
        List<String> listInA = new ArrayList<String>();
        ReflectionTestUtils.setField(a, "list", listInA);
        assertThat(a.someMethod(), is(listInA));
    }
}

这篇关于是否可以调用模拟对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:40