0

So it may be, that I have a basical missunderstanding in Java. Lets assume I have a method, which gets an Object as parameter. Does it even make sense or is it possible to test, what happens, when I pass null?:

     @Test(expected = NullPointerException.class)
        public void test_nullPointer() {
            doThrow(new NullPointerException()).when(myService).getSomeInformation(null);
            classUnderTest.doSomething(null);
            verify(myService).getSomeInformation(isNull(myObject.class));
        }

Of course this doesn't work. But it's what I am currently trying to realise, if of course it even makes sense to do so.

Edit: The myService.getSomeInformation(myObject obj) gets called, when I call classUnderTest.doSomething(myObject obj). So it passes the obj to myService to return something based on the obj.

The thing is, I just want to ensure, that if any other class would call classUnderTest.doSomething(null), a uncatched NullPointerException is thrown. It's just the question if this is even necessary, testing this behaviour. And if yes, how to realise it.

user5417542
  • 3,146
  • 6
  • 29
  • 50
  • This code: `doThrow(new NullPointerException()).when(myService).getSomeInformation(null);` means that when the `getSomeInformation` method of `myService` mock will be called with a `null` parameter, an exception will be thrown. We are missing some code to see what mught be wrong (is it really a mock? Is the method called? etc.) – Tunaki Oct 20 '15 at 12:14
  • 1
    Your verify statement will not be processed (because the JVM has thrown the NPE in the previous line). – Stormcloud Oct 20 '15 at 12:22
  • Edited some more information. – user5417542 Oct 20 '15 at 12:28

1 Answers1

0

This works (assuming someService is mock)...

    @Test(expected = NullPointerException.class)
    public void test() throws SQLException {
        when( someService.getSomething( null ) ).thenThrow( new NullPointerException() );
        this.someService.getSomething( null );
    }

...but if you start testing your NPEs, you should probably start by handling it better than simply throwing NPEs around (and then test that better behavior).

Does it make sense? Honestly, I doubt it. NPEs are something that happens if you didn't check enough. I personally don't consider an NPE to be something that SHOULD be thrown, just something that happens because I messed up other checks. An IllegalArgumentException at the beginning of the (public) method would probably better (and at least more clear) than an NPE somewhere deep in the code.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
  • OT a little: Be prepared for the standard library to throw NPEs as that is the design recommended by Bloch, see this answer http://stackoverflow.com/questions/3881/illegalargumentexception-or-nullpointerexception-for-a-null-parameter/8160#8160 Of course as that question shows, there is certainly not a consensus in the community on this one. – Jonah Graham Oct 20 '15 at 13:12