我在测试以下方法时遇到问题。如您所见,我收到的状态码为400,而不是200。
information from Test:
Type = shop.web.ProductController
Method = public java.lang.String
shop.web.ProductController.getProductById(java.lang.Long,org.springframework.ui.Model)
Async:
Async started = false
Async result = null
Resolved Exception:
Type=org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
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:"SAMEORIGIN"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<400>
Expected :200
Actual :400
在方法中,我使用@RequestParam来提取查询参数。
@Controller
@RequestMapping("/products")
public class ProductController {
...
@GetMapping("/product")
public String getProductById(@RequestParam(value="id") Long productId, Model model) {
model.addAttribute("product", productService.getProductById(productId));
model.addAttribute("newOrder", new Order(productId));
return "product";
}
...
}
在程序中,我使用Spring Security,因此我创建了用户来访问受保护的方法。
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ProductRepository productRepository;
@MockBean
private UserRepository userRepository;
@MockBean
private PasswordEncoder passwordEncoder;
@MockBean
private ProductService productService;
private List<Product> productcs;
@Before
public void setup() {
productcs = Arrays.asList(
new Product("iPhone 5",new BigDecimal(3000),"iPhone 8 cali",
"Apple","SmartPhone",30,0,false, NEW),
new Product("Samsung Galaxy 5",new BigDecimal(2000),"Samsung 8 cali",
"Samsung","SmartPhone",30,0,false, NEW)
);
when(productRepository.findAll())
.thenReturn(productcs);
when(productRepository.findByCategory("SmartPhone")).
thenReturn(productcs);
when(productRepository.findByUnitPriceBetween(new BigDecimal(1500),new BigDecimal(2500))).
thenReturn(Arrays.asList(new Product("Samsung Galaxy 5",new BigDecimal(2000),"Samsung 8 cali",
"Samsung","SmartPhone",30,0,false, NEW)));
when(userRepository.findByUsername("testuser"))
.thenReturn(new User("testuser","testpass"));
when(productService.getProductById(1L))
.thenReturn(new Product("iPhone 5",new BigDecimal(3000),"iPhone 8 cali",
"Apple","SmartPhone",30,0,false, NEW));
}
@Test
@WithMockUser(username="testuser", password="testpass", authorities="ROLE_USER")
void getProductById() throws Exception{
mockMvc.perform(get("/products/product")
.param("id","1L"))
.andExpect(status().isOk());
}
答案 0 :(得分:0)
您正在传递字符串"1L"
作为参数值。不能解析为Long。使用"1"
。