MongoDB和Mock测试:更改MongoTemplate.save(obj)的参数

时间:2016-01-22 09:54:14

标签: java mongodb unit-testing spring-data spring-data-mongodb

我使用 MongoDB 3.2.1 + SpringDataMongoDB 1.8.2.RELEASE Mockito 2.0.2-beta

我有用户类:

@Document(collection = "users")
public class User implements Serializable {
    @JsonView(UserView.Summary.class)
    @Id
    private String id;
    @JsonView(UserView.Summary.class)
    private String name;
    private String password;
    @JsonView(UserView.Summary.class)
    private String email;

    public User() { }

    public User(String id) {
        this.id = id;
    }

    public User(String name, String password, String email) {
        this.name = name;
        this.password = password;
        this.email = email;
    }
    // getters and setters
}

它的DAO层(部分):

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private Logger LOGGER;
    @Autowired
    @Qualifier(value = "mongoTemplate")
    private MongoTemplate mongoTemplate;

    public User create(User user) {
        LOGGER.debug("UserDaoImpl.create: "+user);
        mongoTemplate.insert(user);
        return user;
    }
}

现在我想要像这样模拟mongoTemplate

@Bean(name = "mongoTemplate")
public MongoTemplate getMongoTemplate() {
    MongoTemplate mongoTemplate = Mockito.mock(MongoTemplate.class);
    List<User> allUsers = new ArrayList<>();
    allUsers.add(new User("2323", "22", "1@1.1"));
    allUsers.add(new User("2323derfvb", "22234", "2@2.2"));
    Mockito.when(mongoTemplate.findAll(User.class)).thenReturn(allUsers);

    // **Don't work: it doesn't fill ID field for user**
    Mockito.doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        ((User) args[0]).setId("2342");
        return null;
    }).when(mongoTemplate).insert(User.class);

    return mongoTemplate;
}

不幸的是我遇到了问题。 mongoTemplate在调用方法id时填充mongoTemplate.insert(user)字段,我可以返回id字段作为DAO的答案。但是,如果模拟方法返回void,则 Mockito 无法更改参数。我只能这样做:

Mockito.doNothing().when(mongoTemplate).insert(User.class);
在这种情况下,我不能改变user参数。像

这样的链
Mockito.doAnswer(invocation -> {
    Object[] args = invocation.getArguments();
    ((User) args[0]).setId("2342");
    return null;
}).doNothing().when(mongoTemplate).insert(User.class);

也没有帮助。

在这种情况下,有谁能说我如何更改输入参数?

0 个答案:

没有答案