简体   繁体   中英

How to get context in JUnit4

I have a 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;
    }
                     ...
}

In order to validate "String dimension" against a string-array in strings.xml, I need to call getResources() and for this I need a context (this is the only reason I have context in this class.)

This works fine in the app, but now I want to write JUnit4 tests for class Unit and would want to call Unit(), for instance something like:

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
                          ...

}

How do I get a context into the class UnitTest? Or should I somehow rewrite the test?

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

You can use a Mock object configured with a mocking library of your choice, eg. Mockito .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM