一般我是在还没有进入service的时候写的测试类。
第一步:实体类,这里我觉得在添加或查询时,每次都要set,很麻烦,所以我用了构 造方法
package com.fjz.vxsell.bean;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;
/**
* @author 冯师兄
* @date 2020-04-27 15:58
*/
@Entity
@DynamicUpdate
@Data
public class ProductCategory {
@Id
@GeneratedValue
private Integer categoryId;//类目id
private String categoryName;//类目名称
private Integer categoryType;//类目编号
public ProductCategory() {
}
public ProductCategory(String categoryName, Integer categoryType) {
this.categoryName = categoryName;
this.categoryType = categoryType;
}
}
第二步:repository
package com.fjz.vxsell.repository;
import com.fjz.vxsell.bean.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @author 冯师兄
* @date 2020-04-27 16:31
*/
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {
//用 多个categoryType查询,结果为list
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
第三步:测试类
package com.fjz.vxsell.repository;
import com.fjz.vxsell.bean.ProductCategory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryRepositoryTest {
@Autowired
private ProductCategoryRepository repository;
/**
* 添加
*/
@Test
public void save() {
ProductCategory productCategory = new ProductCategory("垃圾站",5);
ProductCategory result = repository.save(productCategory);
//使用断言,result不等于null,等同于Assert.assertNotEquals(0, result);
Assert.assertNotNull(result);
}
/**
* 用多个CategoryType查询
*/
@Test
public void findByCategoryTypeIn(){
List<Integer> list = Arrays.asList(3,5,7);
List<ProductCategory> result = repository.findByCategoryTypeIn(list);
//这里我们期望查询的结果大于0,相当于不期望为0
Assert.assertNotEquals(0,result.size());
}
}
结果:因为这里查询的结果是list,所以这里打了断点
查询出3条记录,说明操作成功
注:在这里,实体类必须将无参数的构造方法也写出来,否则会报错