我有这个方法我的存储库方法抛出RepositoryException和服务方法抛出服务异常我正在模拟存储库并抛出存储库异常但它不抛出任何异常可以任何人请解释这里发生了什么。
public class IndActivityTest {
static BigDecimal offset;
static SecurityContext userContext;
SearchFilter filter = new SearchFilter();
SearchFilterToDB filterToDB = new SearchFilterToDB();
static BigDecimal limit;
static User user = null;
@Mock
static UserRepository repository;
@Mock
static SearchRepository searchRepository;
@InjectMocks
static SearchApiServiceImpl searchApiImple;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@BeforeClass
public static void setUp(){
user = new User();
String scheme="https";
userContext = new ServiceSecurityContext(user, scheme);
}
@Test
public void getIndActivitiesPositiveResponse() throws RepositoryException,ServiceException{
List<IndActivityDetailEntity> activityDetailEntities = new ArrayList<>();
when(searchRepository.getIndActivitiesFromDB(filterToDB,user)).thenReturn(activityDetailEntities);
Response response = searchApiImple.getIndActivities(filter, userContext);
assertEquals(response.getStatus(), 200);
}
@Test(expected=ServiceException.class)
public void getIndActivitiesNegetiveResponse() throws RepositoryException,ServiceException{
when(searchRepository.getIndActivitiesFromDB(filterToDB,user)).thenThrow(new RepositoryException());
searchApiImple.getIndActivities(filter, userContext);
}
}
public Response getIndActivities(SearchFilter searchFilter, SecurityContext securityContext)
throws ServiceException {
List<Activity> activities = new ArrayList<>();
try {
logger.info("Entering getActivities");
List<IndActivityDetailEntity> activityDetailEntities = new ArrayList<>();
User user = (User) securityContext.getUserPrincipal();
SearchFilterToDB searchFilterToDB = newFilterToDB(searchFilter, user);
activityDetailEntities = searchRepository.getIndActivitiesFromDB(searchFilterToDB, user);
if (!activityDetailEntities.isEmpty())
activities = SearchUtil.convertIndActivityToIndActivityDTO(activityDetailEntities, searchRepository);
logger.info(" Exiting getActivities");
} catch(Exception e){
handleException(e);
}
return Response.status(200).entity(new InlineResponse200().data(activities)).build();
}
private void handleException(Exception e) throws ServiceException{
logger.error("Service Exception "+e);
if( e instanceof ServiceException)
throw (ServiceException)e;
if( e instanceof RepositoryException ){
RepositoryException re = (RepositoryException)e;
throw new ServiceException(re.getErrorCode(),re,re.getMessage());
}else{
throw new ServiceException(e.getMessage(), e,ServiceConstant.UNKNOWN);
}
}
答案 0 :(得分:1)
问题出在您的new FilterToDB(searchFilter, user)
服务方法的第getIndActivities()
行,因为searchFilterToDB
个对象不同,方法调用实际上并未被模拟。
因此,要解决此问题,您需要将new
FilterToDB
对象创建提取到单独的类&amp;模拟对该类的方法调用。