在创建一个api删除用户的电子邮件地址时,我们收到406错误。我们通过在mvc-dispatcher.xml
文件中设置contentNegotiation来解决此问题:
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"
p:favorPathExtension="false"
p:favorParameter="true"
p:parameterName="response-type"
p:ignoreAcceptHeader="false">
<property name="defaultContentType" value="application/json"/>
</bean>
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager"
/>
api网址为:/users/{emailId:.+}
此问题已解决,并且api正常运行,但是在编写测试用例时无法使它正常工作。
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(
{
"classpath:configuration/mvc-dispatcher.xml"
}
)
@Transactional
public class UserControllerTest {
@Test
public void deleteUser() throws Exception {
User user = make(a(UserMaker.User));
userRepository.save(user);
UserResource userResources = new UserResource(user);
String emailId = userResources.getEmailId();
String API = "/users/" + emailId;
mockMvc.perform(
delete(API)
.contentType(MediaType.APPLICATION_JSON_VALUE)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
}
我得到以下输出:
deleteUser(com.walkover.user.api.controller.UserControllerTest) Time
elapsed: 0.053 sec <<< FAILURE!
java.lang.AssertionError: Status expected:<200> but was:<406>
答案 0 :(得分:0)
好吧,很明显Http代码406尚未设置可接受的标头。检查服务所需的标头是什么?设置请求标头并执行,它将起作用