簡體   English   中英

如何對 JPA idclass 進行單元測試

[英]How to Unit test JPA idclass

我正在努力編寫/理解 Intellij IDE 中 JPA 繼承 @idClass 的單元測試。 運行代碼覆蓋率測試時,IDE 顯示 5/6 方法覆蓋。 但是這個類只有五個方法。 第6種方法在哪里? 我錯過了什么?

package com.beetlehand.model;

import javax.persistence.*;
import java.util.Objects;

@Entity
@Table(name = "product_attribute", schema = "beetlehand", catalog = "")
@IdClass(ProductAttributeEntityPK.class)
public class ProductAttributeEntity {
    private int productId;
    private int attributeValueId;

    /*** Getters and Setters ***/

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ProductAttributeEntity that = (ProductAttributeEntity) o;
        return productId == that.productId &&
                attributeValueId == that.attributeValueId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(productId, attributeValueId);
    }
}

和單元測試

package com.beetlehand.model;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class ProductAttributeEntityPKTest {
    @Test
    void testGetProductId() {
        ProductAttributeEntity entity = new ProductAttributeEntity();
        entity.setProductId(1);
        entity.setAttributeValueId(1);

        assertEquals(1, entity.getProductId());
    }
    @Test
    void testGetAttributeValueId() {
        /*** test logic ***/

        assertEquals(1, entity.getAttributeValueId());
    }
    @Test
    void testEquals() {
        /*** test logic ***/

        assertEquals(true, entity.equals(entity2));
    }
    @Test
    void testHashCode() {
        /*** test logic ***/

        assertEquals(entity2.hashCode(), entity.hashCode());
    }
}

我在想if語句中的每個控件都會增加coverage的值。 您無法獲得100% 的 covarage值,因為您沒有在equals方法中提供所有控件。 您必須在單元測試方法中提供所有控件(相同對象、空對象、不同類對象)。

!!! 您必須首先檢查空對象,否則在提交空對象時會得到NullPointerException

我也想提出測試建議。 首先,我建議您研究單元測試命名約定 例如,您可以查看此標題 -> 單元測試命名最佳實踐

@Test
void equals_WhenObjectIsNull_ShouldReturnFalse() {

}

@Test
void equals_WhenObjectIsSame_ShouldReturnTrue() {

}

我的另一個建議是,您可以在@Before注釋下創建實體對象並減少代碼行。

public ProductAttributeEntity entity;
 
@Before
public void setUp() {
    entity = new ProductAttributeEntity();
    entity.setProductId(1);
    entity.setAttributeValueId(1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM