如何在 JUnit4 中获取上下文

How to get context in JUnit4

我有一个class:

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 中的字符串数组验证 "String dimension",我需要调用 getResources() 并且为此我需要一个上下文(这是我有上下文的唯一原因这个class.)

这在应用程序中运行良好,但现在我想为 class 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
                          ...

}

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

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);
    }
    ...

您可以使用 Mock object configured with a mocking library of your choice, eg. Mockito.