当前位置: 首页 > 知识库问答 >
问题:

spring MVC应用程序Junit测试用例失败

邓毅
2023-03-14

我的JUnit测试用例失败了。行出现错误

mockito.When(BlogEntryService.Find(1L)).ThenReturn(entry);

故障跟踪是

java.lang.NullPointerException位于com.sample.controller.BlogentryControllerTest.GetExistingBlogEntry(BlogentryControllerTest.java:72)位于Sun.Reflect.NativeMethodAccessorImpl.Invoke0(原生方法)位于Sun.Reflect.NativeMethodAccessorImpl.Invoke(未知源)位于Sun.Reflect.DelegatingMethodAccessorImpl.Invoke(未知源)位于java.lang.Reflect.MethodInvoke(TMethodCallbacks.evalue(RunAfterTestMethodCallbacks.Java:83)位于org.springFramework.test.context.junit4.statements.springRepeat.evalue(SpringRepeat.Java:72)位于org.springFramework.test.context.junit4.springJunit4ClassRunner.runchild(SpringJunit4ClassRunner.runchild(SpringJunit4ClassRunner.:233)位于R.Run(ParentRunner.Java:363)在org.springframework.test.context.junit4.springjunit4classrunner上运行(SpringJunit4classrunner.Java:176)在org.eclipse.jdt.internal.junit4.runner.junit4testreference上运行(Junit4testreference.Java:50)在org.eclipse.jdt.internal.junit.runner.testexecution.run(Testexecution.Java:38)在

在我看来,blogEntryService似乎为空

我的密码是

    /**
 * TODO - Describe purpose and operation of class.
 * 
 * <table border="1" cellpadding="0" cellspacing="0" width="100%">
 * <caption align="center">Edit and Version History</caption>
 * <tr><th>Version</th><th>Date</th><th>Author</th><th>Description</th></tr>
 * <tr><td>1.0</td><td>Jan 17, 2016</td><td>EOV537</td><td>Initial creation.</td></tr>
 * </table>
 */
package com.sample.controller;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;

import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.sample.config.ApplicationConfig;
import com.sample.model.BlogEntry;
import com.sample.service.BlogEntryService;

/**
 * @author EOV537 -
 * @since 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class})
@WebAppConfiguration
public class BlogEntryControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private BlogEntryController blogentryconttroller;

    @Mock
    private BlogEntryService blogEntryService;

    @Autowired
    private WebApplicationContext appCtx;

    @Before
    public void setup() {

        MockitoAnnotations.initMocks(BlogEntryControllerTest.class);
        mockMvc = MockMvcBuilders.webAppContextSetup(appCtx).build();
    }

    @Test
    public void getExistingBlogEntry() throws Exception {

        BlogEntry entry = new BlogEntry();
        entry.setId(1L);
        entry.setTitle("Test Title");

        Mockito.when(blogEntryService.find(1L)).thenReturn(entry);

        mockMvc.perform(MockMvcRequestBuilders.get("/rest/blog-entries/1"))
                .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Test Title")))
                .andExpect(
                        MockMvcResultMatchers.jsonPath("$.links[*].href",
                                Matchers.hasItem(Matchers.endsWith("/blog-entries/1"))))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }

    public void getNonExistingBlogEntry() throws Exception {

        Mockito.when(blogEntryService.find(1L)).thenReturn(null);
        mockMvc.perform(MockMvcRequestBuilders.get("/rest/blog-entries/1")).andExpect(
                MockMvcResultMatchers.status().isNotFound());
    }



}

BlogEntryController.java

package com.sample.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sample.assembler.BlogEntryResourceAsm;
import com.sample.model.BlogEntry;
import com.sample.resource.BlogEntryResource;
import com.sample.service.BlogEntryService;

/**
 * @author EOV537 -
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/rest/blog-enteries")
public class BlogEntryController {

    public BlogEntryController() {

    }

    public BlogEntryController(BlogEntryService blogEntryService) {

        this.blogEntryService = blogEntryService;
    }

    private BlogEntryService blogEntryService;

    @RequestMapping(value = "/{blogEntryId}", method = RequestMethod.GET)
    public ResponseEntity<BlogEntryResource> getExsitingBlogEntry(@PathVariable Long blogEntryId) {

        BlogEntry entry = blogEntryService.find(blogEntryId);

        if (entry != null) {
            BlogEntryResource res = new BlogEntryResourceAsm().toResource(entry);
            return new ResponseEntity<BlogEntryResource>(res, HttpStatus.OK);
        } else {
            return new ResponseEntity<BlogEntryResource>(HttpStatus.NOT_FOUND);
        }
    }

}

BlogEntryService.java

package com.sample.service;

import org.springframework.stereotype.Component;

import com.sample.model.BlogEntry;

/**
 * @author EOv537 -
 * 
 * @since 1.0
 */

public interface BlogEntryService {
    public BlogEntry find(Long id);
}

BlogEntryResource.java

package com.sample.resource;

import org.springframework.hateoas.ResourceSupport;

/**
 * @author EOv537 -
 * @since 1.0
 */
public class BlogEntryResource extends ResourceSupport {

    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

BlogEntryResourceasM.java

public class BlogEntryResourceAsm extends ResourceAssemblerSupport<BlogEntry, BlogEntryResource> {

    /**
     * @param controllerClass
     * @param resourceType
     */
    public BlogEntryResourceAsm() {
        super(BlogEntryController.class, BlogEntryResource.class);
        // TODO Auto-generated constructor stub
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.hateoas.ResourceAssembler#toResource(java.lang.Object)
     */
    @Override
    public BlogEntryResource toResource(BlogEntry blogEntry) {

        BlogEntryResource res = new BlogEntryResource();
        res.setTitle(blogEntry.getTitle());
        Link link = ControllerLinkBuilder.linkTo(BlogEntryController.class).slash(blogEntry.getId()).withSelfRel();
        return res;

    }
}

ApplicationConfig.java

/**
 * TODO - Describe purpose and operation of class.
 * 
 * <table border="1" cellpadding="0" cellspacing="0" width="100%">
 * <caption align="center">Edit and Version History</caption>
 * <tr><th>Version</th><th>Date</th><th>Author</th><th>Description</th></tr>
 * <tr><td>1.0</td><td>Jan 17, 2016</td><td>EOV537</td><td>Initial creation.</td></tr>
 * </table>
 */
package com.sample.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @author EOV537 -
 * @since 1.0
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.sample"})
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";

    private static final String VIEW_RESOLVER_SUFFIX = ".jsp";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        // viewResolver.setViewClass(InternalResourceViewResolver.class); // NOSONAR
        viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
        viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);

        return viewResolver;
    }

}

webapplint.java

/**
 * TODO - Describe purpose and operation of class.
 * 
 * <table border="1" cellpadding="0" cellspacing="0" width="100%">
 * <caption align="center">Edit and Version History</caption>
 * <tr><th>Version</th><th>Date</th><th>Author</th><th>Description</th></tr>
 * <tr><td>1.0</td><td>Jan 17, 2016</td><td>EOV537</td><td>Initial creation.</td></tr>
 * </table>
 */
package com.sample.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author EOV537 -
 * @since 1.0
 */
public class WebApplint implements WebApplicationInitializer {
    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ApplicationConfig.class);

        ServletRegistration.Dynamic registration = servletContext.addServlet("DispatcherServlet",
                new DispatcherServlet(rootContext));

        registration.addMapping("/");

        registration.setLoadOnStartup(1);
        servletContext.addListener(new ContextLoaderListener(rootContext));

    }
}

共有1个答案

谷梁承宣
2023-03-14
private MockMvc mockMvc;

@Autowired
@InjectMocks
private BlogEntryController blogentryconttroller;

@Autowired
private WebApplicationContext appCtx;

@Mock
BlogEntryService blogEntryService;

@Before
public void setup() {
    MockitoAnnotations.initMocks(BlogEntryControllerTest.this);
    mockMvc = MockMvcBuilders.webAppContextSetup(appCtx).build();
}

@Test
public void getExistingBlogEntry() throws Exception {
    BlogEntry entry = new BlogEntry();
    entry.setId(1L);
    entry.setTitle("Test Title");
    Mockito.when(blogEntryService.find(1L)).thenReturn(entry);
    mockMvc.perform(MockMvcRequestBuilders.get("/rest/blog-enteries/1"))
            .andExpect(MockMvcResultMatchers.status().isOk());
}
 类似资料:
  • 我有一个简单的测试用例: FileManager中的函数删除 /myDir下的所有文件,然后再次保留文件。 如上所述,我有一个。运行时,我可以按以下顺序查看所有打印: 但是,测试在失败。有两件事我不明白: > 我不明白,它在中失败了,为什么我仍然可以看到打印的,听起来就像是失败了,它没有停止运行,而是继续运行下一个测试?JUnit测试用例中的场景背后发生了什么?? 我不明白的另一件事是为什么tes

  • 我试图使用JUnit servlet在Adobe AEM实例上远程执行一个JUnit测试。供参考的帖子:哪种测试框架适合Adobe CQ5项目? 我已经定义了我的测试案例,并希望能够在这个URL上看到它 这是一个非常简单的测试用例(junit3): 为了使testcase在Sling remote JUnit测试servlet中可用,我需要做什么?

  • 问题是,如果在该类之前运行任何其他测试,则2个存储库测试类将<code>无法加载该测试类的第一个测试用例的ApplicationContext。 Github上的项目“修复单元测试”分支 我使用Mongodb嵌入式数据库对一个spring-boot maven应用程序进行了一系列JUnit组件测试。 其中2个测试类在2个spring存储库上运行单元测试。 但是,由它们自己运行的测试类工作得非常好,

  • 我正在学习JUnit5和测试用例。我使用的是spring boot version'2.2.6.Release和JUnit5,在我的应用程序中,我有一个基于属性文件中的布尔标志进行处理的方法。 \src\main\resources\application.properties 数据库连接属性用于创建数据库连接 ControllerTest.java 默认情况下,该标志为false,因此每次测试用

  • 我是新的火花与Java编程。我有一个从Oracle数据库读取数据的方法。现在我需要帮助编写测试用例使用JUnit框架为下面的代码。 数据集df=spark。read()。格式(“jdbc”)。jdbc(jdbcUrl、dbTable1、connectionProperties);

  • 我写了一个java程序,它基本上和wordle一样。例如,给定2 3x3行 如果猜测与答案匹配(在本例中,索引[0][0]),则将其标记为“绿色” 如果猜测与确切位置的答案不匹配,但它是有效的(例如,答案[1][0]处的答案与猜测[1][0]处的答案不匹配,但是猜测[0][1]处的答案),则将被计为“黄色” 这是我目前拥有的代码。它适用于这个测试用例和除一个之外的所有其他测试用例。我似乎没能抓住我