如何解决Mockito抛出“嵌套异常是java.lang.NullPointerException”的问题?

时间:2019-04-03 14:50:59

标签: java mockito

第一个代码块是Mockito测试代码,然后是实际代码。 我已经检查了代码,它工作正常,但是在使用Mockito测试进行检查时,抛出了空指针异常错误。  有人可以帮我解决这个错误吗?

    @Test
    public void showImage() throws Exception {
        User user = new User();
        UserProfile userProfile = new UserProfile();
        userProfile.setId(1);
        userProfile.setEmailAddress("a@gmail.com");
        userProfile.setFullName("Abhi Mahajan");
        userProfile.setMobileNumber("9876543210");
        user.setProfile(userProfile);
        user.setId(1);
        user.setUsername("Abhi");
        user.setPassword("password1@");

        session = new MockHttpSession();
        session.setAttribute("loggeduser", user);

        Image image = new Image();
        image.setId(1);
        image.setTitle("new");
        image.setDescription("This image is for testing purpose");
        image.setUser(user);

        List<Image> images = new ArrayList<>();
        Tag tag = new Tag();
        tag.setId(1);
        tag.setName("dog");
        images.add(image);
        tag.setImages(images);

        List<Tag> tags = new ArrayList<>();
        tags.add(tag);
        image.setTags(tags);

        Mockito.when(imageService.getImage(Mockito.anyInt())).thenReturn(image);

        this.mockMvc.perform(get("/images/1/new")
                .param("imageId","1")
                .session(session))
                .andExpect(view().name("images/image"))
                .andExpect(content().string(containsString("Welcome User. This is the image")));
    @RequestMapping("/images/{imageId}/{title}")
    public String showImage(@PathVariable("imageId") Integer imageId, Model model) {
        Image image = imageService.getImageByImageId(imageId);

        //Calls the comment Service to get all the comments related to an image & return a list.
        List <Comment> comments = commentService.getCommentsByImageId(imageId);
        model.addAttribute("image", image);
        model.addAttribute("tags",image.getTags());

        //Comment list is added to the model so that it is displayed in the images.html. Here the key is "comments"
        model.addAttribute("comments",comments);
        return "images/image";

0 个答案:

没有答案