【发布时间】:2018-11-25 10:03:19
【问题描述】:
我正在为服务层运行 Junit 测试用例,但我得到了
org.junit.ComparisonFailure:预期:VendorEntity@3e60be48 但为:null
当调用 vendorRepo.save(vendorEntity) 方法时它返回 null,我无法弄清楚它为什么返回 null。下面是我的代码。
@Autowired
private VendorSvc vendorSvc;
@MockBean
private VendorRepo vendorRepo;
@Test
public void testSaveVendorForm() {
VendorEntity vendorEntiy = getVendor();
Mockito.when(vendorRepo.save(vendorEntiy)).thenReturn(vendorEntiy);
// saveVendorForm return null
VendorEntity vendorEntity2 = vendorSvc.saveVendorForm(getVendorDto());
assertThat(vendorEntity2).isEqualTo(vendorEntiy);
}
在 saveVendorForm 进行一些更改后,接受 vendorEntity 下面的代码有效,但我不想将实体类对象传递给服务层,因为我想在服务层中创建实体对象并将其传递给 dao 层
@Test
public void testSaveVendorForm() {
VendorEntity vendorEntity = getVendor();
Mockito.when(vendorRepo.save(vendorEntity)).thenReturn(vendorEntity);
VendorEntity vendorEntity2 = vendorSvc.saveVendorForm(vendorEntity);
assertThat(vendorEntity2).isEqualTo(vendorEntity);
}
private VendorEntity getVendor() {
VendorEntity vendorEntity = new VendorEntity();
SocietyEntity societyEntity = new SocietyEntity();
societyEntity.setSocietyId(1L);
PincodeEntity pincodeEntity = new PincodeEntity();
pincodeEntity.setPincodeId(1L);
vendorEntity.setVendor("XYZ Cafe");
vendorEntity.setAddress("abc address");
vendorEntity.setEmailId("xyz@gmail.com");
vendorEntity.setContactNo1("123456");
vendorEntity.setContactNo2("123457");
vendorEntity.setSocietyId(societyEntity.getSocietyId());
vendorEntity.setPincodeId(pincodeEntity.getPincodeId());
vendorEntity.setWebsite("www.xyzabc.com");
vendorEntity.setCategoryId(2);
vendorEntity.setStatus(Constant.ACTIVE);
vendorEntity.setCreatedBy(1L);
vendorEntity.setCreatedDate(CommonUtil.getCurrentTimeStamp());
vendorEntity.setCreatedIp(Constant.DEFAULT_IP);
vendorEntity.setSocietyEntity(new SocietyEntity());
vendorEntity.setPincodeEntity(new PincodeEntity());
return vendorEntity;
}
@Override
public VendorEntity saveVendorForm(VendorDto vendorDto) {
VendorEntity vendorEntity = new VendorEntity();
// copy properties from (source,target)
BeanUtils.copyProperties(vendorDto,vendorEntity);
vendorEntity.setCreatedBy(vendorDto.getCreatedBy());
vendorEntity.setCreatedDate(vendorDto.getCreatedDate());
vendorEntity.setCreatedIp(vendorDto.getCreatedIp());
vendorEntity.setModifiedBy(vendorDto.getModifiedBy());
vendorEntity.setModifiedDate(vendorDto.getModifiedDate());
vendorEntity.setModifiedIp(vendorDto.getModifiedIp());
vendorEntity.setSocietyEntity(new SocietyEntity());
vendorEntity.setPincodeEntity(new PincodeEntity());
vendorEntity.setStatus(Constant.ACTIVE);
// below code returns null but works well when run in tomcat and form submitted through web browser
return vendorRepo.save(vendorEntity);
}
public interface VendorRepo extends JpaRepository<VendorEntity, Long> {
}
谁能告诉我代码有什么问题。
【问题讨论】:
-
如何在您的测试类中声明 vendorRepo ?你能附上完整的测试类吗?
-
@bittu 我已经为 vendorRepo 添加了代码
标签: spring-boot junit5 spring-boot-test