-1

I have a class that looks like this:

@Service
@Transactional
public class BookServiceImpl implements BookService {
    @Autowired
    private BookRepository bookRepository;

    public void removeOne(Long id) throws DataAccessException {
        bookRepository.delete(id);
    }
}

My exception tests looks like this

@Rule
public final ExpectedException exception = ExpectedException.none();

@Test
public void removeOneThrowsNullPointerException() {
    BookService foo = new BookServiceImpl();

    exception.expect(NullPointerException.class);
    foo.removeOne(1L);
}

Now this tests passes but first why must the BookService class be instantiated and normally this test would pass if was a simple unit test because we have a book with id 1L but now its a null, I have read articles on @Rule, what is actually going on? and is this a proper test for finding exception in the method removeOne()?

0

1 Answer 1

1

Probably you have NullPointerException on the bookRepository in your service. By other word it is not autowired properly. Did you try to debug this test to see what exactly object is null?

There are 2 possible ways to write correct tests:

  1. For integration testing you need to care about autowire all dependencies, read about Spring and testing.
  2. For pure unit testing you need to care about mocking of all dependencies.

The usage of @Rule is correct way to test exceptional cases.

UPDATE: The simplest way to test exceptional cases for service layer is to mock your repository class to throw the DataAccessException and inject it into the service class:

@Rule
public final ExpectedException exception = ExpectedException.none();

@Test
public void removeOneThrowsDataAccessException() {
    BookRepository mockedRepository = Mock(BookRepository.class);
    when(mockedRepository.get(1L)).thenThrow(new DataAccessException());

    BookService foo = new BookServiceImpl(mockedRepository);

    exception.expect(DataAccessException.class);

    foo.removeOne(1L);
}
Sign up to request clarification or add additional context in comments.

13 Comments

my question is not about null pointer , this occures when we dont have an empty instance or variable , but normally i was given a task to write exception test for about 10 service logic that are working correctly , so how is that i should return an exception in this test ? also i am testing the scenario where i gave a null parameter to a method
The simplest way to test exceptional cases for service layer is to mock your repository class to throw the DataAccessException and inject it into service class.
can you show a code snippet on what u mean thank you
See the updated my post.
could not import the Mock u used in test @Dmytro maslenko
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.