gpt4 book ai didi

java - 用于单元测试的模拟 Spring Controller

转载 作者:行者123 更新时间:2023-12-02 09:57:05 32 4
gpt4 key购买 nike

我正在尝试测试属于 mvc Controller 一部分的剩余调用。我的单元测试当前返回 404 错误代码,而不是 200 状态代码,这将确定请求已成功发送。

这是我正在尝试测试的方法的签名:

@PreAuthorize("hasRole('ROLE_SSL_USER')")
@PostMapping(value = "/employee", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> postEmployee(HttpEntity<String> httpEntity, @RequestHeader("DB-Client-Id") String clientId,
@RequestHeader("X-Forwarded-Client-Dn") String dn) throws IOException, ValidationException {}

这是我的单元测试类:

public class ControllerTest {

@InjectMocks
private Controller aController;

private MockMvc mockMvc;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(aController).build();
}

@Test
public void PostEmpTest() {

try {
this.mockMvc.perform(post("/employee")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

我是否在 Perform() 调用中遗漏了某些内容,导致出现 404 错误请求代码?

最佳答案

我使用这样的 Controller 测试代码

@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
@AutoConfigureWebClient
public class ControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void entityTypes() throws Exception {
String json = "...";
mockMvc.perform(
post("URL")
.contentType(APPLICATION_JSON_UTF8)
.content(json))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
;
}
}

尝试一下 - 我希望它会有所帮助。

PS:另外,我不确定,但看起来您需要将 @RequestBody 添加到 Controller 方法声明中:

public ResponseEntity<Object> postEmployee(
@RequestBody HttpEntity<String> httpEntity,
@RequestHeader("DB-Client-Id") String clientId,
@RequestHeader("X-Forwarded-Client-Dn") String dn) throws IOException, ValidationException {}

关于java - 用于单元测试的模拟 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927592/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com