Spring Boot之DAO層的單元測試小結

DAO層

dao是data access object的簡寫,基於Java對象訪問數據庫中的數據,這是應用中必備的系統模塊。

測試註解

  • DataJpaTest
    主要用以測試DAO的業務功能

DAO層的實體定義

實體Bean定義如下:

@Entity
@Data
public class GameEntity {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column
    private String name;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdTime;
}

在這個Bean中定義了id, name和創建時間三個字段。
定義Repository DAO對象:

@Repository
public interface GameRepository extends JpaRepository<GameEntity, Long> {
    public GameEntity findByName(String name);
}

在這個Repository中定義了一個方法,用來實現基於name來查詢GameEntity實例。

DAO的單元測試

單元測試用例如下:

import lombok.extern.slf4j.Slf4j;
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.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.Objects;
import static org.hamcrest.Matchers.greaterThan;

@RunWith(SpringRunner.class)
@DataJpaTest
@Slf4j
public class GameRepositoryTest {
    @Autowired
    private GameRepository gameRepository;

    @Autowired
    private TestEntityManager entityManager;

    @Test
    public void testGame() {
       GameEntity gameEntity = new GameEntity();
       gameEntity.setCreatedTime(new Date());
       gameEntity.setName("zhangsan");

       gameEntity = this.gameRepository.save(gameEntity);

       Assert.assertTrue(Objects.nonNull(gameEntity));
       Assert.assertThat("id is null", 1l, greaterThan(gameEntity.getId()));
    }
}

在上述測試用例中使用了@DataJpaTest用來啓動DAO層的單元測試。 正常基於@Autowired引入GameRepository實例。 這裏默認提供了TestEntityManager實例,主要用於在測試環節下,引入EntityManager實例,可以用來執行其它的SQL操作。

總結

這裏做了一些假定,由於其只有很少的依賴和業務邏輯。在實際業務場景中,業務邏輯以及數據操作會比較複雜,單元測試用例的依賴會比較多。

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