标签: spring-mvc-test

如何避免Spring MVC测试的"循环视图路径"异常

我的一个控制器中有以下代码:

@Controller
@RequestMapping("/preference")
public class PreferenceController {

    @RequestMapping(method = RequestMethod.GET, produces = "text/html")
    public String preference() {
        return "preference";
    }
}
Run Code Online (Sandbox Code Playgroud)

我只是尝试使用Spring MVC测试来测试它,如下所示:

@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    private MockMvc mockMvc;
    @Before
    public void setup() {
        mockMvc = webAppContextSetup(ctx).build();
    }

    @Test
    public void circularViewPathIssue() throws Exception {
        mockMvc.perform(get("/preference"))
               .andDo(print());
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下异常:

循环视图路径[preference]:将再次调度回当前处理程序URL [/ preference].检查您的ViewResolver设置!(提示:由于默认的视图名称生成,这可能是未指定视图的结果.)

我发现奇怪的是,当我加载包含模板和视图解析器的"完整"上下文配置时,它工作正常,如下所示:

<bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="webTemplateResolver">
    <property name="prefix" value="WEB-INF/web-templates/" />
    <property name="suffix" value=".html" …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc circular-reference thymeleaf spring-mvc-test

96
推荐指数
10
解决办法
16万
查看次数

模拟MVC - 添加请求参数进行测试

我使用spring 3.2 mock mvc来测试我的控制器.我的代码是

 @Autowired
    private Client client;

     @RequestMapping(value = "/user", method = RequestMethod.GET)
        public String initUserSearchForm(ModelMap modelMap) {
            User user = new User();
            modelMap.addAttribute("User", user);
            return "user";
        }

        @RequestMapping(value = "/byName", method = RequestMethod.GET)
        @ResponseStatus(HttpStatus.OK)
        public
        @ResponseBody
        String getUserByName(@RequestParam("firstName") String firstName,
                                 @RequestParam("lastName") String lastName, @ModelAttribute("userClientObject") UserClient userClient) {

            return client.getUserByName(userClient, firstName, lastName);
        }
Run Code Online (Sandbox Code Playgroud)

我写了以下测试:

@Test
 public void testGetUserByName() throws Exception {
        String firstName = "Jack";
        String lastName = "s";       
        this.userClientObject = client.createClient();
        mockMvc.perform(get("/byName")
                .sessionAttr("userClientObject", this.userClientObject)
                .param("firstName", firstName)
                .param("lastName", lastName) …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-mvc-test

65
推荐指数
2
解决办法
11万
查看次数

使用Spring MVC Test测试Spring MVC @ExceptionHandler方法

我有以下简单的控制器来捕获任何意外的异常:

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity handleException(Throwable ex) {
        return ResponseEntityFactory.internalServerErrorResponse("Unexpected error has occurred.", ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用Spring MVC Test框架编写集成测试.这是我到目前为止:

@RunWith(MockitoJUnitRunner.class)
public class ExceptionControllerTest {
    private MockMvc mockMvc;

    @Mock
    private StatusController statusController;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new ExceptionController(), statusController).build();
    }

    @Test
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception {

        when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception"));

        mockMvc.perform(get("/api/status"))
                .andDo(print())
                .andExpect(status().isInternalServerError())
                .andExpect(jsonPath("$.error").value("Unexpected Exception"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我在Spring MVC基础结构中注册了ExceptionController和一个模拟StatusController.在测试方法中,我设置了从StatusController抛出异常的期望.

抛出异常,但ExceptionController没有处理它.

我希望能够测试ExceptionController获取异常并返回适当的响应.

有关为什么这不起作用以及我应该如何进行此类测试的任何想法?

谢谢.

spring spring-mvc mockito spring-mvc-test

48
推荐指数
3
解决办法
4万
查看次数

隔离控制器测试无法实例化Pageable

我有一个Spring MVC控制器,它使用Spring-Data的分页支持:

@Controller
public class ModelController {

    private static final int DEFAULT_PAGE_SIZE = 50;

    @RequestMapping(value = "/models", method = RequestMethod.GET)
    public Page<Model> showModels(@PageableDefault(size = DEFAULT_PAGE_SIZE) Pageable pageable, @RequestParam(
            required = false) String modelKey) {

//..
        return models;
    }

}
Run Code Online (Sandbox Code Playgroud)

我想使用漂亮的Spring MVC测试支持测试RequestMapping.为了使这些测试保持快速并与所有其他内容隔离开来,我不想创建完整的ApplicationContext:

public class ModelControllerWebTest {
    private MockMvc mockMvc;

    @Before
    public void setup() {
        ModelController controller = new ModelController();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void reactsOnGetRequest() throws Exception {
        mockMvc.perform(get("/models")).andExpect(status().isOk());
    }

}
Run Code Online (Sandbox Code Playgroud)

这种方法适用于其他控制器,它们不期望使用Pageable,但是有了这个,我得到了一个很好的长Spring堆栈跟踪.它抱怨无法实例化Pageable:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is …
Run Code Online (Sandbox Code Playgroud)

testing spring-mvc spring-data spring-mvc-test

37
推荐指数
3
解决办法
1万
查看次数

无法为Spring控制器的JUnit测试加载ApplicationContext

我想写一个测试用例来检查我的控制器(getPersons).这是服务器端代码.我有什么困惑我应该放在里面@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/app-contest.xml"})

其次,我遇到了一些错误:

无法加载应用程序上下文.找不到我在@ContextConfiguration中指定的路径[

我有这样的结构:

 restAPI
    *src/main/java
      com.company.controller
         personController.java
    *Test
      com.company.testController
         personControllerTest.java
    *src
      main
       webapp
         WEBINF
           app-context.xml


@Autowired
private PersonService personService;

@RequestMapping(value="/t2/{yy_id}/person", method=RequestMethod.GET)
@ResponseBody
public PersonInfo[] getPersons() {

    return personService.getPersons();
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:WEB-INF/app-context.xml"})
@WebAppConfiguration
public class PersonControllerTest  {


@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Autowired
private PersonService personService;

@Test
public void getPersons() throws Exception {

    this.mockMvc.perform(get("/t2/1/person")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());

}
Run Code Online (Sandbox Code Playgroud)

跟踪

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:103) …
Run Code Online (Sandbox Code Playgroud)

junit spring spring-mvc junit4 spring-mvc-test

36
推荐指数
2
解决办法
20万
查看次数

单元测试通过Maven,但未通过Cobertura:"期望分支目标65处的堆栈图帧"

我最近在我的Java/Spring-MVC项目中添加了Cobertura插件.奇怪的是,我的所有单元测试都在通过,并且当Maven进行初始测试运行时它们仍然通过,但是当Cobertura尝试运行测试时,它们都会失败,并显示相同的错误消息:

Expecting a stackmap frame at branch target 65 in method xxx.xxxx.xxxx.xxxx;)V at offset 40
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会发生这种情况,甚至不知道如何解决这个问题.我搜索过互联网,但没有发现任何类似的问题.我使用JUnit和spring-test-mvc进行测试.

谁看过这个吗?

java cobertura spring-mvc maven spring-mvc-test

19
推荐指数
2
解决办法
5210
查看次数

在Spring Boot 1.4 MVC测试中使用@WebMvcTest设置MockMvc

MockMVc使用新的Spring Boot 1.4以不同的方式设置了很少的工作代码@WebMvcTest.我理解standaloneSetup方法.我想知道的是设置之间的差异MockMvc,通过WebApplicationContext和自动装配MockMvc.

代码片段1:通过WebApplicationContext设置MockMvc

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = ProductController.class)
public class ProductControllerTest {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;

@MockBean
private ProductService productServiceMock;

@Before
public void setUp() {
     mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void testShowProduct() throws Exception {      

    Product product1 = new Product();
    /*Code to initialize product1*/

    when(productServiceMock.getProductById(1)).thenReturn(product1);

    MvcResult result = mockMvc.perform(get("/product/{id}/", 1))
            .andExpect(status().isOk())
            /*Other expectations*/
            .andReturn();
  }
}
Run Code Online (Sandbox Code Playgroud)

根据WebMvcTestAPI文档,默认情况下,使用@WebMvcTest注释的测试也将自动配置Spring Security和MockMvc.所以,我希望这里有一个401 Unauthorized状态代码,但测试通过200状态代码.

接下来,我尝试了自动接线MockMvc,但测试失败了401 …

spring-mvc spring-mvc-test spring-boot

16
推荐指数
3
解决办法
2万
查看次数

@WebAppConfiguration没有注入

我正在尝试使用Spring 3.2.1创建spring-mvc测试.在一些教程之后,我认为这将是直截了当的.

这是我的测试:

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = { JpaTestConfig.class } )

@WebAppConfiguration
public class HomeControllerTest {

@Resource
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Test
public void testRoot() throws Exception {
    mockMvc.perform(get("/").accept(MediaType.TEXT_PLAIN)).andDo(print())
            // print the request/response in the console
            .andExpect(status().isOk()).andExpect(content().contentType(MediaType.TEXT_PLAIN))
            .andExpect(content().string("Hello World!"));
}

@Before
public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
Run Code Online (Sandbox Code Playgroud)

这是我的相关pom.xml:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
    <scope>test</scope>
<exclusions>
    <exclusion>
        <artifactId>hamcrest-core</artifactId>
        <groupId>org.hamcrest</groupId>
    </exclusion>
</exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.1.RELEASE</version> …
Run Code Online (Sandbox Code Playgroud)

unit-testing spring-mvc spring-mvc-test

15
推荐指数
3
解决办法
2万
查看次数

如何测试DeferredResult timeoutResult

从一段时间以前,我正在按照Spring博客实施长轮询.

这里我的转换方法具有与以前相同的响应签名,但它现在使用长轮询而不是立即响应:

private Map<String, DeferredResult<ResponseEntity<?>>> requests = new ConcurrentHashMap<>();

@RequestMapping(value = "/{uuid}", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<?>> poll(@PathVariable("uuid") final String uuid) {
    // Create & store a new instance
    ResponseEntity<?> pendingOnTimeout = ResponseEntity.accepted().build();
    DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(TWENTYFIVE_SECONDS, pendingOnTimeout);
    requests.put(uuid, deferredResult);

    // Clean up poll requests when done
    deferredResult.onCompletion(() -> {
        requests.remove(deferredResult);
    });

    // Set result if already available
    Task task = taskHolder.retrieve(uuid);
    if (task == null)
        deferredResult.setResult(ResponseEntity.status(HttpStatus.GONE).build());
    else
        // Done (or canceled): Redirect to …
Run Code Online (Sandbox Code Playgroud)

spring-mvc spring-mvc-test spring-web

14
推荐指数
2
解决办法
4179
查看次数

Spring Boot集成测试:@AutoConfigureMockMvc和上下文缓存

我正在使用Spring Boot 1.5.1构建非常基本的Web应用程序,并希望创建用于检查REST端点的集成测试.正如文档所推荐的那样,可能会使用MockMvc.

这是非常简单的测试类:

package foo.bar.first;

import ...

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest1 {

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private MockMvc mvc;

    @Test
    public void shouldStartWebApplicationContext() {
        assertThat(context).isNotNull();
    }

    @Test
    public void shouldReplyToPing() throws Exception {
        mvc.perform(get("/ping"))
                .andExpect(status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)

正如所料,它启动完整的应用程序上下文并运行测试.

后来我创建了其他类似的测试类,并注意到每个测试类都启动了全新的应用程序上下文.实验表明,上下文仅在来自同一包的测试类之间共享.

例如,如果多次复制相同的测试类,则上下文如下:

foo.bar
  first
    ApplicationTest1 (shared context)
    ApplicationTest2 (shared context)
  second
    ApplicationTest3 (brand new context)
Run Code Online (Sandbox Code Playgroud)

进一步的调查表明它与@AutoConfigureMockMvc注释有关.如果删除了注释和MockMvc相关的测试用例,则所有三个类都成功共享相同的上下文.

那么问题是如何使用MockMvc获取所有测试的共享上下文

注意:其他资源建议MockMvcBuilders.webAppContextSetup(context).build()用于获取MockMvc实例,但它对我不起作用(处理Web请求时不涉及过滤器).

junit spring-mvc spring-mvc-test spring-boot

12
推荐指数
1
解决办法
5316
查看次数