Я работаю над учебным пособием по Yabe и столкнулся с некоторым исключением из-за нулевого указателя при тестовом использованииTheCommentsRelation
useTheCommentsRelation
A java.lang.NullPointerException has been caught, null
In /test/BasicTest.java, line 96 :
bobPost.addComment("Jeff", "Nice post");
Hide tracejava.lang.NullPointerException
at models.Post.addComment(Post.java:30)
at BasicTest.useTheCommentsRelation(BasicTest.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
Вот код теста;
@Test
public void useTheCommentsRelation() {
// Create a new user and save it
User bob = new User("bob@gmail.com", "secret", "Bob").save();
// Create a new post
Post bobPost = new Post(bob, "My first post", "Hello world").save();
// Post a first comment
bobPost.addComment("Jeff", "Nice post");
bobPost.addComment("Tom", "I knew that !");
// Count things
assertEquals(1, User.count());
assertEquals(1, Post.count());
assertEquals(0, Comment.count()); // 2 when correct not 0
// Retrieve Bob's post
bobPost = Post.find("byAuthor", bob).first();
assertNotNull(bobPost);
// Navigate to comments
assertEquals(2, bobPost.comments.size());
assertEquals("Jeff", bobPost.comments.get(0).author);
// Delete the post
bobPost.delete();
// Check that all comments have been deleted
assertEquals(1, User.count());
assertEquals(0, Post.count());
assertEquals(0, Comment.count());
}
а вот класс Post с методом addComment в конце.
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
@Entity
public class Post extends Model{
public String title;
public Date postedAt;
@Lob
public String content;
@ManyToOne
public User author;
@OneToMany(mappedBy="post", cascade=CascadeType.ALL)
public List<Comment> comments;
public Post(User author, String title, String content){
this.author = author;
this.title = title;
this.content = content;
this.postedAt = new Date();
}
public Post addComment(String author, String content) {
Comment newComment = new Comment(this, author, content).save();
this.comments.add(newComment);
this.save();
return this;
}
}
Класс комментариев
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
@Entity
public class Comment extends Model{
public String author;
public Date postedAt;
@Lob
public String content;
@ManyToOne
public Post post;
public Comment(Post post, String author, String content){
this.post = post;
this.author = author;
this.content = content;
this.postedAt = new Date();
}
}
Спасибо всем, кто зашел так далеко.