dimanche 3 mars 2019

Test metod with @RequestParam

I' ve got a problem with test the below method. As you can see I receive status code 400 instead of 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

In method I use @RequestParam use to extract query parameters.

@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";
}
...
}

In program I use Spring Security so I create user to access protected method.

@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());
}

If you have any qestion please let me know. Thx for help ;)

Aucun commentaire:

Enregistrer un commentaire