gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:37:38 25 4
gpt4 key购买 nike

我编写了 CRUD 应用程序(笔记本),现在我正在学习如何测试我的代码。我使用模拟编写了一些测试,但在这种情况下,我不知道如何测试例如我的方法 -> addNote。我搜索了一些测试 CRUD 的页面,但没有找到与此类似的代码。

这是我的 Controller :

@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 方法测试的唯一事情是重定向:

@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 来检查它。你能告诉我该怎么做,或者给我链接任何来源,我可以在哪里学习模拟测试吗?

最佳答案

一般来说,您只会测试您编写的代码。可以安全地假设数据库驱动程序可以工作。

如果您想确保记录确实最终进入数据库,请让 Spring 为您 Autowiring 存储库。

@Autowired
private NoteRepository noteRepository;

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

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

关于java - 如何使用hibernate测试将对象保存到数据库的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60005399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com