我正在尝试为我的spring应用程序编写Junit测试,并且测试的类是DAO类。我正在使用JPA来维持。我无法找到使用mockito测试spring JPA dao类的正确示例。以下是我到目前为止所尝试的内容。
DOA课程
@Repository
public class UserDaoImpl extends AbstractAppDao<User, Integer> {
@PersistenceContext
private EntityManager entitymanager;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
private User user;
static Logger logger = LoggerFactory.getLogger("com.test.UserDaoImpl.lcass");
public UserDaoImpl() {
super(User.class);
}
@Override
public String createUser(String userName, String firstName, String lastName, Set<String> assignUserGroups,
String emailId, String approverEmailId, String loggedInUserName) throws Exception {
User user = null;
try {
user = new User();
User approver=new User();
user.setLoginUserId(userName);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmailId(emailId);
user.setNotifyViaEmail("Y");
user.setContactNo(220);
if (approverEmailId != null) {
approver=getUserByEmail(approverEmailId);
if (approver.getUserId()!= 0) {
user.setApproverId(approver.getUserId());
}
}
user.setLoginRetryCount(10);
user.setActiveStatus(PDPConstants.PENDING_STATUS);
user.setUpdatedDate(new Date());
save(user);
return "User is created successfully";
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Junit Code到目前为止
@RunWith(MockitoJUnitRunner.class)
public class UserDaoTest {
@Mock
private EntityManager entitymanager;
@InjectMocks
UserDaoImpl userDao;
@Test
public void createPdpUser() throws Exception {
User user = null;
try {
user = new User();
User approver=new User();
user.setLoginUserId("test");
user.setFirstName("firstName");
user.setLastName("lastName");
user.setEmailId("am");
user.setNotifyViaEmail("Y");
user.setContactNo(220);
String approverEmailId;
user.setApproverId(22);
user.setLoginRetryCount(10);
user.setActiveStatus("PA");
user.setUpdatedDate(new Date());
userDao.save(user);
Mockito.verify(userDao.getEntityManager(),Mockito.atLeast(1)).merge(Mockito.anyObject());
} catch (Exception e) {
e.printStackTrace();
}
}
}
我最终修改了junit代码,并且能够运行测试用例