【发布时间】:2020-04-13 10:47:27
【问题描述】:
我有一个程序,它显示带有名称的字段,用户需要输入它们。我该如何测试?
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 - 我的控制器类。
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"));
}
}
【问题讨论】:
-
有几种方法,你试过了吗?