vendredi 31 janvier 2020

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

I wrote CRUD app (Notebook), and now I'm learning how to test my code. I wrote some tests using mocks, but in this case Idk how to test for example my method -> addNote. I searched a few pages with testing CRUD but I have not found similar code to this.

This is my 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";
}

And the only thing I was able to test with the addNote method was redirection:

@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"));

}

As you can see, I also use param, which creates a new object in my database, but I don't know how to check it using test. Can you tell me how can I do it, or link me any source, where I can learn testing with mocks?

Aucun commentaire:

Enregistrer un commentaire