java - 使用 Mock 和 InvocationOnMock 进行单元测试
问题描述
我是 Java Spring 的新手,我需要 Mockito 的指导。
我试图测试我的服务层,但它一直无法验证模拟用户名和电子邮件地址。
我目前真的很困惑我应该如何正确地做到这一点。
谢谢!
用户服务.java
package com.example.newproject.newproject.service;
import com.example.newproject.newproject.entity.User;
import java.util.List;
public interface UserService {
boolean addUser(String username,String email);
List<User> viewAllUsers();
}
UserServiceImpl.java
package com.example.newproject.newproject.service.impl;
import com.example.newproject.newproject.entity.User;
import com.example.newproject.newproject.repository.UserRepository;
import com.example.newproject.newproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public boolean addUser(String username, String email) {
if(userRepository.findByUsernameAndEmail(username, email) == null)
{
User user = new User();
user.setUsername(username);
user.setEmail(email);
userRepository.save(user);
return false;
}else{
return true;
}
}
@Override
public List<User> viewAllUsers() {
return userRepository.findAll();
}
}
我的模拟
@Test
public void testAddUser(){
Mockito.when(userRepository.findByUsernameAndEmail("Google","google@google.com")).then(invocationOnMock -> {
User user = new User();
return user;
});
boolean result = userService.addUser("Google","google@google.com");
Assert.assertFalse(result);
Mockito.verify(userRepository, Mockito.times(1)).save(userArgumentCaptor.capture());
User user = userArgumentCaptor.getValue();
Assert.assertEquals("Google", user.getUsername());
Assert.assertEquals("google@google.com", user.getEmail());
}
我得到的错误是
java.lang.AssertionError
在运行期间
解决方案
推荐阅读
- java - PDFbox 2.0.20 - 新的 PagePane() 抛出 RuntineException
- html - Django - 视频文件未加载到视图中
- stenciljs - 构建输出文件
- docker - 传递环境变量时出现“无效的卷规范”
- python - TypeError:“元组”对象不可调用问题
- postgresql - 如何在 Postgresql 中的几何列上创建 Gin 索引?
- c# - 防止 Exchange 2013 将邮件正文文本/纯文本转换为 HTML
- c# - 试图找出模型和 DbContext 的 EntityFramework 元数据:'Employee'
- javascript - 从 json 数组创建数据结构
- python - Python守护进程线程内存泄漏?