java - 如何为 Spring Boot 应用程序编写 Junit 测试用例?

标签 java junit entity

我必须编写一些junit测试用例来检查实体。我使用 postgres 作为我的数据库。

我的实体类

@Entity
@Table(name = "display")
public class Display {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String group;

public Display() {

}
public Display(Long id, String title, String grp) {
    this.id = id;
    this.title= title;  
    this.group= grp;
}

public void setId(Long id) {
    this.id = id;
}

public Long getId() {
    return this.id;
}

public void setGroup(String id) {
    this.group = id;
}

public String getGroup() {
    return this.group;
}

public void settitle(String title) {
    this.title = title;
}

public String gettitle() {
    return this.title;
}

}

我的存储库

@Repository
public interface DisplayRepository extends CrudRepository<Display, Long> {

}

界面

public interface IDisplayService {
    List<Display> findAll();
}

服务等级

@Service
public class DisplayService implements IDisplayService {
    @Autowired
    private DisplayRepository repository;

@Override
public List<Display> findAll() {
    List<Display> d = (List<Display>) repository.findAll();
    return d;
}
}

我尝试编写 junit 测试用例,但出现无法加载应用程序。为此编写 junit 测试用例的正确方法是什么?

这是我为服务编写的测试用例

文件夹:test/java/example/demo/Test.java

@RunWith(MockitoJUnitRunner.class)
@TestPropertySource("classpath:conn.properties")

public class DisplayServiceTest {


@Value("${id}")
private String value;


@Mock
private DisplayRepository DisplayReps;

@InjectMocks
private DisplayService DisplayService;

@Test
public void whenFindAll_thenReturnProductList() {

Menu m = new Menu()
m.setId(value);

    List<Display> expectedDisplay = Arrays.asList(m);
    doReturn(expectedDisplay).when(DisplayReps).findAll();
    List<Display> actualDisplay = DisplayService.findAll();
    assertThat(actualDisplay).isEqualTo(expectedDisplay);
}

在测试/java/example/demo/resources中 连接属性 id=2

返回值 0 有什么问题吗? 谢谢

最佳答案

我已经成功地让你的代码正常工作了。我将只发布更改后的类:

界面:

public interface DisplayRepository extends CrudRepository<Display, Long> {

   Optional<Display> findByTitle(String name);
}

测试类:

@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
@DataJpaTest
public class DisplayRepositoryTest {

@Autowired
private TestEntityManager testEntityManager;

@Autowired
private DisplayRepository productRespository;

@Before()
public void setUp(){

    Display m = new Display();
    // m.setId(2L); // The ID is autogenerated; can retrieve it from the persistAndFlush result
    m.setCategory("Group1");
    m.setTitle("Product2");

    testEntityManager.persistAndFlush(m);
}

@Test
public void whenFindByName_thenReturnProduct() {
    // when
    Display product = productRespository.findByTitle("Product2").orElseThrow(() -> new RuntimeException("Product not found"));

    // then
    assertThat(product.getTitle()).isEqualTo("Product2");
}

@Test
public void whenFindAll_thenReturnProductList() {
    // when
    List<Display> products = (List<Display>) productRespository.findAll();

    // then
    assertThat(products).hasSize(1);
}
}

当尝试运行您提供的代码时,出现了一些问题:

  • 您使用保留字group 作为 Display 类中的字段。因此,Hibernate 无法创建该表,因此我将其重命名为类别。
  • 存在编译问题,因为存储库中未定义方法 findByName;此外,Display 类中没有要进行映射的字段 name;因此,我添加了 findByTitle 方法,因为它是一个现有字段,并且似乎与您在测试方法中查询的值匹配。
  • 由于 ID 字段是自动生成的,因此在持久显示时测试 setup() 失败。

如果你想使用@Mock来模拟类,你必须调用:

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

然后您可以像往常一样模拟响应:Mockito.when(DisplayReps.findByTitle("A")).thenReturn(Optional.of(new Display(2L, "ALFA", "GRP1")));

关于java - 如何为 Spring Boot 应用程序编写 Junit 测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58969080/

相关文章:

java - JUnit - 参数化测试 - 多个构造函数调用

java - 实体可以通过其所有属性来识别吗?

java - 使用 MOA 对新示例进行分类?

java - SpringBoot 应用程序在 WLS12c/Java8/RHEL fedora7.5 中失败,无法读取架构文档 http ://www. springframework.org/schema/beans/spring-beans.xsd

java - 导入 GData 库以与 Google App Engine 一起使用

android - 当我在 robolectric 单元测试中添加影子类时抛出 LinkageError 和 IllegalAccessException 异常

Java 手机 : Android or Blackberry?

java - assertEquals(Object o1, Object o2) 是否使用 equals 方法

NHibernate:实体和同一查询中可能的子类的查询条件

ios - 在此模型中找不到名为 'Book' 的实体。 ios 核心数据错误?