NullPointerException in JUnit - exception

I am running this JUint test method, and while running getting an exception NullPointerException. How to handle this exception over here?
#Test
public void testDivision1() {
System.out.println("testDivision");`
Operation instance = new Operation(100, 2, null);
int res = instance.calculate();
assertEquals(50, res);
}

As you pass null for EnumOp operator here
Operation instance = new Operation(100, 2, null);
I assume this operation fails
return operator.calculate(firstOperand, secondOperand);
You should set a valid EnumOp for the test.

Related

Null pointer exception in method that calls another method Mockito

I am new to Mockito and Powermockito. I have a class to test which interacts with the database in order find and also delete data from the database through different public methods. The application is typical Java EE application and the The class under test belongs to Service package in Businesslogic. The method which I want to test looks like below :
public List<QuestionDtoWrapper> searchInQuestions(final Integer ID, final Integer catID,
final String searchString, final String language) {
final List<QuestionDtoWrapper> result = new ArrayList<>();
//In line below I get null pointer exception although I have stubbed this method
final List<QuestionDtoInt> questions = facade.findQuestionsByCatTemplate(ID, catID,
searchString, language);
for (final QuestionDtoInt question : questions) {
result.add(new QuestionDtoWrapper(question));
}
Collections.sort(result, new QuestionComparator(new Locale("de")));
return result;
}
This is how I tried to test the method in my Junit Test:
#RunWith(MockitoJUnitRunner.class)
#PrepareForTest(QuesService.class)
public class QuesServiceTest {
#Mock
QuesFacade mockFbFacade;
#Mock
List<QuesDtoInt> questions;
#Spy
QuesService myService = new QuesService();
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void testSearchInQuestions() throws ParseException {
PowerMockito.doReturn(questions).when(mockFbFacade).findQuestionsByCatTemplate(anyInt(), anyInt(), anyString(), anyString());
List<QuestionDtoWrapper> res = null ;
res = myService.searchInQuestions(anyInt(), anyInt(), anyString(), anyString());
assertNotNull(res);
}
I am getting Null pointer exception in Line where the method calls another method. See my comment in source code. Could someone please let me know:
1) Am I using mockito for the correct subject ? Should I use real Test data ? But what about the database connections n all ? I tried that approach and ended up using Mockito only.
2) Why am I getting Null pointer exception although I have stubbed that method with Powermockito ?
3) please provide your valuable suggestions to test the given method correctly.
Note:- I am not allowed to do any refactoring in the code.

Handling Runtime Exception in CompletableFuture in java8

Below is the sample code I'm using to understand exception handling in completablefuture in java8.
If we make use of exceptionally method as per doc,
exceptionally method catches even runtime exception as well and proceeds to last block in the pipeline.
if we don't use exceptionally method then, it justs prints running and exits.
Correct me if my understanding isn't correct.
Question is Lets say if i want to throw runtime exception and want application to stop. Basically if i throw Runtime exception , it shouldn't proceed to next block in pipeline. How should i do that. Any pointers are helpful.
public static void main(String[] args) {
final CompletableFuture<String> retrieveName = CompletableFuture.supplyAsync(() -> {
System.out.println("running");
int i = 0;
if(i == 0) {
throw new RuntimeException("ding");
}
return "test";
}).exceptionally(it -> {
System.out.println(it.getMessage());
return "empty";
}).thenApply(it -> {
System.out.println("last block" + it);
return "dummy";
});
}
Try this:
public static void main(String[] args) {
try {
final CompletableFuture<String> retrieveName = CompletableFuture.supplyAsync(() -> {
System.out.println("running");
int i = 0;
if (i == 0) {
throw new RuntimeException("ding");
}
return "test";
}).exceptionally(it -> {
if (it.getMessage().contains("ding")) {
throw (RuntimeException) it;
}
System.out.println(it.getMessage());
return "empty";
}).thenApply(it -> {
System.out.println("last block" + it);
return "dummy";
});
retrieveName.join();
} catch (Exception e) {
System.out.println("main() exception, cause=" + e.getCause());
}
}
This is the output:
running
main() exception, cause=java.lang.RuntimeException: ding
I made 3 small changes to your code:
Wrapped it all in a try-catch
Threw a RuntimeException in exceptionally() for the "ding" exception.
Added a call to retrieveName.join(). From the Javadoc for CompletableFuture.join():
public T join​()
Returns the result value when complete, or throws an (unchecked) exception if completed exceptionally.
Update based on OP feedback ------->
Lets say if i want to throw runtime exception and want application to
stop. Basically if i throw Runtime exception , it shouldn't proceed to
next block in pipeline. How should i do that.
You can achieve what you want with just 2 changes to your code:
[1] Completely remove the exceptionally() callback so the CompletableFuture (CF) terminates with an exception. In exceptionally() in the OP code the exception was being swallowed rather than rethrown, and returning a CF, so the thenApply() method was still performed.
[2] Add a call to retrieveName.join() at the end of main(). This is a blocking call, but since the thread had terminated with an exception that 's not really relevant for the sample code. The join() method will extract the thrown RunTimeException and re-throw it, wrapped in a CompletionException.
Here's your modified code:
public static void main(String[] args) {
final CompletableFuture<String> retrieveName = CompletableFuture.supplyAsync(() -> {
System.out.println("running");
int i = 0;
if(i == 0) {
throw new RuntimeException("ding");
}
return "test";
}).thenApply(it -> {
System.out.println("last block" + it);
return "dummy";
});
retrieveName.join();
}
Notes:
This is not how to do things in Production. The blocking call from join() was not a problem here, but could be for a long running CF. But you obviously can't extract the exception from the CF until it is complete, so it makes sense that the join() call blocks.
Always bear in mind that main() is not running in the same thread(s) as the CF.
An alternative approach (if viable) might be to handle all the necessary post-exception actions (logging, etc,) within exceptionally() and then terminate normally with a suitable return value (e.g. "Exception handled!") rather than propagating the exception.
You can check whether the CF is still running by calling the non-blocking isDone() method. You can also check whether the CF ended with an exception (isCompletedExceptionally()) or was cancelled(isCancelled​()).

Findbugs reports Load of known null value while validating constructor argument

Upon scanning following code with findbugs, it reports Dodgy code:NP: Load of known null value in new ....(at line where new Exception is thrown)
Sometimes it is required to check null before initializing an object.
Why is this considered "dodgy"??
public class Employee{
#Valid
private Department dept;
#JsonCreator
public Employee(#JsonProperty(value = "department", required = true) Department aDepartment)
throws EmpServiceException{
if (aDepartment == null) {
throw new EmpServiceException(aDepartment, "Invalid Request");
}
this.dept= aDepartment;
}
My guess is that FindBugs is pointing out that the line where you throw the exception
throw new EmpServiceException(aDepartment, "Invalid Request");
is equivalent to
throw new EmpServiceException(null, "Invalid Request");
and wants you to use the latter. Is the first argument for that EmpServiceException constructor annotated with #NonNull?

Exception handling and constructors

I am writing data to a file, when I write this data I want to do it so that if the file does not open it will give the user a message saying that something whent wrong. The way I do this is by calling the method to write, if it fails it returns false. That way I can prompt the user to do something to check what has happened.
However when I create the object I cant return anything from the constructor so I am a bit stumped about what I should do.
public class Writetofile {
BufferedWriter writer = null;
public Writetofile(String[]details) throws IOException{
String machine= details[0];
String date=details[1];
String start_time = details[2];
try{
File new_cal= new File("C:\\Activity_Calibrator\\log\\"+machine+"\\"+machine+date+".txt");
new_cal.getParentFile().mkdir();
FileWriter fwriter = new FileWriter(new_cal);
writer = new BufferedWriter(fwriter);
writer.write("Linear Calibratiton for " + machine + " carried out " + date+" ./n");
writer.close();
}
catch(Exception e){ in here I would like to be able to send a message back to m
code so that it can tell the user to check the folder etc}
}
when I call the record data if something goes wrong it will return a false to the calling class. and I can put a message.
public boolean recordData(String record) throws IOException{
try{
writer.append(record);
writer.close();
return true;
}
catch(Exception e){
return false;
}
}
}
}
A constructor should not DO anything. A constructor is an initialization phase closely tied to the allocation of an object.
Throwing exceptions, or doing anything in a constructor that might throw an exception is to be avoided.
Java does not separate the phases of allocation and initialization, no code, especially IO code should be in a constructor.

Junit exception handling

I want to know that whether this test case should pass or fail
beacause
expected = IndexOutOfBoundsException.class
and actually it is throwing Arithmatic exception. can anyone explain?
#Test(expected = IndexOutOfBoundsException.class)
public void testDivideNumbers()throws ArithmeticException{
try{
double a = 10/0;
fail("Failed: Should get an Arithmatic Exception");
}
catch (ArithmeticException e) {
}
}
To test that the correct exception is thrown you should not have the test method throw the exception but just have the test itself result in the thrown exception.
So if ArithmeticException is expected then the test should be:
#Test(expected = ArithmeticException.class)
public void testDivideNumbers() {
double a = 10/0;
}
It should fail because it doesn't throw any exception; the ArithmeticException is caught and swallowed by the catch block.
This test is expecting to get an IndexOutOfBoundsException thrown. Because that does not happen in the test, the test fails. You can "fix" the test like this:
#Test(expected = IndexOutOfBoundsException.class)
public void testDivideNumbers() {
try {
double a = 10/0;
Assert.fail("Failed: Should get an Arithmetic Exception");
}
catch (ArithmeticException e) {
// Assert that this exception is thrown as expected
Assert.assertEquals("/ by zero", e.getMessage());
}
throw new IndexOutOfBoundsException();
}
You should not leave the catch block empty. You should always put some assert in it proving that the fail() didn't happen and the catch did happen and, importantly, happened for the reason you expected.