gpt4 book ai didi

java - 如何为 Postmapping 方法编写 junit 测试

转载 作者:行者123 更新时间:2023-12-01 17:41:07 28 4
gpt4 key购买 nike

我有一个显示带有名称的字段的程序,用户需要输入它们。我该如何测试这个?

User.java - 用户类。

public class User {
@NotEmpty
private String firstName;

@NotEmpty
private String lastName;

public String getAllInfo() {
return this.firstName + '\n' + this.lastName;
}

//getters and setters

}

Store.java - 我的 Controller 类。

public class Store {

...

@PostMapping("/cart/index")
public String getInfo(@Valid final User user, final Model model) {
Store.LOGGER.info("{}", user.getAllInfo());
return "cart/index";
}

@GetMapping(value = "cart/index")
public String index(final Model model) {
model.addAttribute("user", new User());
return "cart/index";
}

...
}

我的 junit 测试现在失败,并且收到以下消息。

null
null
MockHttpServletRequest:
HTTP Method = POST
Request URI = /cart/index
Parameters = {}
Headers = {Accept=[application/json]}

Handler:
Type = app.vlad.store.Store
Method = public java.lang.String app.vlad.store.Store.getInfo(app.vlad.user.User,org.springframework.ui.Model)

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = cart/index
View = null
Attribute = user
value = app.vlad.user.User@248deced
errors = []

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = cart/index
Redirected URL = null
Cookies = []

java.lang.AssertionError:JSON 路径“$.firstName”没有值,异常:json 不能为 null 或为空

我的测试:

StoreTest.java

public class StoreTest {

@Autowired
MockMvc mockMvc;

@Mock
private User user;
@Mock
private Model model;
@Mock
Store store;

@Autowired
List<Products> products;

@Before
public void setup() {

MockitoAnnotations.initMocks(this);
final Store store = new Store(this.products);

this.mockMvc = MockMvcBuilders.standaloneSetup(store).build();

}
@Test
public void testGetInfo() throws Exception {
this.user.setFirstName("Ivan");
this.user.setLastName("Ivanov");

this.mockMvc
.perform(MockMvcRequestBuilders.post("/cart/index")
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("Ivan"))
.andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value("Ivanov"));

}
}

最佳答案

最好的方法是使用 SpringBootTest。这将启动一个 Spring Boot 应用程序,然后您可以使用 RestAssured 之类的东西来调用 API。

该网站详细介绍了所有设置:http://www.masterspringboot.com/getting-started/testing-spring-boot/testing-spring-boot-with-rest-assured

关于java - 如何为 Postmapping 方法编写 junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186207/

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