英文:
How to mock jpa repository save(without return object) and modify id of input object
问题
我在项目中使用了Spring Data JPA,我的模型代码如下:
@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Activity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String number;
//...
}
我的服务代码如下:
activityRepository.save(activity);//activity在id字段中没有数据
activity.setNumber("D" + activity.getId()); //A
activityRepository.save(activity);
我的模拟代码如下:
when(activityRepository.save(activity)).thenReturn(tempActivity);
//调用服务方法
verify(activityRepository).save(activity);
问题是,在代码A中我一直遇到空指针异常。那么我该如何模拟这个repository的save方法呢?
英文:
I use Spring Data JPA in my project and my model code is here:
@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Activity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String number;
//...
}
My service code is here:
activityRepository.save(activity);//activity has no data in field id
activity.setNumber("D"+activity.getId()); //A
activityRepository.save(activity);
And my mock code is here:
when(activityRepository.save(activity)).thenReturn(tempActivity);
//invoke service method
verify(activityRepository).save(activity);
The question is that I have always been met with the Null Pointer Exception in code A.So how can I mock this repository save method?
答案1
得分: 0
-
使用从activityRepository.save(activity)返回的对象
activity = activityRepository.save(activity);//activity在字段id中没有数据 activity.setNumber("D" + activity.getId()); //A activity = activityRepository.save(activity);
-
返回一个经模拟返回的修改后版本
tempActivity = activity.toBuilder().id(5).build(); when(activityRepository.save(activity)).thenReturn(tempActivity); //调用服务方法 verify(activityRepository).save(activity);
英文:
Two points:
-
Use the returned object from activityRepository.save(activity)
activity = activityRepository.save(activity);//activity has no data in field id activity.setNumber("D"+activity.getId()); //A activity = activityRepository.save(activity);
-
Return a modified version, that is returned by the mock
tempActivity = activity.toBuilder().id(5).build(); when(activityRepository.save(activity)).thenReturn(tempActivity); //invoke service method verify(activityRepository).save(activity);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论