如何在JUnit4中获取上下文

时间:2015-10-02 08:33:07

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

我有一个班级:

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(),为此我需要一个上下文(这是我在这个类中有上下文的唯一原因。)< / p>

这在应用程序中运行良好,但现在我想为类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类中获取上下文?或者我应该以某种方式改写测试?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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