Service 代码
package com.nz.mockito.Impl;
import com.nz.mockito.RegistrationService;
import com.nz.mockito.mapper.SaleDao;
import com.nz.mockito.mapper.UserDao;
import com.nz.mockito.object.SalesRep;
import com.nz.mockito.object.User;
import com.nz.mockito.util.FindUtils;
import javax.xml.bind.ValidationException;
import java.io.IOException;
/**
* @author Sherry
* @date 2024/1/24
*/
public class RegistrationServiceImpl implements RegistrationService {
SaleDao saleDao = new SaleDao();
UserDao userDao = new UserDao();
@Override
public User register(String name, String phone) throws Exception {
if(name== null || name.length() == 0){
throw new ValidationException("name not empty");
}
if(phone == null || !isValid(phone)){
throw new ValidationException("phone format error");
}
String areaCode = FindUtils.getAreaCode(phone);
String operatorCode = FindUtils.getOperatorCode(phone);
User user;
try{
SalesRep rep = saleDao.findRep(areaCode, operatorCode);
//
user = userDao.save(name, phone, rep.getRepId());
}catch (Exception e){
throw new IOException(e);
}
return user;
}
private boolean isValid(String phone) {
return true;
}
}
Service Test类
package com.nz.mockito.Impl;
import com.nz.mockito.mapper.SaleDao;
import com.nz.mockito.mapper.UserDao;
import com.nz.mockito.object.User;
import com.nz.mockito.util.FindUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import javax.xml.bind.ValidationException;
/**
* @author Sherry
* @date 2024/1/24
*/
class RegistrationServiceImplTest {
@InjectMocks
@Spy
private RegistrationServiceImpl registrationService;
@Mock
private UserDao userDao;
@Mock
private SaleDao saleDao;
@BeforeEach
void setUp(){
MockitoAnnotations.openMocks(this);
}
@Test
void register() throws Exception {
String name = null;
String phone = "1234";
try{
registrationService.register(name, phone);
Assertions.fail("fail here");
}catch (Exception e){
Assertions.assertTrue(e instanceof ValidationException);
}
name = "nz";
phone = null;
try{
registrationService.register(name, phone);}
catch (Exception e){
Assertions.assertTrue(e instanceof ValidationException);
}
phone = "1234";
MockedStatic<FindUtils> utilStatic = Mockito.mockStatic(FindUtils.class);
utilStatic.when(() -> FindUtils.getAreaCode(Mockito.anyString())).thenReturn("a");
utilStatic.when(() -> FindUtils.getOperatorCode(Mockito.anyString())).thenReturn("b");
Mockito.when(saleDao.findRep("a","b")).thenCallRealMethod();
Mockito.when(userDao.save(name, phone, "ECHO")).thenCallRealMethod();
User user = registrationService.register(name, phone);
Assertions.assertEquals("ECHO", user.getRepId());
}
}