mardi 23 mars 2021

How to write JUnit 5 test for void method that saves record in database?

I have a simple todo app in Spring Boot. I am trying to write a test for createTodo method that saves todo in repository/database. I am getting java.lang.NullPointerException on line todoServiceImpl.createTodo(newTodo);

What am I missing? Is it possible to test it without mocking repository?

TodoServiceImpl.java class

@AllArgsConstructor
@Slf4j
@Service
public class TodoServiceImpl implements TodoService {

    private final TodoRepository todoRepository;

    @Override
    public void createTodo(Todo todo) {
        todoRepository.save(todo);
    }
}

TodoServiceImplTest.java

class TodoServiceImplTest {

    @Mock
    private TodoRepository todoRepository;

    private Todo todo;
    private TodoServiceImpl todoServiceImpl;

    @BeforeEach
    public void setup(){
        todoServiceImpl = new TodoServiceImpl(todoRepository);
    }

    @Test
    @DisplayName("New todo should be saved")
    void createTodoTest() {
        
        // Setup
        Todo newTodo = Todo.builder().id("1").todo("Shopping").build();
        todoServiceImpl.createTodo(newTodo);

        // Expected behavior
        Optional<Todo> todo = todoRepository.findById("1");

        // Assert
        assertEquals(todo.getTodo(), "Shopping");
        assertTrue(todo.isPresent());
    }

Aucun commentaire:

Enregistrer un commentaire