首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用hibernate测试将对象保存到数据库的方法?

如何使用hibernate测试将对象保存到数据库的方法?
EN

Stack Overflow用户
提问于 2020-01-31 22:02:38
回答 2查看 539关注 0票数 0

我写了CRUD应用程序(Notebook),现在我正在学习如何测试我的代码。我使用mock编写了一些测试,但在本例中,Idk如何测试我的方法-> addNote。我用测试CRUD搜索了几个页面,但我没有找到与此类似的代码。

这是我的控制器:

代码语言:javascript
运行
复制
@Controller
public class NoteController {


private NoteService noteService;

@Autowired
public NoteController(NoteService noteService) {
    this.noteService = noteService;
}

@GetMapping("/notebook")
public String getNotebook(Model model)
{
    model.addAttribute("notes",noteService.getNotes());
    model.addAttribute("newNote",new Note());
    return "main-view";
}

@PostMapping("/notebook/add-note")
public String addNote(Model model, @ModelAttribute Note note)
{
    if(note.getTitle()==null || note.getTitle() == null)
    {
        model.addAttribute("errorMessage","You have to fill in the title and text, to save the note");
    }
    else {
        noteService.saveNote(note.getTitle(), note.getText());
    }
    return "redirect:/notebook";
}

@GetMapping("/notebook/{id}")
public String getNoteById(Model model, @PathVariable Long id)
{
    Note note = null;
    try {
        note = noteService.findNoteById(id);
    }
    catch (Exception e)
    {
        model.addAttribute("errorMessage","Note not found");
    }
    model.addAttribute("note", note);
    return "show-note";
}

@RequestMapping(value = "/notebook/{id}/edit", method = {RequestMethod.POST,RequestMethod.GET})
public String editNoteById(Model model, @PathVariable Long id,@ModelAttribute Note updatedNode)
{
    if(updatedNode!=null)
    {
        noteService.update(updatedNode);
    }
    Note note = null;
    try {
        note = noteService.findNoteById(id);
    }
    catch (Exception e)
    {
        model.addAttribute("errorMessage","Note not found");
    }
    model.addAttribute("edit",true);
    model.addAttribute("note", note);

    return "show-note";
}

@PostMapping("/notebook/{id}/delete")
public String deleteNote(@PathVariable Long id)
{
    noteService.deleteNote(id);
    return "redirect:/notebook";
}

我唯一能用addNote方法测试的就是重定向:

代码语言:javascript
运行
复制
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApiTest {

@Autowired
MockMvc mockMvc;

@Test
public void addNote() throws Exception {

    mockMvc.perform(post("/notebook/add-note")
            .param("title","mmtitle")
            .param("text", "mmtext"))
            .andExpect(redirectedUrl("/notebook"));

}

如您所见,我还使用了param,它在我的数据库中创建了一个新对象,但是我不知道如何使用test来检查它。你能告诉我如何才能做到这一点,或者链接我的任何资源,在那里我可以学习使用mock进行测试?

EN

回答 2

Stack Overflow用户

发布于 2020-01-31 22:11:52

通常,您只需要测试自己编写的代码。可以安全地假设数据库驱动程序可以工作。

如果您希望确保记录确实在数据库中结束,请让Spring自动为您创建存储库。

代码语言:javascript
运行
复制
@Autowired
private NoteRepository noteRepository;

这需要配置用于测试的数据库。大多数Spring Boot配置的系统都带有H2或HSQL,轻量级内存数据库。

然后,您可以使用存储库查询数据库,并确保可以从那里加载保存的条目。

票数 0
EN

Stack Overflow用户

发布于 2020-01-31 23:21:11

您确实可以使用内存中的数据库进行测试,但如果您更喜欢基于模拟的方法,则可以测试所涉及的对象的行为,前提是底层Hibernate代码可以工作:-)

代码语言:javascript
运行
复制
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class ControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private NoteRepository noteRepository;

  @Test
  public void addNote() throws Exception {

    String json = "{" +
            "\"id\":1," +
            "\"name\":\"my note\"" +
            "}";

    this.mockMvc.perform(post("/notebook/add-note")
            .contentType(MediaType.APPLICATION_JSON).content(json)
            .andExpect(status().isOk());

    verify(noteRepository, times(1)).save(isA(Note.class));

}

使用NoteRepository模拟,您可以验证调用了哪些方法以及调用了多少次。

您需要排除DataSourceAutoConfiguration以关闭自动数据源初始化(如果您在没有运行数据库的情况下进行测试,则不希望这样做)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60005399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档