GVKun编程网logo

Struts 2 Junit测试用例执行失败(StrutsTestCase.getActionProxy:138»NullPointer)

12

如果您对Struts2Junit测试用例执行失败感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Struts2Junit测试用例执行失败的详细内容,我们还将为您解答Strut

如果您对Struts 2 Junit测试用例执行失败感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Struts 2 Junit测试用例执行失败的详细内容,我们还将为您解答StrutsTestCase.getActionProxy:138»NullPointer的相关问题,并且为您提供关于@PutMapping的JUnit RestControllerTest引发InvocationTargetException、Android HttpUrlConnection getInputStream引发NullPointerException、Android InstrumentationTestCase getFilesDir()返回null、android – 由于“java.lang.NullPointerException”导致Instrumentation运行失败的有价值信息。

本文目录一览:

Struts 2 Junit测试用例执行失败(StrutsTestCase.getActionProxy:138»NullPointer)

Struts 2 Junit测试用例执行失败(StrutsTestCase.getActionProxy:138»NullPointer)

我通过参考以下
链接创建了一个示例struts 2项目和junit测试用例。

http://self-learning-java-tutorial.blogspot.com.au/2015/04/struts2-junit- integration.html

但是,在执行测试用例时,出现以下错误,

Eclipse JUNIT stacktrace中的错误

答案1

小编典典

在构建路径中添加classes文件夹后,eclipse中的错误得以解决。

Eclipse错误

但是在 执行maven构建测试期间遇到新问题之后

@PutMapping的JUnit RestControllerTest引发InvocationTargetException

@PutMapping的JUnit RestControllerTest引发InvocationTargetException

您需要如下所示返回songService.getSongById的值

@Test
void updateSongById_success() throws Exception {
    
    when(songService.getSongById(Mockito.any())).thenReturn(getValidSongDto());
    
    when(songService.updateSong(anyInt(),any(SongDto.class))).thenReturn(getValidSongDto());
    
    String songDtoJson = objectMapper.writeValueAsString(getValidSongDto());
    
    mockMvc.perform(put("/rest/v1/songs/1")
            .content(songDtoJson)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
}

Android HttpUrlConnection getInputStream引发NullPointerException

Android HttpUrlConnection getInputStream引发NullPointerException

我正在尝试从以下网址下载图像:

https://hme_player_pictures.s3.amazonaws.com/test-512813ed3b83286c72f376c7-thumb100.jpg

这是堆栈跟踪:

03-21 12:58:04.040: W/System.err(7084): java.lang.NullPointerException
03-21 12:58:04.040: W/System.err(7084):     at libcore.net.http.httpconnection$Address.hashCode(httpconnection.java:343)
03-21 12:58:04.045: W/System.err(7084):     at java.util.HashMap.get(HashMap.java:298)
03-21 12:58:04.050: W/System.err(7084):     at libcore.net.http.httpconnectionPool.get(httpconnectionPool.java:67)
03-21 12:58:04.050: W/System.err(7084):     at libcore.net.http.httpconnection.connect(httpconnection.java:128)
03-21 12:58:04.050: W/System.err(7084):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-21 12:58:04.055: W/System.err(7084):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:460)
03-21 12:58:04.055: W/System.err(7084):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
03-21 12:58:04.055: W/System.err(7084):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-21 12:58:04.060: W/System.err(7084):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-21 12:58:04.065: W/System.err(7084):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
03-21 12:58:04.065: W/System.err(7084):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
03-21 12:58:04.070: W/System.err(7084):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270)
03-21 12:58:04.070: W/System.err(7084): ...

码:

URL imageUrl = new URL(url);
HttpURLConnection c = (HttpURLConnection)imageUrl.openConnection();
InputStream in = c.getInputStream(); // Nullpointer exception on this line, c is definitely not null, I debugged

无法弄清楚为什么会引发NullPointerException.上面的网址确实可以在浏览器中使用.

解决方法:

对于它的价值,我在Android HTTP库中看到很多错误.从条码扫描器中,我可以看到大约3500万人员的堆栈跟踪,因此,我想我已经看到了其中的一切.这是我们在下面的应用程序中发现并吞下的所有怪异内容.我建议您将其作为平台错误来解决,并优雅地失败.

https://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/HttpHelper.java

  private static int safelyConnect(String uri, HttpURLConnection connection) throws IOException {
    try {
      connection.connect();
    } catch (NullPointerException npe) {
      // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(npe.toString());
    } catch (IllegalArgumentException iae) {
      // Also seen this in the wild, not sure what to make of it. Probably a bad URL
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(iae.toString());
    } catch (SecurityException se) {
      // due to bad VPN settings?
      Log.w(TAG, "Restricted URI? " + uri);
      throw new IOException(se.toString());
    } catch (indexoutofboundsexception ioobe) {
      // Another Android problem? https://groups.google.com/forum/?fromgroups#!topic/google-admob-ads-sdk/U-WfmYa9or0
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(ioobe.toString());
    }
    try {
      return connection.getResponseCode();
    } catch (NullPointerException npe) {
      // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(npe.toString());
    } catch (NumberFormatException nfe) {
      // Again seen this in the wild for bad header fields in the server response!
      Log.w(TAG, "Bad server status? " + uri);
      throw new IOException(nfe.toString());
    }
  }

Android InstrumentationTestCase getFilesDir()返回null

Android InstrumentationTestCase getFilesDir()返回null

我正在使用InstrumentationTestCase对我的应用程序的一个组件进行单元测试.

该组件将数据持久保存到内部存储并使用Context :: fileList();检索持久化文件.

我遇到以下问题:在应用程序中使用此方法(在设备上)工作完全正常.但是当我尝试使用InstrumentationTestCase(Android-)单元测试(也在设备上)时,我在fileList()方法中得到一个NullPointerException.我深入研究android源代码,发现getFilesDir()(see source here)返回null并导致此错误.

要重现的代码如下:

public class MyTestCase extends InstrumentationTestCase
{   
    public void testExample() throws Exception
    {
        assertNotNull(getInstrumentation().getContext().getFilesDir()); // Fails
    }
}

我的问题是:这种行为是否有意?我该怎么做才能绕过这个问题?我是使用InstrumentationTestCase还是应该使用不同的东西?

我找到了this question,但我不确定这是否涵盖了我遇到的同样问题.

解决方法

我认为您将测试数据与测试应用程序分开是正确的.

您可以通过执行以下命令为Instrumentation app创建文件目录来解决Null问题

adb shell
cd /data/data/<package_id_of_instrumentation_app>
mkdir files

您只能在模拟器或root设备上执行此操作.

然后从你的问题测试不会失败.我做了它并且还将名为tst.txt的文件上传到文件dir,所有以下测试都成功:

assertNotNull(getInstrumentation().getContext().getFilesDir());
assertNotNull(getInstrumentation().getContext().openFileInput("tst.txt"));
assertNotNull(getInstrumentation().getContext().openFileOutput("out.txt",Context.MODE_PRIVATE));

但我认为为测试项目提供数据的更方便的方法是使用测试项目的资产,您可以在其中简单地保存一些文件并打开它们:

assertNotNull(getInstrumentation().getContext().getAssets().open("asset.txt"));

或者如果要将某些测试结果保存到文件中,可以使用ExternalStorage:

File extStorage = Environment.getExternalStorageDirectory();
assertNotNull(extStorage);

android – 由于“java.lang.NullPointerException”导致Instrumentation运行失败

android – 由于“java.lang.NullPointerException”导致Instrumentation运行失败

我试图通过使用ActivityUnitTestCase扩展测试类,在我的应用程序中为活动编写单元测试用例.我可以早期成功运行测试用例,但现在我总是在运行它们时得到异常.即使我很熟悉处理NullPointerExceptions,但我无法弄清楚导致此问题.我找不到任何类似的问题,所以我发布这个.

堆栈跟踪显示我的代码中的这一行有一个空对象引用

activity = startActivity(mIntent,null,null);

但是StartActivity方法应该是获取我正在测试的活动的实例.我不知道为什么它返回null.

这是堆栈跟踪.

java.lang.NullPointerException: Attempt to write to field 'android.os.IBinder android.app.ActivityThread.mLastIntendedActivityToken' on a null object reference
at android.app.Activity.performCreate(Activity.java:6372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:346)
at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:158)
at com.abc.test.MainActivityTest.access$100(MainActivityTest.java:16)
at com.abc.test.MainActivityTest$1.run(MainActivityTest.java:34)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:1891)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Test running Failed: Instrumentation run Failed due to 'java.lang.NullPointerException'

这是Test类

public class MainActivityTest extends ActivityUnitTestCase<MainActivity>{

    private Intent mIntent;
    private MainActivity activity;

    public MainActivitytest() {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        //Create an intent to launch target Activity as it is not automatically started by Android Instrumentation
        mIntent = new Intent(getInstrumentation().getContext(),MainActivity.class);
        //Start the activity under test in isolation,in the main thread to avoid assertion error.
        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                activity = startActivity(mIntent,null);
            }
        });
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    /**
     * Tests the preconditions of this test fixture.
     */
    @SmallTest
    public void testPreconditions() {
        assertNotNull("MainActivity is null",getActivity());
    }

    @MediumTest
    public void testSecondActivityWasLaunchedWithIntent() {
        // Get the intent for the next started activity
        final Intent launchIntent = getStartedActivityIntent();
        //Verify the intent was not null.
        assertNotNull("Intent was null",launchIntent);
        //Verify that LaunchActivity was finished
        assertTrue(isFinishCalled());
    }
}

解决方法

@prudhvi我不认为我有一个银弹,不幸的是,但我建议尝试跟随 these steps升级到SDK的较新版本的新的测试支持库.对不起,我不能更多的帮助!

今天关于Struts 2 Junit测试用例执行失败StrutsTestCase.getActionProxy:138»NullPointer的讲解已经结束,谢谢您的阅读,如果想了解更多关于@PutMapping的JUnit RestControllerTest引发InvocationTargetException、Android HttpUrlConnection getInputStream引发NullPointerException、Android InstrumentationTestCase getFilesDir()返回null、android – 由于“java.lang.NullPointerException”导致Instrumentation运行失败的相关知识,请在本站搜索。

本文标签: