java.lang.AssertionError: expected:<1> but was:<30> in Junit - junit

I am new for Junit and Mockito and i am trying to test below code but ia m getting exception --->java.lang.AssertionError: expected:<1> but was:<30>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:645)
at org.junit.Assert.assertEquals(Assert.java:631)
at can some one help me what is mistack?and suggest me right way
Original
public List<GithubModel> getGitHubUsersList(){
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity<GithubModel>httpEntity = new HttpEntity<GithubModel>(httpHeaders);
ResponseEntity<List<GithubModel>>usersList = restTemplate.exchange("https://api.github.com/repos/git/git/contributors",
HttpMethod.GET,httpEntity, new ParameterizedTypeReference<List<GithubModel>>() {
});
return usersList.getBody();
}
TestCase:
#Spy
#InjectMocks
MicroServicesTest1 microServicesTest1;
#Mock
RestTemplate mockRestTemplate;
#Before
public void create(){
MockitoAnnotations.initMocks(this);
}
#Test
public void getGitHubUsersListTest(){
ResponseEntity<List<GithubModel>> response = Mockito.mock(ResponseEntity.class);
Mockito.when(mockRestTemplate.exchange(Mockito.anyString(), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.eq(new ParameterizedTypeReference<List<GithubModel>>(){}))).thenReturn(response);
Mockito.when(response.getBody()).thenReturn(getUsersList());
List<GithubModel> mocklist = microServicesTest1.getGitHubUsersList();
assertEquals(1, mocklist.size());
}
/**
* getUsersList
* #return
*/
public List<GithubModel>getUsersList(){
GithubModel githubModel = new GithubModel();
githubModel.setId(1);
githubModel.setLogin("hello1");
githubModel.setNode_id("hello2");
List<GithubModel>list = new ArrayList<>();
list.add(githubModel);
return list;
}

Related

How to make mock JdbcTemplate.queryForObject() method

I am new for Junit and Mockito and i am not understand how to write test case for below JdbcTemplate and i tried but getting exception ,Can some one help me please
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
Code
#Repository
public class BaaisnEvcIdMSRepository {
#Autowired
private JdbcTemplate jdbcTemplate;
#Transactional
public RowMapperServerResponse getQueryEvcidRepository(BaaisnEvcIdRequest baaisnEvcIdRequest) {
RowMapperServerResponse rowMapperServerResponse = jdbcTemplate.queryForObject(
"select * from Master_Circuit WHERE master_ckt_id = ( select max(master_ckt_id) from master_circuit WHERE product = ? AND id_type = ?)",
new Object[]{baaisnEvcIdRequest.getProduct_type(),baaisnEvcIdRequest.getLata()}, new BaaisnRowMapper());
return rowMapperServerResponse;
}
}
test class
public class BaaisnEvcIdMSRepositoryTest {
#InjectMocks
BaaisnEvcIdMSRepository baaisnEvcIdMSRepository;
#Mock
JdbcTemplate jdbcTemplate;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getQueryEvcidRepositoryTest() {
when(jdbcTemplate.queryForObject(eq(ArgumentMatchers.anyString()), refEq(new Object[]{ArgumentMatchers.anyInt()}), eq(String.class))).thenReturn("data");
verify(jdbcTemplate, times(1)).queryForObject(eq(ArgumentMatchers.anyString()), refEq(new Object[]{ArgumentMatchers.anyInt()}), eq(String.class));
}
}
The InvalidUseOfMatchersException is coming from your use of eq(ArgumentMatchers.anyString()) and refEq(new Object[]{ArgumentMatchers.anyInt()}). You are not supposed to wrap ArgumentMatchers inside anything else.
You also seem to aim at the wrong queryForObject method. It should be this one instead.
As mentioned before you need to call the method under test before doing the verification.
#Test
public void getQueryEvcidRepositoryTest() {
// use a real `BaaisnEvcIdRequest` object if you can
BaaisnEvcIdRequest req = Mockito.mock(BaaisnEvcIdRequest.class);
Mockito.when(req.getProduct_type()).thenReturn(1);
Mockito.when(req.getLata()).thenReturn(new Object());
Object[] array = new Object[]{req.getProduct_type(),req.getLata()};
Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(array), Mockito.any(RowMapper.class)))
.thenReturn("data");
baaisnEvcIdMSRepository.getQueryEvcidRepository(req);
Mockito.verify(jdbcTemplate, Mockito.times(1))
.queryForObject(Mockito.anyString(), Mockito.eq(array), Mockito.any(RowMapper.class));
}

Mockito do not throw exception

I have this method my repository method throws RepositoryException and service method throws Service exception i am mocking the repository and throwing repository exception but it is not throw any exception can anybody please explain what is going on here.
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);
}
}
The issue is at the line new FilterToDB(searchFilter, user) in your getIndActivities() method of the service, because searchFilterToDB objects are different, the method call is NOT actually mocked.
So, to solve the problem, you need to extract new FilterToDB object creation to a separate class & mock the method call to that class.

Lifecycle of #After method

I am trying to gather some information after every test method, and would like to analyze the gathered information after the test class completes. So, I have a private member variable, a list which I would like to add to after every test method completes. However, at the end of the day, the member variable always remains null.
Note: My test class implements Callable interface.
Here is my code snippet:
{
private List<String statisticsCollector;
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
this.statisticsCollector = new ArrayList<String>();
}
#Override
public List<String> call() {
log.info("Starting a new thread of execution with Thread# -" + Thread.currentThread().getName());
core.run(this.getClass());
return getStatisticsCollector(); // this is always returing a list of size 0
}
#After
public void gatherSomeStatistics() {
x = x+1;
String sb = new String("Currently executing ----" + x);
log.info("Currently executing ----" + x);
addToStatisticsCollector(sb);
}
#Test
#FileParameters(value = "classpath:folder/testB.json", mapper = MyMapper.class)
public void testB(MarsTestDefinition testDefinition) {
runTests(testDefinition);
}
#Test
#FileParameters(value = "classpath:folder/testA.json", mapper = MyMapper.class)
public void testA(MyDefinition testDefinition) {
runTests(testDefinition);
}
public List<String> getStatisticsCollector() {
return this.statisticsCollector;
}
public void addToStatisticsCollector(String sb) {
this.statisticsCollector.add(sb);
}
}
So, why is it always getting reset, even though I am appending to the list in my #After annotated method?
Any help will be highly appreciated. Thanks
Try with following code, is it working ?
private static List<String> statisticsCollector = new ArrayList<String>();
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
}
public List<String> getStatisticsCollector() {
return statisticsCollector;
}

ArgumentCaptor is null

I'm trying to write a unit test for the code below where I instantiate a bean and pass it on to other private methods of the class for further processing before doing what the main method does:
public OverviewTabViewBean build(Listing listing) {
VehicleDetailListingBean vehicleDetailListingBean = new VehicleDetailListingBean();
applyVehicleDetailListingRules(listing, vehicleDetailListingBean);
OverviewTabViewBean overviewTabViewBean = new OverviewTabViewBean();
if (vehicleDetailListingBean != null) {
overviewTabViewBean.setMake(vehicleDetailListingBean.getMake());
overviewTabViewBean.setModel(vehicleDetailListingBean.getModel());
overviewTabViewBean.setAtCarId(vehicleDetailListingBean.getAtCarId());
..
}
return overviewTabViewBean;
private void applyCommonListingRules(Listing listing, VehicleDetailListingBean vehicleDetailListingBean) {
rulesEngineService.applyRules(listing, vehicleDetailListingBean, vehicleDetailRules.getCommonListingRules());
}
Test looks something like this:
#Captor
ArgumentCaptor<OverviewTabViewBean> overviewTabViewBean;
#Captor
ArgumentCaptor<VehicleDetailListingBean> vehicleDetailListingBean;
#Mock
private RulesEngineService rulesEngineService;
#Mock
private VehicleDetailRules vehicleDetailRules;
#Mock
private VehicleReferenceService vehicleReferenceService;
#BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
/**
* build
*/
#Test
public void build() {
Listing listing = new Listing();
listing.setListingId(111L);
listing.setListingType(ListingType.NEW);
List<Rule<Listing, ListingBean>> rules1 = new ArrayList<Rule<Listing, ListingBean>>();
List<Rule<Listing, ListingBean>> rules2 = new ArrayList<Rule<Listing, ListingBean>>();
doReturn(rules1).when(vehicleDetailRules).getCommonListingRules();
doReturn(rules2).when(vehicleDetailRules).getDetailListingRules();
overviewTabViewBeanBuilder.build(listing);
verify(rulesEngineService, times(2)).applyRules(anyObject(), vehicleDetailListingBean.capture(), anyList());
.....
}
vehicleDetailListingBean is returning as null a not stepping into the if block. What am I doing wrong here?

Ehcache hangs in test

I am in the process of rewriting a bottle neck in the code of the project I am on, and in doing so I am creating a top level item that contains a self populating Ehcache. I am attempting to write a test to make sure that the basic call chain is established, but when the test executes it hands when retrieving the item from the cache.
Here are the Setup and the test, for reference mocking is being done with Mockito:
#Before
public void SetUp()
{
testCache = new Cache(getTestCacheConfiguration());
recordingFactory = new EntryCreationRecordingCache();
service = new Service<Request, Response>(testCache, recordingFactory);
}
#Test
public void retrievesResultsFromSuppliedCache()
{
ResultType resultType = mock(ResultType.class);
Response expectedResponse = mock(Response.class);
addToExpectedResults(resultType, expectedResponse);
Request request = mock(Request.class);
when(request.getResultType()).thenReturn(resultType);
assertThat(service.getResponse(request), sameInstance(expectedResponse));
assertTrue(recordingFactory.requestList.contains(request));
}
private void addToExpectedResults(ResultType resultType,
Response response) {
recordingFactory.responseMap.put(resultType, response);
}
private CacheConfiguration getTestCacheConfiguration() {
CacheConfiguration cacheConfiguration = new CacheConfiguration("TEST_CACHE", 10);
cacheConfiguration.setLoggingEnabled(false);
return cacheConfiguration;
}
private class EntryCreationRecordingCache extends ResponseFactory{
public final Map<ResultType, Response> responseMap = new ConcurrentHashMap<ResultType, Response>();
public final List<Request> requestList = new ArrayList<Request>();
#Override
protected Map<ResultType, Response> generateResponse(Request request) {
requestList.add(request);
return responseMap;
}
}
Here is the ServiceClass
public class Service<K extends Request, V extends Response> {
private Ehcache cache;
public Service(Ehcache cache, ResponseFactory factory) {
this.cache = new SelfPopulatingCache(cache, factory);
}
#SuppressWarnings("unchecked")
public V getResponse(K request)
{
ResultType resultType = request.getResultType();
Element cacheEntry = cache.get(request);
V response = null;
if(cacheEntry != null){
Map<ResultType, Response> resultTypeMap = (Map<ResultType, Response>) cacheEntry.getValue();
try{
response = (V) resultTypeMap.get(resultType);
}catch(NullPointerException e){
throw new RuntimeException("Result type not found for Result Type: " + resultType);
}catch(ClassCastException e){
throw new RuntimeException("Incorrect Response Type for Result Type: " + resultType);
}
}
return response;
}
}
And here is the ResponseFactory:
public abstract class ResponseFactory implements CacheEntryFactory{
#Override
public final Object createEntry(Object request) throws Exception {
return generateResponse((Request)request);
}
protected abstract Map<ResultType,Response> generateResponse(Request request);
}
After wrestling with it for a while, I discovered that the cache wasn't being initialized. Creating a CacheManager and adding the cache to it resolved the problem.
I also had a problem with EHCache hanging, although only in a hello-world example. Adding this to the end fixed it (the application ends normally).
CacheManager.getInstance().removeAllCaches();
https://stackoverflow.com/a/20731502/2736496