相关疑难解决方法(0)

java.lang.AssertionError:junit Spring MVC Controller时未设置内容类型?

我正在使用JUnit来测试我的Spring MVC控制器.下面是我的方法,它返回一个index.jsp页面并Hello World在屏幕上显示 -

@RequestMapping(value = "index", method = RequestMethod.GET)
public HashMap<String, String> handleRequest() {
    HashMap<String, String> model = new HashMap<String, String>();

    String name = "Hello World";
    model.put("greeting", name);

    return model;
}
Run Code Online (Sandbox Code Playgroud)

以下是我对上述方法的JUnit测试:

public class ControllerTest {

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");

        this.mockMvc = standaloneSetup(new Controller()).setViewResolvers(viewResolver).build();
    }

    @Test
    public void test01_Index() throws Exception {

    mockMvc.perform(get("/index")).andExpect(status().isOk()).andExpect(content().contentType("application/json"))
        .andExpect(jsonPath("$.greeting").value("Hello World"));

    }
}
Run Code Online (Sandbox Code Playgroud)

当我调试它时,junit上面运行正常但是当我运行junit时run as junit,它给了我这个错误 …

java junit spring spring-mvc spring-test-mvc

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

java.lang.AssertionError:即使将内容类型设置为json/application,也未设置内容类型

之前已经问过这个问题并且我已经尝试了他们的解决方案,但这对我不起作用,我正在使用MockMvc单元测试我的休息呼叫的内容类型.我得到这个例外:

java.lang.AssertionError:未设置内容类型

我正在使用produces属性在我的搜索方法中设置它.

这是我初始化模拟的方法:

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    ReflectionTestUtils.setField(restController, "luceneSearchEnabled", true);
    mockMvc = standaloneSetup(restController).build();
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试方法:

@Test
public void pmmSearchContentTypeTest() throws Exception { 
    mockMvc
          .perform(get("/api/v1/pmm").contentType(MediaType.APPLICATION_JSON))
          .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE)
          .andReturn();
}
Run Code Online (Sandbox Code Playgroud)

这是我设置内容类型的搜索方法:

@RequestMapping(value = "/api/" + REST_API_VERSION + "/" + ONE_INTERFACE, method = RequestMethod.GET, produces ={MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public String pmmSearch() { ... }
Run Code Online (Sandbox Code Playgroud)

我不知道这里有什么问题.

java spring spring-mvc spring-test

6
推荐指数
1
解决办法
5608
查看次数

标签 统计

java ×2

spring ×2

spring-mvc ×2

junit ×1

spring-test ×1

spring-test-mvc ×1