如何模拟 JPA 存储库的保存操作(不返回对象)并修改输入对象的 ID。

huangapple go评论50阅读模式
英文:

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

  1. 使用从activityRepository.save(activity)返回的对象

    activity = activityRepository.save(activity);//activity在字段id中没有数据
    activity.setNumber("D" + activity.getId()); //A
    activity = activityRepository.save(activity);
    
  2. 返回一个经模拟返回的修改后版本

    tempActivity = activity.toBuilder().id(5).build();
    when(activityRepository.save(activity)).thenReturn(tempActivity);
    //调用服务方法
    verify(activityRepository).save(activity);
    
英文:

Two points:

  1. 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);
    
  2. 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);
    

huangapple
  • 本文由 发表于 2023年2月6日 16:25:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定