我正试图在Spring启动应用程序中使用Spring休息时使用MockMVC来测试我的其余控制器类的put方法。测试总是没有给我这个错误
java.lang.AssertionError:预期状态:< 200>但是:< 400>
下面的是其余的控制器类
package com.store.rest.controller;
import java.time.LocalDate;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.store.domain.Product;
import com.store.exception.ProductNotFoundException;
import com.store.repository.ProductRepository;
import com.store.rest.representation.ProductCollectionRepresentation;
@RestController
@Transactional
public class ProductController {
@Autowired
@Qualifier("productRepository")
private ProductRepository productRepository;
@RequestMapping(value = "/product/id/{id}", method = RequestMethod.GET)
public Product getProductById(@PathVariable("id") Long productId)
throws ProductNotFoundException {
Product product = productRepository.findOne(productId);
if (product == null) {
throw new ProductNotFoundException("the product id " + productId
+ " is not existed");
}
return product;
}
@RequestMapping(value = "/product/name/{name}", method = RequestMethod.GET)
public Product getProductByName(@PathVariable("name") String productName)
throws ProductNotFoundException {
Product product = productRepository.findByProductName(productName);
if (product == null) {
throw new ProductNotFoundException("the product name "
+ productName + " is not existed");
}
return product;
}
@RequestMapping(value = "/product/sku/{sku}", method = RequestMethod.GET)
public Product getProductBySKU(@PathVariable("sku") String productSKU)
throws ProductNotFoundException {
Product product = productRepository.findByProductSku(productSKU);
if (product == null) {
throw new ProductNotFoundException("the product Sku" + productSKU
+ " is not existed");
}
return product;
}
@RequestMapping(value = "/products", method = RequestMethod.GET)
public ProductCollectionRepresentation getProducts(
@RequestParam(required = false) Integer first,
@RequestParam(required = false) Integer last) {
List<Product> products = productRepository.findAll();
if (products == null) {
throw new ProductNotFoundException(
"no Products are available in the store");
}
if (first != null && (last != null && last < products.size())) {
return new ProductCollectionRepresentation(products.subList(
first - 1, last));
} else if (first != null && (last == null || last > products.size())) {
return new ProductCollectionRepresentation(products.subList(
first - 1, products.size()));
}
return new ProductCollectionRepresentation(products);
}
@RequestMapping(value = "/product/id/{id}", method = RequestMethod.PUT)
public Product updateProductById(@RequestBody Product product,
@PathVariable("id") long productId) {
Product foundProduct = productRepository.findOne(productId);
if (foundProduct == null) {
throw new ProductNotFoundException("the product Id" + productId
+ " is not existed to update it");
}
String productSku = product.getProductSku() != null?product.getProductSku():foundProduct.getProductSku();
String productName = product.getProductName() != null?product.getProductName():foundProduct.getProductName();
Product UpdatedProduct = new Product(foundProduct.getId(),
productSku, productName,
LocalDate.now());
UpdatedProduct = productRepository.saveAndFlush(UpdatedProduct);
return UpdatedProduct;
}
}
我的测试是
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class ProductControllerTest {
private MediaType contentType = new MediaType( MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
@InjectMocks
private ProductController productController;
@Mock
private ProductRepository productRepository;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(productController)
.setControllerAdvice(new RestErrorHandlerAdvice()).build();
}
@Test
public void testUpdateProductByIdExisted() throws Exception {
Product product = new Product(1L,"SKU_A", "ProductA", LocalDate.of(2016, 8, 16));
Product updatedProduct = new Product("SKU_A", "Product_A1");
when(productRepository.findOne(1L)).thenReturn(product);
this.mockMvc.perform(
MockMvcRequestBuilders.put("/product/id/{id}",1L)
.contentType(contentType)
.accept(contentType)
.content(asJsonString(updatedProduct)))
.andExpect(status().isOk())
.andExpect(jsonPath("productSku", is("SKU_A")))
.andExpect(jsonPath("productName", is("Product_A1")));
verify(productRepository, times(1)).saveAndFlush(product);
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
域类产品
@Entity
@Table(name="product")
@XmlRootElement
public class Product implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "product_id")
private long productId;
@Column(name = "product_sku", nullable=false, unique=true)
private String productSku;
@Column(name = "product_name",nullable=false, unique=true)
private String productName;
@Column(name = "product_created")
@Convert(converter = LocalDateConverter.class)
private LocalDate productCreated;
@Column(name = "product_lastupdate")
@Convert(converter = LocalDateConverter.class)
private LocalDate productLastUpdated;
public Product(){
}
public Product(String sku,String productName){
this.productSku = sku;
this.productName = productName;
this.productCreated = LocalDate.now();
this.productLastUpdated = LocalDate.now();
}
public Product(String sku,String productName, LocalDate createdDate){
this.productSku = sku;
this.productName = productName;
this.productCreated = createdDate;
this.productLastUpdated = createdDate;
}
public Product(Long id,String sku,String productName, LocalDate createdDate){
this.productId = id;
this.productSku = sku;
this.productName = productName;
this.productCreated = createdDate;
this.productLastUpdated = createdDate;
}
public long getId() {
return productId;
}
public String getProductSku() {
return productSku;
}
public void setProductSku(String productSku) {
this.productSku = productSku;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public LocalDate getProductCreated() {
return productCreated;
}
public void setProductCreated(LocalDate productCreated) {
this.productCreated = productCreated;
}
public LocalDate getProductLastUpdated() {
return productLastUpdated;
}
public void setProductLastUpdated(LocalDate productLastUpdated) {
this.productLastUpdated = productLastUpdated;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((productName == null) ? 0 : productName.hashCode());
result = prime * result
+ ((productSku == null) ? 0 : productSku.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (productName == null) {
if (other.productName != null)
return false;
} else if (!productName.equals(other.productName))
return false;
if (productSku == null) {
if (other.productSku != null)
return false;
} else if (!productSku.equals(other.productSku))
return false;
return true;
}
@Override
public String toString() {
return "Product [productId=" + productId + ", productSku=" + productSku
+ ", productName=" + productName + ", productCreated="
+ productCreated + ", productLastUpdated=" + productLastUpdated
+ "]";
}
}
任何想法为什么我在测试中获得400状态而不是200状态?