Getting java.lang.NullPointerException when calling Method.invoke


The parameter that you pass to invoke must be an object on which the method is invoked, unless the method is static. What you did through reflection is equivalent to this:

MyTest obj = null;
obj.testBlah();

Naturally, there's an NPE. To fix this problem, pass an object on which to invoke the method, or make the method static.

Here is one way to make a fix:

public <T> void parse(Class<T> clazz, T obj)
throws Exception {
    Method[] methods = clazz.getMethods();
    int pass = 0;
    int fail = 0;

    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            Test test = method.getAnnotation(Test.class);
            Class expected = test.expected();
            try {
                method.invoke(obj);
                pass++;
            } catch (Exception e) {
                if (Exception.class != expected) {
                    e.printStackTrace();
                    fail++;
                } else {
                    pass++;
                }
            }
        }
    }
    System.out.println("Passed:" + pass + "   Fail:" + fail);
}

...

parser.parse(MyTest.class, new MyTest());

Demo on ideone.



Mockito : java.lang.NullPointerException when calling method from mocked Class

There is several issues in your code, the first one being that you are mocking the class you want to test, doing that you will only test the mock of ResourceB or you'll have to stub the code and force chosen method to call real code (thenCallRealMethod). The main idea is to never mock the class you are testing.

That is also why you have an NPE, because a mock don't need internal fields instance. As it should'nt need to.

Here's a correct way, there might be variations but that one is the most straightforward. So basically you'd want to test the interactions between ResourceB and ResourceC, as this is a unit test of ResourceB you'd want to mock ResourceC. The thing is mocks are per instance so you have to pass the mocked one to ResourceB.

It can be injected via constructor injection, you then need to modify the ResourceB :

public class ResourceB {
  ResourceC c;

  public ResourceB() { c = new resourceC(); } // normal behavior

  @VisibleForTesting // guava annotation (in, order to expalain why
there is this constructor)
  ResourceB(ResourceC c_override) { c = c_override; } // constructor
for the test, note the package visibility

  // ...
}

And in the test you'll write it this way :

public class TestResourceB {
  ResourceB tested_b;
  @Mock ResourceC mocked_c;

  @Before
  public void init_tested_and_mocks() {
    MockitoAnnotations.initMocks(this);
    tested_b = new ResourceB(mocked_)
  }

  @Test
  public void ensure_result_from_ResourceC_is_returned() {
    // given 
    when(mocked_c.callFuncA()).thenReturn("result that should be
returned");

    // when
    String output = tested_b.callFuncA();

    // then
    assertThat(output).isEqualTo("result that should be returned");
  }
}

By the way here's a few things to add :

  • As you are using JUnit 4.x, I'm using more meaningful/descriptive method names.
  • I'm using the Behavior Driven Development keywords (given, when, then) to help drive the test scenario.
  • Also I use AssertJ lib to write meaningful assertions.

Getting java.lang.NullPointerException when calling Method.invoke

The parameter that you pass to invoke must be an object on which the method is invoked, unless the method is static. What you did through reflection is equivalent to this:

MyTest obj = null;
obj.testBlah();

Naturally, there's an NPE. To fix this problem, pass an object on which to invoke the method, or make the method static.

Here is one way to make a fix:

public <T> void parse(Class<T> clazz, T obj)
throws Exception {
    Method[] methods = clazz.getMethods();
    int pass = 0;
    int fail = 0;

    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            Test test = method.getAnnotation(Test.class);
            Class expected = test.expected();
            try {
                method.invoke(obj);
                pass++;
            } catch (Exception e) {
                if (Exception.class != expected) {
                    e.printStackTrace();
                    fail++;
                } else {
                    pass++;
                }
            }
        }
    }
    System.out.println("Passed:" + pass + "   Fail:" + fail);
}

...

parser.parse(MyTest.class, new MyTest());

Demo on ideone.


grails unit test - java.lang.NullPointerException: Cannot invoke method finish() on null object

try:

grails test-app
TransactionController.testTransactionAnalytics

you forgot the "test" in front of the method name... and yes... it seems, you don't have to write it in the classname, but in the methodname you have to...


java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View .MainActivity.findViewById(int)' on a null object reference

put imageview as a variable of your class

private ImageView image;

on your onCreate initialize

image = (ImageView) findViewById(R.id.image);


public class Connection extends AsyncTask<String, Void, String>
{
        public String result;

        //I know, this isn't correct, how can i do?
        public MainActivity MainActivity;

        @Override
        protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
            //...

        return "a string";
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
                //...

        // Where the error is generated
        //do other stuff with your imageview

        //...

    }
}

caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void ... on a null object reference

Before you invoke findByViewId the view must be inflated. What you have to do is.. move this code from onCreate method to 'onCreateView' method. IN onCreateView method place it below setContentView() line..

ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
MenuNames);

final ListView lv = (ListView)
getListView().findViewById(R.id.listView1);

lv.setAdapter(adapter);

lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v,
            int position, long id) {

        if(position == 1) {
            //code specific to first list item    
            Intent myIntent = new Intent(v.getContext(),
ConsultationActivity.class);
            startActivity(myIntent);
        }
}

java.lang.NullPointerException: CameraUpdateFactory is not initialized, calling method on "onResume"

From http://developer.android.com/reference/com/google/android/gms/maps/CameraUpdateFactory.html,

Prior to using any methods from this class, you must do one of the following to ensure that this class is initialized:

  • Wait for a GoogleMap to become available from a MapFragment or MapView that you have added to your application. You can verify that the GoogleMap is available by calling the getMap() method and checking that the returned object is not null.
  • Call initialize(Context). As long as a GooglePlayServicesNotAvailableException isn't thrown, this class will be correctly initialized.

You have to make sure it's initialized before you can call any methods on it.



- Technology - Languages
+ Webmasters
+ Development
+ Development Tools
+ Internet
+ Mobile Programming
+ Linux
+ Unix
+ Apple
+ Ubuntu
+ Mobile & Tablets
+ Databases
+ Android
+ Network & Servers
+ Operating Systems
+ Coding
+ Design Software
+ Web Development
+ Game Development
+ Access
+ Excel
+ Web Design
+ Web Hosting
+ Web Site Reviews
+ Domain Name
+ Information Security
+ Software
+ Computers
+ Electronics
+ Hardware
+ Windows
+ PHP
+ ASP/ASP.Net
+ C/C++/C#
+ VB/VB.Net
+ JAVA
+ Javascript
+ Programming
Privacy Policy - Copyrights Notice - Feedback - Report Violation 2018 © BigHow