Reputation: 1717
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?
Upvotes: 1
Views: 2421
Reputation: 9965
You can use a Mock object configured with a mocking library of your choice, eg. Mockito.
Upvotes: 1
Reputation: 28099
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);
}
...
Upvotes: 4