简单方案:
@Inject
private BookRepository bookRepository;
@Inject
private AuthorRepository authorRepository;
private MockMvc restBookMockMvc;
private Book book;
private Author author;
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
BookResource bookResource = new BookResource();
ReflectionTestUtils.setField(bookResource, "bookRepository", bookRepository);
this.restBookMockMvc = MockMvcBuilders.standaloneSetup(bookResource).build();
}
@Before
public void initTest() {
authorRepository.deleteAll();
author = new Author();
author.setName("Pedro");
authorRepository.save(author);
bookRepository.deleteAll();
book = new Book();
book.setName(DEFAULT_NAME);
book.setAuthor(author);
}
@Test
public void getBook() throws Exception {
// Initialize the database
bookRepository.save(book);
// Get the book
restBookMockMvc.perform(get("/api/books/{id}", book.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(book.getId()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
.andExpect(jsonPath("$.author.name").value(author.getName().toString()));
}
简单测试:
{{1}}
返回状态500和复杂错误:
com.fasterxml.jackson.databind.JsonMappingException:没有序列化程序 上课时发现 org.springframework.data.mongodb.core.convert.DefaultDbRefResolver $ LazyLoadingInterceptor 并且没有发现创建BeanSerializer的属性(以避免 异常,禁用SerializationFeature.FAIL_ON_EMPTY_BEANS)) (通过参考链: com.mycompany.myapp.domain.Book [ “作者”] - GT; com.mycompany.myapp.domain.Author $$ EnhancerByCGLIB $$ e7a6d2fe [ “回调”])
如果将Book类中的Author设置为eager(lazy == false),则可以正常工作。我能做什么?这是MongoDB或Jackson本身的Spring Data中的一个问题吗?
我找到this JIRA,但似乎没有人正在处理这个问题。