当前位置: 首页 > 面试题库 >

Spring框架测试RESTful Web服务(控制器)离线,即没有服务器,没有数据库

姬昀
2023-03-14
问题内容

我有一个非常简单的RESTful控制器,可以使用并生成JSON。我需要脱机测试此控制器,即没有服务器运行,也没有数据库运行。而且我为无法找到解决方案而发疯。我的初始测试用例将包括:

  • 测试REST URI,即GET,POST,PUT,DELETE-我必须能够根据发送的数据声明返回的数据。
  • 断言将测试JSON数据
    我有以下URI:

  • / pcusers-返回所有用户

  • / pcusers / {id}-返回特定用户
  • / pcusers / create / {pcuser}-将用户添加到数据库
  • / pcusers / update / {pcuser}-更新用户
  • / pcusers / delete / {id}-删除用户

注意:这不是典型的MVC应用程序。我没有意见。我有一个纯REST控制器,它发出JSON并使用JSON格式的数据。

如果有人可以引导我朝正确的方向前进,将不胜感激。

只是为了清楚我的代码是什么样子:

@Controller
@RequestMapping("/pcusers")
public class PcUserController {
    protected static Logger logger = Logger.getLogger(PcUserController.class);

    @Resource(name = "pcUserService")
    private PcUserService pcUserService;

    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public List<PcUser> readAll() {
        logger.debug("Delegating to service to return all PcUsers");
        return pcUserService.readAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, consumes = "application/json", produces = "application/json")
    @ResponseBody
    public PcUser read(@PathVariable String id) {
        logger.debug("Delegating to service to return PcUser " + id);
        return pcUserService.read(id);
    }

    @RequestMapping(value = "/create/{pcUser}", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    @ResponseBody
    public boolean create(@PathVariable PcUser pcUser) {
        logger.debug("Delegating to service to create new PcUser");
        return pcUserService.create(pcUser);
    }

    @RequestMapping(value = "/update/{pcUser}", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    @ResponseBody
    public boolean update(@PathVariable PcUser pcUser) {
        logger.debug("Delegating to service to update existing PcUser");
        return pcUserService.update(pcUser);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    @ResponseBody
    public boolean delete(@PathVariable String id) {
        logger.debug("Delegating to service to delete existing PcUser");
        return pcUserService.delete(id);
    }
}

经过研究,我遇到了一个名为spring-test-mvc的Spring框架。看起来非常有前途,我已经设法在这方面取得了良好的开端。但是现在我有一个新问题。当我向“ / pcusers / {id}”提交GET请求时,控件将传递给负责处理该映射的read方法。在该方法内部,我有一个pcUserService进行读取。现在,问题是当我运行此测试时,真实控制器内的pcUserService实例为NULL;因此,由于无法在NULL对象上调用read而导致崩溃。

这是PcUserControllerTest代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/applicationContextTest.xml")
public class PcUserControllerTest {

    @Autowired
    PcUserService pcUserService;

    @Autowired
    PcUserController pcUserController;

    PcUser pcUser;

    @Before
    public void setUp() throws Exception {
        pcUser = new PcUser("John", "Li", "Weasley", "john", "john", new DateTime());

        pcUserService.create(pcUser);
    }

    public void tearDown() throws Exception {
        pcUserService.delete(pcUser.getId());
    }

    @Test
    public void shouldGetPcUser() throws Exception {
        standaloneSetup(pcUserController)
                .build()
                .perform(get("/pcusers/" + pcUser.getId()).accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}

问题答案:

这是一个建议,应该给你一些想法。我假设你熟悉SpringJUnit4ClassRunner@ContextConfiguration。首先创建一个包含PcUserController和的测试应用程序上下文PcUserService。在PcUserControllerTest下面的示例类中,Jackson用于转换JSON消息,Mockito用于模拟。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(/* Insert test application context here */)
public class PcUserControllerTest {

    MockHttpServletRequest requestMock;
    MockHttpServletResponse responseMock;
    AnnotationMethodHandlerAdapter handlerAdapter;
    ObjectMapper mapper;
    PcUser pcUser;

    @Autowired
    PcUserController pcUserController;

    @Autowired
    PcUserService pcUserServiceMock;

    @Before
    public void setUp() {
        requestMock = new MockHttpServletRequest();
        requestMock.setContentType(MediaType.APPLICATION_JSON_VALUE);
        requestMock.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

        responseMock = new MockHttpServletResponse();

        handlerAdapter = new AnnotationMethodHandlerAdapter();
        HttpMessageConverter[] messageConverters = {new MappingJacksonHttpMessageConverter()};
        handlerAdapter.setMessageConverters(messageConverters);

        mapper = new ObjectMapper();
        pcUser = new PcUser(...);

        reset(pcUserServiceMock);
    }
}

现在,我们拥有创建测试所需的所有代码:

@Test
public void shouldGetUser() throws Exception {
    requestMock.setMethod("GET");
    requestMock.setRequestURI("/pcusers/1");

    when(pcUserServiceMock.read(1)).thenReturn(pcUser);

    handlerAdapter.handle(requestMock, responseMock, pcUserController);

    assertThat(responseMock.getStatus(), is(HttpStatus.SC_OK));
    PcUser actualPcUser = mapper.readValue(responseMock.getContentAsString(), PcUser.class);
    assertThat(actualPcUser, is(pcUser));
}


@Test
public void shouldCreateUser() throws Exception {
    requestMock.setMethod("POST");
    requestMock.setRequestURI("/pcusers/create/1");
    String jsonPcUser = mapper.writeValueAsString(pcUser);
    requestMock.setContent(jsonPcUser.getBytes());

    handlerAdapter.handle(requestMock, responseMock, pcUserController);

    verify(pcUserServiceMock).create(pcUser);
}


 类似资料:
  • 我有一个简单的spring boot应用程序,它从JMS队列中获取消息,并将一些数据保存到日志文件中,但不需要web服务器。有没有办法在没有web服务器的情况下启动spring boot?

  • 我需要了解在我的项目范围内使用autheorizaion服务器的便利性。 我们正在实现我们的服务并将其部署到客户环境中。 客户基础结构已经提供了一种身份验证机制,以便对用户进行身份验证。 此机制拦截所有通信并将用户重定向到“登录”表单。 之后,用户被重定向到我们的服务,我们必须处理和消化它,并使用JWT令牌进行响应。 这是我感到迷茫的地方: 我在想: 使用Spring oauth2 向授权服务器请

  • 我有支持SpringWebSocket的Spring服务器。我想使用STOMP子协议来处理web套接字上的通信,因此STOMPendpoint的配置如下所示: Spring文档和我能找到的关于这个主题的基本资源展示了如何使用SockJS StompJS创建STOMP客户端。它可以工作,但据我所知,根本不需要它——因为STOMP只是一个子协议,我应该能够通过使用STOMP消息语法,基本上从任何web

  • 问题内容: 我正在运行一个Java应用程序,我们将其作为服务器端系统进行分发。我正在尝试编写启动器(这里的“写”有点夸张,我基本上只是复制Java.exe文件,以便我们可以在Windows的进程浏览器中获得所需的名称)。该exe位于应用程序文件树的bin /目录中。 现在,我们在文件树中还有一个jre /目录,这是Java.exe实际所在的位置(我们将产品与Java环境一起交付)。当我使用Java

  • 我正在尝试使用spring-integration-kafka-2.1.0。在我公司的项目中发布。但是,由于下面列出的例外情况,它不起作用:org。springframework。信息。MessageDeliveryException:Dispatcher没有频道“org”的订户。springframework。网状物上下文WebApplicationContext:/order。“奥Kafka”

  • 我使用的是Spring 2.0.1。使用spring云总线发布并安装所有项目(2个服务和云配置服务器) 配置服务器还具有spring云配置监视器 我在我的Git reposroty中编辑文件(使用具有Spring Cloud Config本机配置文件的本地文件)。检测到更改,我在Cloud Config Server中看到以下行: 但是,其他服务都不会收到有关更新密钥的通知。 另一方面,如果我手动