Creating a unit test

Let's write a simple unit test to test whether we are able to access the todo data using TodoRepository. The following snippet shows the important details:

    @DataJpaTest
@RunWith(SpringRunner.class)
public class TodoRepositoryTest {

@Autowired
TodoRepository todoRepository;

@Test
public void check_todo_count() {

assertEquals(3, todoRepository.count());

}

}

A few important things to note are as follows:

  • @DataJpaTest: The @DataJpaTest annotation is typically used along with SpringRunner in a JPA repository unit test. This annotation will enable only JPA-related auto-configuration. The test would use an in-memory database by default.
  • @RunWith(SpringRunner.class): A simple alias for SpringJUnit4ClassRunner is SpringRunner. It launches a Spring context.
  • @Autowired TodoRepository todoRepository: Autowires TodoRepository to be used in the test.
  • assertEquals(3, todoRepository.count()): Checks that the count returned is 3. Remember that we inserted three todos in data.sql.
A word of caution—we are taking a shortcut to writing a unit test in the preceding example. Ideally, a unit test should not depend on data that was already created in the database. We will fix this in our future tests.

The Extending Repository interface helps us to expose selected methods in entities.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset