gpt4 book ai didi

java - Android 测试 - 无法设置正确的配置

转载 作者:行者123 更新时间:2023-11-28 20:55:17 25 4
gpt4 key购买 nike

我有一个 Android 应用,我想为它创建测试用例。

我已经阅读了 Android Dev 文档中的文档,并尝试了很多东西......

这是我的应用程序的主要结构:enter image description here

我创建了 SadAppTest 类,在编辑器中通过 ALT+ENTER 覆盖 SadApp extends Application 类,然后选择 Create Test 选项,请参阅:

enter image description here

生成的测试类代码如下:

包 com.procode.saveadog;

import android.test.ApplicationTestCase;

/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class SadAppTest extends ApplicationTestCase<SadApp> {
public SadAppTest() {
super(SadApp.class);
}
}

我尝试添加一个简单的测试,测试 SadApp 类中的内容。在文档中,我读到我应该通过 getActivity() 函数在代码中获取 Application 对象。

我创建了一个非常简单的测试,它从 Application 类中询问用户的 UUID,并比较给定的 UUID 是否相同。代码:

public void testUserUuid(){
assertEquals(getApplication().getUserId(), getApplication().getUserId());
}

但是这个测试抛出一个NullPointerException!

    java.lang.NullPointerException
at com.example.myapp.SadAppTest.testUserUuid(SadAppTest.java:14)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)

正是 getActivity() 方法返回 null,因为这个测试运行良好:

public void testUserUuid(){
assertTrue(getApplication() == null);
}

我错过了什么?

最佳答案

引用ApplicationTestCase您需要在 getApplication() 之前调用 createApplication() 的文档:

The test case will not call onCreate() until your test calls createApplication(). This gives you a chance to set up or adjust any additional framework or test logic before onCreate().

关于java - Android 测试 - 无法设置正确的配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833912/

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