【问题标题】:How to get context in JUnit4如何在 JUnit4 中获取上下文
【发布时间】:2015-12-30 10:31:12
【问题描述】:

我有一堂课:

public class Unit {

    private int id;
    private String unit;
    private String dimension;
    private Float factor;

    private Context ctx;


    public Unit(Context context){ this.ctx = context; }

    public Unit(String unit, String dimension, Float factor, Context context) {
        super();
        this.ctx = context;
        setUnit(unit);
        setDimension(dimension);
        setFactor(factor);
    }

    public void setDimension(String d) {
        String[] dimensions = ctx.getResources().getStringArray(R.array.dimensions_array);

        if(!Arrays.asList(dimensions).contains(d)){
            throw new IllegalArgumentException("Dimension is not one of the permittable dimension names");
    }

        this.dimension = d;
    }
                     ...
}

为了针对 strings.xml 中的字符串数组验证“字符串维度”,我需要调用 getResources(),为此我需要一个上下文(这是我在此类中有上下文的唯一原因。)

这在应用程序中运行良好,但现在我想为 Unit 类编写 JUnit4 测试并想调用 Unit(),例如:

public class UnitTest {
    Unit unit;

    @Before
    public void init() throws Exception {
        System.out.println("Setting up ...");

        unit = new Unit("dm","length", (float) 0.1,some_context); // What context should I put here?
    }

    @Test
                          ...

}

如何在 UnitTest 类中获取上下文?或者我应该以某种方式重写测试?

【问题讨论】:

    标签: java android unit-testing junit4 android-context


    【解决方案1】:
    import static org.mockito.Mockito.*;
    
    @RunWith(MockitoJunitRunner.class)
    public class UnitTest {
        @Mock private Context context;
    
        @Before
        public void init() throws Exception {
            when(context.doStuff()).thenReturn("stuff");
            unit = new Unit("dm","length", (float) 0.1, context);
        }
        ...
    

    【讨论】:

    • 感谢您的回复。我不确定我是否理解“doStuff-thenReturn”部分。如果我把那个留出来(可以吗?),我会在“unit=new Unit(...)”这一行得到一个 NPE,这是由于“String [] 维度 = ctx.getResources()..." 在 setDimension() 方法中。我还尝试调用“MockitoAnnotations.initMocks(this);”在 init() 中,当我在某处读到所需的内容时。
    • 1.如果您使用@RunWith(MockitoJunitRunner.class),则不需要MockitoAnnotations.initMocks(this)
    • 2. when(context.doStuff()).thenReturn("stuff"); 展示了如何模拟与模拟对象的交互。在这种情况下,我假设您要模拟一个名为 doStuff() 的方法。您似乎想将其更改为 when(context.getResources()).thenReturn(new String[] { ... });
    • 谢谢,这很有帮助。我实际上使用了when(context.getResources().getStringArray(R.array.dimensions_array)).thenReturn(new String [] {"length", "mass", "volume"});,并且还不得不将模拟上下文更改为@Mock(answer = Answers.RETURNS_DEEP_STUBS) private Context context;,因为我有一个链式存根。
    【解决方案2】:

    您可以使用配置了您选择的模拟库的Mock object,例如。 Mockito.

    【讨论】:

    • 谢谢。你能说得清楚一点吗,因为我只是一个初学者?
    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2023-03-10
    • 2017-09-22
    • 2021-03-31
    • 2019-11-09
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多