springboot第二章-----打造企業級微信點餐系統(2)--買家類目--03單元測試的使用

一般我是在還沒有進入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條記錄,說明操作成功 

注:在這裏,實體類必須將無參數的構造方法也寫出來,否則會報錯

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章