Details
Recommendation type: NullPointerException Thrown
Configurable in Preferences: No
Filter category: Exceptions / assertion errors
Description
UTA displays this recommendation when a NullPointerException has been thrown during the test run. Depending on you code, the following action links may be available:
- Highlight - highlights the issue in the execution flow displayed in the Unit Test Assistant view.
- Go to - navigates to the code that throws NullPointerException.
- Null source - navigates to the source of null.
- Mock it - mocks the value of the object that is the source of null.
- Instantiate it - creates an instance of the object that is the source of null
- Generate missing stub - mocks the method called on the mock
UTA can detect the a NullPointerException within one source class.
See Exceptions and Assertion Errors for more options that can be displayed for exceptions.
Example
In the following example, the value of customer
is null
:
When the getName
method is called on the customer object, the NullPointerExceprion is thrown:
UTA detects the NullPointerException and displays the following information in the Recommendations view:
Repair
You can prevent the NullPointerException from being thrown in one of the following ways:
- Click Null source to navigate to the source of null and manually modify your code. For example, you can manually instantiate the
customer
object to ensure the object value is not null. - Click Instantiate it to automatically instantiate the object. The test will be updated with code required to create an instance of the
customer
object. You may need to manually replace the default values UTA generates.
- Click Mock it to automatically mock the object value. The test will be updated with code required to create the mock.
Then rerun the test. UTA will display information that NullPointerException has been thrown, because thegetName
method is called on the mocked object.
Click Generate missing stub to mock thegetName
method, which is called on the mockedcustomer
object.
The test will be updated with with code required to stub thegetName
method. - Click Mark as expected to add the
@Test(expected=NullPointerException.class)
annotation to the test code. This will prevent UTA from displaying this recommendation in the subsequent test runs.