您好,我是 JUnit 测试和 Mockito 的新手,我的问题是如何在我的 customArticleRepository
中为这个自定义部分更新方法编写单元测试,该方法没有返回参数?
我有一个名为 Article
的 POJO 对象,我想部分更新它。 REST 端点 PUT 获取 DTO 对象 Classification Mask
,并将特定更新值作为请求正文,调用服务层 ArticleService
,它调用我的 CustomArticleRepository
方法。
这是我的文章对象
public class Article {
private String id;
@Field("_cls")
private String inheritance;
private String title;
private Date published;
private String content;
private String link;
private String summary;
private String description;
private Date updated;
private String primary;
private String[] secondary;
private String category;
private String[] categories;
private String person;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private Date deleted_date;
private Boolean is_new;
private Boolean edited;
private Aws aws;
这是我的 DTO 对象
public class ClassificationMask {
private String id;
private String title;
private String content;
private String primary;
private String[] secondary;
private Float sentiment_positive;
private Float sentiment_negative;
private Float sentiment_neutral;
private Float sentiment_mixed;
private String category;
private String person;
private Boolean is_new;
private Datasource datasource;
这是我在存储库中的部分更新方法
public void partialUpdateMask(String id, ClassificationMask articleUpdate) {
Query query = new Query(where("id").is(id));
Update update = new Update();
if(articleUpdate.getPrimary() !=null) { update.set("primary", articleUpdate.getPrimary()); }
if(articleUpdate.getSecondary() !=null){ update.set("secondary", articleUpdate.getSecondary());}
if(articleUpdate.getCategory() !=null){ update.set("category", articleUpdate.getCategory());}
if(articleUpdate.getPerson() !=null){ update.set("person",articleUpdate.getPerson());}
if(articleUpdate.getIs_new() !=null){ update.set("is_new",articleUpdate.getIs_new()); }
update.set("edited",true);
mongoTemplate.updateFirst(query,update ,Article.class);
}
最佳答案
测试我们可以拥有的 void 方法:
- 修改被测对象状态的方法:以便您可以验证 sut 的状态是否与您的方面一致
- 该方法不会修改 SUT 的状态,但会在数据库上写入数据,以便您可以验证 DAO 是否已被调用
这是第二种情况,你可以有这样的东西:
Mockito.verify(mongoTemplate).updateFirst(query, update, Article.class);
通过这种方式,您可以测试
- 该方法确实调用了 updateFirst
- 使用正确参数调用 updateFirst 方法
关于java - 使用 java springboot mongodb 进行部分更新的 JUNIT 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59568112/