如何为 spring 启动应用程序编写 Junit 测试用例?
How to write Junit test cases for spring boot application?
我必须编写一些 junit 测试用例来检查实体。我正在使用 postgres 作为我的数据库。
我的实体class
@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();
}
服务class
@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);
}
在test/java/example/demo/resources
conn.properties
id=2
其返回值为 0
有什么问题吗?
谢谢
我已设法让您的代码正常工作。我将 post 仅更改 classes:
界面:
public interface DisplayRepository extends CrudRepository<Display, Long> {
Optional<Display> findByTitle(String name);
}
测试class:
@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);
}
}
在尝试 运行 您提供的代码时,出现了一些问题:
- 您在显示 class 中使用了保留字
group
作为字段。因此,Hibernate 无法创建 table,因此我将其重命名为类别。
- 存在编译问题,因为存储库中未定义方法
findByName
;此外,显示 class 中没有要映射到的字段 name
;因此,我添加了方法 findByTitle
因为它是一个现有字段并且它似乎与您在测试方法中查询的值匹配。
- 因为 ID 字段是自动生成的,所以在持久显示时测试设置 () 失败。
如果你想使用@Mock 来模拟classes,你必须调用:
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
然后您可以照常模拟回复:Mockito.when(DisplayReps.findByTitle("A")).thenReturn(Optional.of(new Display(2L, "ALFA", "GRP1")));
我必须编写一些 junit 测试用例来检查实体。我正在使用 postgres 作为我的数据库。
我的实体class
@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();
}
服务class
@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);
}
在test/java/example/demo/resources conn.properties id=2
其返回值为 0 有什么问题吗? 谢谢
我已设法让您的代码正常工作。我将 post 仅更改 classes:
界面:
public interface DisplayRepository extends CrudRepository<Display, Long> {
Optional<Display> findByTitle(String name);
}
测试class:
@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);
}
}
在尝试 运行 您提供的代码时,出现了一些问题:
- 您在显示 class 中使用了保留字
group
作为字段。因此,Hibernate 无法创建 table,因此我将其重命名为类别。 - 存在编译问题,因为存储库中未定义方法
findByName
;此外,显示 class 中没有要映射到的字段name
;因此,我添加了方法findByTitle
因为它是一个现有字段并且它似乎与您在测试方法中查询的值匹配。 - 因为 ID 字段是自动生成的,所以在持久显示时测试设置 () 失败。
如果你想使用@Mock 来模拟classes,你必须调用:
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
然后您可以照常模拟回复:Mockito.when(DisplayReps.findByTitle("A")).thenReturn(Optional.of(new Display(2L, "ALFA", "GRP1")));