![](/img/trans.png)
[英]Running Gradle test with Robolectric and AppCompat results in NullPointerException
[英]Unit test with Robolectric.buildAttributeSet() results in NullPointerException
我有一個 PercentView 類,我正在嘗試設置一個測試,我想驗證它是否被繪制到正確的大小。 我已經將它用於一個簡單的欄,但現在我想要一個圖像/圖標在它上面,它是一個可繪制的(實際上是矢量)。
關於這個的一些注意事項:
app_enabled.xml
的可繪制文件(它是矢量),它是main\\res\\drawable\\app_enabled.xml
。Robolectric 3.5.1
我已經聲明了樣式:
<declare-styleable name="PercentageView">
<attr name="image" format="integer" />
</declare-styleable>
和觀點:
public class PercentageView extends View {
private int _activeColor;
private int _barBackgroundColor;
private float _barHeight;
private Drawable _icon;
private Paint _barBackgroundPaint;
private Paint _barActivePaint;
private int _percent;
public PercentageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
TypedArray args = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.PercentageView,
0,
0);
try {
_icon = args.getDrawable(R.styleable.PercentageView_image);
} finally {
args.recycle();
}
init();
}
}
現在測試:
@RunWith(RobolectricTestRunner.class)
public class PercentageViewTests {
private ShadowCanvas _shadowCanvas;
private int _width;
private int _height;
private float _expectedPercentWidth;
private int _thePercent;
private Canvas _canvas;
private PercentageView SetUpView(int width, int height, int percent, boolean useIcon) {
ShadowApplication app = shadowOf(RuntimeEnvironment.application);
//Attempt to pass in the icon, if useIcon is true
AttributeSet attr = useIcon ? Robolectric.buildAttributeSet()
.addAttribute(R.styleable.PercentageView_image, "@drawable/app_enabled") //NullPointerException here
.build() : null;
PercentageView view = new PercentageView(app.getApplicationContext(), attr);
view.setLayoutParams(new ViewGroup.LayoutParams(width, height));
view.setPercent(percent);
return view;
}
@Before
public void setup() {
Random random = new Random(10);
_width = random.nextInt(100);
random.setSeed(101);
_height = random.nextInt(200);
random = new Random(0);
_thePercent = random.nextInt(100);
_expectedPercentWidth = _width * _thePercent / 100;
_canvas = new Canvas();
_shadowCanvas = shadowOf(_canvas);
}
@Test
public void ShouldHaveIcon() {
PercentageView view = SetUpView(_width, _height, _thePercent, true);
view.onDraw(_canvas);
assertThat(_shadowCanvas.getRectPaintHistoryCount(), is(equalTo(3)));
}
}
非常悲傷的堆棧跟蹤:
java.lang.NullPointerException
at org.robolectric.Robolectric$AttributeSetBuilder.addAttribute(Robolectric.java:161)
at myorg.controls.PercentageViewTests.SetUpView(PercentageViewTests.java:41)
at myorg.controls.PercentageViewTests.ShouldHaveIcon(PercentageViewTests.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:523)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:226)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:108)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:35)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:62)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
嘗試用R.styleable.PercentageView_image
替換R.attr.image
。
似乎addAttribute()
的第一個參數需要是一個attr
res,而不是一個stylable
。
這是遲到的回應,但是,今天我也在努力解決這個問題。
我想創建一個自定義的 HelpLinkButton,它接受一個 Url 作為 xml 中的屬性參數。
attrs.xml:
<declare-styleable name="HelpLinkButton">
<attr name="Url" format="string|reference" />
</declare-styleable>
幫助鏈接按鈕
class HelpLinkButton @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int
) : AppCompatButton(context, attrs, defStyleAttr) {
var uri: Uri = Uri.EMPTY
init {
super.setOnClickListener {}
context?.let { _context ->
_context.obtainStyledAttributes(attrs, R.styleable.HelpLinkButton, defStyleAttr, 0)?.let { typedArray ->
if (typedArray.hasValue(R.styleable.HelpLinkButton_Url)) {
typedArray.getResourceId(R.styleable.HelpLinkButton_Url, -1).let {
if (it != -1) {
uri = Uri.parse(_context.getString(it))
} else {
typedArray.getString(R.styleable.HelpLinkButton_Url)?.let {
uri = Uri.parse(it)
}
}
}
}
typedArray.recycle()
}
}
}
override fun setOnClickListener(l: OnClickListener?) {}
}
測試.kt
@RunWith(AndroidJUnit4::class)
class HelpLinkButtonTest {
@Test
fun inits_with_string_attr() {
val builder = Robolectric.buildAttributeSet()
val url = "http://example.com"
builder.addAttribute(R.attr.Url, url)
val button = HelpLinkButton(
context = ApplicationProvider.getApplicationContext(),
attrs = builder.build(),
defStyleAttr = 0
)
assertThat(button.uri.toString()).isEqualTo(url)
}
@Test
fun inits_with_resource_attr() {
val builder = Robolectric.buildAttributeSet()
builder.addAttribute(R.attr.Url, "@string/upgrade_now_help_url")
val button = HelpLinkButton(
context = ApplicationProvider.getApplicationContext(),
attrs = builder.build(),
defStyleAttr = 0
)
assertThat(button.uri.toString()).isEqualTo("https://dropbit.app/upgrade")
}
}
我在期望的末尾添加了/
以顯示attrs
按預期工作的失敗輸出。
測試輸出
[Robolectric] com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_resource_attr: sdk=28; resources=BINARY
Called loadFromPath(/system/framework/framework-res.apk, true); mode=binary sdk=28
expected: https://dropbit.app/upgrade/
but was : https://dropbit.app/upgrade
Expected :https://dropbit.app/upgrade/
Actual :https://dropbit.app/upgrade
<Click to see difference>
at com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_resource_attr(HelpLinkButtonTest.kt:40)
[Robolectric] com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_string_attr: sdk=28; resources=BINARY
WARN: No type identifier when getting name for resource number 0x01000000
expected: http://example.com/
but was : http://example.com
Expected :http://example.com/
Actual :http://example.com
<Click to see difference>
at com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_string_attr(HelpLinkButtonTest.kt:26)
Process finished with exit code 255
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.