簡體   English   中英

如何測試使用休眠將對象保存到數據庫的方法?

[英]How to test a method that save an object to the database with hibernate?

我編寫了 CRUD 應用程序(筆記本),現在我正在學習如何測試我的代碼。 我使用模擬編寫了一些測試,但在這種情況下,我知道如何測試我的方法 -> addNote。 我用測試 CRUD 搜索了幾頁,但沒有找到與此類似的代碼。

這是我的控制器:

@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 為您自動裝配存儲庫。

@Autowired
private NoteRepository noteRepository;

這需要配置用於測試的數據庫。 大多數 Spring Boot 配置的系統都帶有 H2 或 HSQL,輕量級內存數據庫。

然后您可以使用存儲庫查詢數據庫,並確保您可以從那里加載保存的條目。

您確實可以使用內存數據庫進行測試,但是如果您更喜歡基於模擬的方法,則可以測試所涉及對象的行為,假設底層 Hibernate 代碼有效:-)

@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 以關閉自動數據源初始化(如果您在沒有運行數據庫的情況下進行測試,則不需要)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM