samedi 25 mars 2017

Spring boot JUnit tests with JPA

I am relatively new to Spring Boot and trying to learn out a few things. I was trying to test a simple JpaRepository functionality. Here is my entity Book class:

@Entity
@Table(name="book")
public class Book {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

private String name;
private String author;

public Book() {

}

public Book(String name, String author){
    this.name = name;
    this.author = author;
}

public long getId(){
    return id;
}

public void setId(long id){
    this.id = id;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name = name;
}

public String getAuthor(){
    return author;
}

public void setAuthor(String author){
    this.author = author;
}

@Override
public String toString(){
    return id + "-" + name + "-" + author;
}

}

And my repository class:

@Repository
public interface BookRepository extends JpaRepository<Book, Long>{

}

And finally my test class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RepoTest {

@Autowired
private BookRepository bookRepository;

@Before
public void setUp() throws Exception {
    bookRepository.deleteAll();
    Book b = new Book("book1", "author1");
    bookRepository.save(b);
}

@Test
public void testFindBook() throws Exception {
    List<Book> books = bookRepository.findAll();
    assertEquals("Did not get all books", 1, books.size());
}
}

I am using Spring boot's default H2 DB as my JPA source. I notice while running the test, the line bookRepository.save(b); executes but it doesn't really save it. Later in the test method, when i retrieve all the books, I see the list is empty. I also also noticed after bookRepository.save(b);, there is no ID generated in the Book entity (it is just 0). Anybody has any idea what's going on?

This is actually part of a very short web app api I am trying to build with Spring boot. If I run the actual api app, the repository methods work quite fine. It's only this test class that I am unable to get passed.

Aucun commentaire:

Enregistrer un commentaire