0

I'm trying create tests for my progressBar class, but i can't get access to MySQL database in standard way. How I should create connection with DB in tests?

public class progressBarTest {

@Resource(name = "jdbc/movie_user_database")
private static DataSource dataSource;

@BeforeClass
public static void setUpClass() throws Exception {
    MovieDatabaseUtil.getInstance().setDataSource(dataSource);
    System.out.println("DataSource created!");

}

@AfterClass
public static void tearDownClass() throws Exception {

}


@Test
public void getMovies() {
    List<Movie> movies = MovieDatabaseUtil.getInstance().getMovies();
    for (Movie m : movies
    ) {
        System.out.println(m.getTitle());
    }
}


@Test
public void progressCalculatorMovies() {
    ProgressBar progressBar = new ProgressBar();
    assertEquals(30, progressBar.progressCalculatorMovies());
}

}

Of course after running i've got NullPointerException. I added some records to db before running test.

Franz17
  • 51
  • 1
  • 8
  • 3
    What type of test are you looking to write here? Unless this is intended to be some kind of end to end test, I'd suggest mocking. – Nick DeFazio Oct 11 '18 at 14:11
  • That's my first time with JUnit. I'm trying to learn sth about creating unit tests by adding it to my existing application. – Franz17 Oct 11 '18 at 14:17

1 Answers1

1

You should mock the connection and not try to test the connection directly. Mocking and stubbing allows you to better test the class under test, and not get distracted by issues with the database connection. It also allows you to test without mucking around with actual database entries.

I highly recommend Mockito (https://site.mockito.org/) framework as tool for mocking such interfaces.

Kenny
  • 316
  • 1
  • 9