我编写了一个测试UsersController的单元测试。UsersControllerTest.findUser工作正常,但不能正常运行UsersControllerTest.insertGetModifyDelete。
在测试日志中,我可以看到POST请求与UsersController的任何方法都不匹配,但是我不明白为什么。您能帮我这个吗?
这是我其余的Java类:
@RestController
@RequestMapping("/users")
public class UsersController {
private final UsersService usersService;
@Autowired
public UsersController(UsersService usersService) {
this.usersService = usersService;
}
@GetMapping(value="/{email}", produces="application/json")
public User get(@PathVariable @Email String email) {
return usersService.findByEmail(email);
}
@PostMapping(consumes="application/json", produces="application/json")
@ResponseBody
public ResponseEntity<String> insert(@RequestBody @Valid User user){
usersService.insert(user);
return ResponseEntity.ok(user.getEmail());
}
@DeleteMapping(value="/{email}", consumes="application/json", produces="application/json")
public ResponseEntity<String> delete(@PathVariable @Email String email) {
usersService.delete(email);
return ResponseEntity.ok(email);
}
@PutMapping(value="/{email}", consumes="application/json", produces="application/json")
public ResponseEntity<User> update(@PathVariable @Email String email, @RequestBody @Valid User user) {
usersService.update(email, user);
return ResponseEntity.ok(user);
}
}
我有2种方法的测试。一个正在返回HTTP代码200,但另一个正在返回403。
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WithMockUser(username = "user", roles = "USER")
public class UsersControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void findUser() throws Exception {
mockMvc.perform(get("/users/{email}", new Object[] {"boy@test.com"})).andExpect(status().isOk()).andExpect(jsonPath("$.email", equalTo("boy@test.com"))).andExpect(jsonPath("$.userName", equalTo("boy")));
}
@Test
public void insertGetModifyDelete() throws Exception {
User user = new User("userName", "email@email.com");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
mockMvc.perform(post("/users").content(json).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
mockMvc.perform(put("/users/{email}", new Object[] {user.getEmail()}).content(json)).andDo(print()).andExpect(status().isOk());
mockMvc.perform(delete("/users/{email}", new Object[] {user.getEmail()}).content(json)).andDo(print()).andExpect(status().isOk());
}
}
这是测试的输出:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /users/boy@test.com
Parameters = {}
Headers = {}
Body = null
Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@ca25360: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER}
Handler:
Type = es.tododev.fairtasks.rest.UsersController
Method = public es.tododev.fairtasks.dto.User es.tododev.fairtasks.rest.UsersController.get(java.lang.String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Disposition=[inline;filename=f.txt], Content-Type=[application/json;charset=UTF-8], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = application/json;charset=UTF-8
Body = {"userName":"boy","email":"boy@test.com"}
Forwarded URL = null
Redirected URL = null
Cookies = []
MockHttpServletRequest:
HTTP Method = POST
Request URI = /users
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json]}
Body = {"userName":"userName","email":"email@email.com"}
Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@66944c7c, SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@ca25360: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 403
Error message = Forbidden
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 6.155 s <<< FAILURE! - in es.tododev.fairtasks.rest.UsersControllerTest
[ERROR] insertGetModifyDelete(es.tododev.fairtasks.rest.UsersControllerTest) Time elapsed: 0.028 s <<< FAILURE!
java.lang.AssertionError: Status expected:<200> but was:<403>
at es.tododev.fairtasks.rest.UsersControllerTest.insertGetModifyDelete(UsersControllerTest.java:48)
您可以尝试调试此程序。我认为问题发生在“
mockMvc”对象未自动连接。mockMvc对象应在程序运行之前从WebApplicationContext加载。
@Autowired
private WebApplicationContext webApplicationContext
@Before()
public void setup()
{
//Init MockMvc Object and build
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
共享Api实现类,添加preauthorize-admin,查看所有用户 这是我的JUnit测试,我发送get请求并返回403错误。
问题内容: 我正在尝试制作Sitecraper。我是在本地计算机上制作的,在那儿工作得很好。当我在服务器上执行相同操作时,它显示403禁止错误。我正在使用PHP简单HTML DOM解析器 。我在服务器上收到的错误是这样的: 警告:file_get_contents(http://example.com/viewProperty.html?id=7715888)[function.file- get
使用curl或postman,我得到403禁止: Lambda函数具有以下权限: S3桶具有以下CORS规则:
我使用http://localhost:8080/auth/realms/{realm_name}/protocol/openid-connect/token endpoint创建令牌。 grant_type=client_credentials 客户端-id:------------- 客户端-secret:78296D38-CC82-4010-A817-65C283484E51 现在我想获得r
我正在调用CloudBlobContainer。CreateIfNotExist(请参阅下面的FindOrCreatePrivate ateBlobContainer方法)间接来自Web API服务,但它返回以下403禁止错误消息: 以下是生成错误的代码: 我需要一些帮助来解决此错误的原因。我尝试了以下方法: 已检查要创建的容器的名称是否有效,并且在这种特定情况下,仅由小写字母组成(无特殊或大写字
我试图实现一个单元测试的在与。 我在关注这个链接,它运行良好,但结果为空,当我用浏览器测试我的websocket时,它会发送所需的结果。 让我展示一下我的测试课 } 这是我的< code > WebSocketConfiguration 类 } 这是我从服务器得到的响应 更新: 在下面的答案中添加建议的更改并经过进一步的研究后,我的测试类现在看起来像这样 } 经过这些更改后,我现在可以将堆栈跟踪打