-3

I'm doing some tests for my app and when I send a null it catch NullPointerException. The method still contines but the test present an error. How can avoid it?.

TestService.java

Integer number = null;

ServiceToTest service;

try{
    service.methodToTest(number);
}
catch(Exception e){
//Do some stuff
}

ServiceToTest.java

public void methodToTest(Integer number){
   if(number != null) //Do some stuff
}

I tried too if(number.equals(null)) but it also have the same exception

Raider
  • 394
  • 1
  • 2
  • 26
  • 4
    Did you initialize `service`? – awksp Jun 26 '14 at 08:02
  • @user3580294 Did you read the Question? – Grim Jun 26 '14 at 08:04
  • @Raider what version of JUnit do you use? – Grim Jun 26 '14 at 08:05
  • @PeterRader Yes. Why? – awksp Jun 26 '14 at 08:07
  • @user3580294 service must be null, its a valid test for NPE, if you initialize the service, no NPE is thrown. He only likes to know how to prevent the error-message, not the NPE. This NPE-Test is a common testcase and checks for non-static-methods. – Grim Jun 26 '14 at 08:09
  • @PeterRader I guess we're interpreting "it" to mean different things. Your interpretation is probably more correct than mine, especially since I just realized that if `service` wasn't initialized the code wouldn't even compile, let alone get to the point where a NPE could be thrown. I'm curious why code from `ServiceToTest.java` would be needed if the test were for `service` only. – awksp Jun 26 '14 at 08:12
  • 1
    @PeterRader I have 4.11 – Raider Jun 26 '14 at 08:17

3 Answers3

4

Use

@Test(expected=NullPointerException.class)

instead of

@Test

and the error-message will go away.

Grim
  • 1,938
  • 10
  • 56
  • 123
  • http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests Duplicate? – Grim Jun 26 '14 at 08:27
0

You should probably add ServiceToTest service = new ServiceToTest() , assuming the constructor takes no arguments. The null reference is for service, not number

Grim
  • 1,938
  • 10
  • 56
  • 123
omu_negru
  • 4,642
  • 4
  • 27
  • 38
  • 1
    -1 Its a NPE-Test. He only like to avoid the error-message,not the NPE. – Grim Jun 26 '14 at 08:11
  • actually, if you want to nitpick, i don't see any real question here..like "how do i avoid the message" – omu_negru Jun 26 '14 at 08:12
  • `... when I send a null it catch ... but the test present an error. How can avoid it.`. Anyway some misread this, i remove the downvote. – Grim Jun 26 '14 at 08:26
0

Assuming you want to test, that your method throws a NullPointerException as expected, then your test case has to assume that the control flow goes into your catch-block and you do nothing there which causes the test to become green. If instead the flow continues beyond the call without getting an exception, you should explicitely fail and cause the test to become red.

Alexander Rühl
  • 6,769
  • 9
  • 53
  • 96