gpt4 book ai didi

java - 如何在 JUnit4 中获取上下文

转载 作者:行者123 更新时间:2023-11-29 03:04:18 24 4
gpt4 key购买 nike

我有一个类:

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 中?或者我应该以某种方式重写测试?

最佳答案

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

关于java - 如何在 JUnit4 中获取上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32903346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com