How to print RuntimeVisibleAnnotations in java ASM - java-bytecode-asm

I am new to ASM. I have a class file in which I have runtime visible annotations for methods. I want to parse this class file and select the annotation according to specific criteria. I looked into the documentation of ASM and tried with the visibleAnnotation. I can't seem to print the list of annotations of method which I can see in my class files.
My code is as
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.ClassReader;
public class ByteCodeParser {
public static void main(String[] args) throws Exception{
InputStream in=new FileInputStream("sample.class");
ClassReader cr=new ClassReader(in);
ClassNode classNode=new ClassNode();
//ClassNode is a ClassVisitor
cr.accept(classNode, 0);
//
Iterator<MethodNode> i = classNode.methods.iterator();
while(i.hasNext()){
MethodNode mn = i.next();
System.out.println(mn.name+ "" + mn.desc);
System.out.println(mn.visibleAnnotations);
}
}
}
The output is:
<clinit>()V
null
<init>()V
null
MyRandomFunction1()V
[org.objectweb.asm.tree.AnnotationNode#5674cd4d]
MyRandomFunction2()V
[org.objectweb.asm.tree.AnnotationNode#63961c42]
My RandomFunction 1 & 2 has annotations but I can't seem to understand [org.objectweb.asm.tree.AnnotationNode#5674cd4d].

I solved this issue myself, I had to iterate over the annotations which I didn't realize initally.
if (mn.visibleAnnotations != null) {
Iterator<AnnotationNode>j=mn.visibleAnnotations.iterator();
while (j.hasNext()) {
AnnotationNode an=j.next();
System.out.println(an.values);
}
}

Related

PowerMockito calls real method on Mocked Object when defining second "when" clause

I am trying to define some different mocked behaviours when a method is called with different parameters. Unfortunately, I find that the second time I try to mock the given method on a (mocked) class, it runs the actual method, causing an exception because the matchers are not valid parameters. Anyone know how I can prevent this?
manager = PowerMockito.mock(Manager.class);
try {
PowerMockito.whenNew(Manager.class).withArguments(anyString(), anyString())
.thenReturn(manager);
} catch (Exception e) {
e.printStackTrace();
}
FindAuthorityDescriptionRequestImpl validFindAuthorityDescription = mock(FindAuthorityDescriptionRequestImpl.class);
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(anyString(), anyString())).thenCallRealMethod();
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(Matchers.eq(VALID_IK),
Matchers.eq(VALID_CATEGORY_NAME))).thenReturn(validFindAuthorityDescription);
PowerMockito.when(manager.processRequest(Matchers.any(FindAuthorityDescriptionRequest.class)))
.thenThrow(ManagerException.class);
PowerMockito.when(manager.processRequest(Matchers.eq(validFindAuthorityDescription)))
.thenReturn(generateValidAuthorityDescriptionResponse());
The following code is a working example based on your mock setup (I've added dummy classes to make it runnable).
The code also contains asserts to verify that the mocked methods return expected values. Also, the real method createFindAuthorityDescriptionRequest is only called once.
Note: This was tested with `powermock 2.0.7` and `mockito 2.21.0`.
If issues persist, I'd suggest checking if the real method is not additionally called from somewhere else in your program (other than the code quoted in your problem statement).
package com.example.stack;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.powermock.api.mockito.PowerMockito.mock;
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.example.stack.*")
public class StackApplicationTests {
private static final String VALID_IK = "IK";
private static final String VALID_CATEGORY_NAME = "CATEGORY_NAME";
private static final Object VALID_RESPONSE = "RESPONSE";
#Test
public void test() {
Manager manager = mock(Manager.class);
try {
PowerMockito.whenNew(Manager.class).withArguments(anyString(), anyString())
.thenReturn(manager);
} catch (Exception e) {
e.printStackTrace();
}
FindAuthorityDescriptionRequestImpl validFindAuthorityDescription = mock(FindAuthorityDescriptionRequestImpl.class);
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(anyString(), anyString())).thenCallRealMethod();
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(eq(VALID_IK), eq(VALID_CATEGORY_NAME)))
.thenReturn(validFindAuthorityDescription);
PowerMockito.when(manager.processRequest(any(FindAuthorityDescriptionRequest.class)))
.thenThrow(ManagerException.class);
PowerMockito.when(manager.processRequest(eq(validFindAuthorityDescription)))
.thenReturn(VALID_RESPONSE);
// verify that the mock returns expected results
assertEquals(Manager.REAL_RESULT, manager.createFindAuthorityDescriptionRequest("any", "any"));
assertEquals(validFindAuthorityDescription, manager.createFindAuthorityDescriptionRequest("IK", "CATEGORY_NAME"));
assertThrows(ManagerException.class, new ThrowingRunnable(){
#Override
public void run( ) {
manager.processRequest(new FindAuthorityDescriptionRequestImpl());
}
});
assertEquals(VALID_RESPONSE, manager.processRequest(validFindAuthorityDescription));
}
}
interface FindAuthorityDescriptionRequest {}
class FindAuthorityDescriptionRequestImpl implements FindAuthorityDescriptionRequest {}
class ManagerException extends RuntimeException {}
class Manager {
public static FindAuthorityDescriptionRequestImpl REAL_RESULT = new FindAuthorityDescriptionRequestImpl();
public Manager(String s1, String s2) {}
public FindAuthorityDescriptionRequest createFindAuthorityDescriptionRequest(String ik, String category) {
return REAL_RESULT;
}
public Object processRequest(FindAuthorityDescriptionRequest request) {
return null;
}
}

Junit for QueryDsl

I'm trying to write a test case for a query dsl, I'm getting null pointer exception when I run the test case
Dsl Class
QMyClass myClass= QMyClass.myClass;
queryFactory = new JPAQueryFactory(em);
JPAQuery<?> from = queryFactory.from(myClass);
JPAQuery<?> where = from
.where(prepdicates);
orderBy(orderSpecifier).offset(sortOrder.getOffset())
.limit(sortOrder.getPageSize());
**Junit test case:**
import javax.inject.Provider;
import javax.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.data.jpa.repository.support.QueryDslRepositorySupport;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.JPQLTemplates;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
#RunWith(PowerMockRunner.class)
public class MyClass{
#Mock
QueryDslRepositorySupport queryDslRepositorySupport;
#Mock
EntityManager entityManager;
#Mock
JPAQueryFactory queryFactory;
#Mock
JPAQuery step1;
#InjectMocks
MyClass myClass;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Provider<EntityManager> provider = new Provider<EntityManager>() {
#Override
public EntityManager get() {
return entityManager;
}
};
queryFactory = new JPAQueryFactory(JPQLTemplates.DEFAULT, provider);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Test
public void sampleTest() throws Exception {
QMyClass class= Mockito.mock(QMyClass.class);
Mockito.when(queryFactory.from(class)).thenReturn(step1);
Predicate step2 = Mockito.mock(Predicate.class);
Mockito.when(step1.where(step2)).thenReturn(step1);
OrderSpecifier step3 = Mockito.mock(OrderSpecifier.class);
Mockito.when(step1.orderBy(step3)).thenReturn(step1);
Mockito.when(step1.offset(Mockito.anyLong())).thenReturn(step1);
Mockito.when(step1.limit(Mockito.anyLong())).thenReturn(step1);
myClass.method("");
}
}
When I run this test case I'm getting null pointer exception at line number 2 in sampleTest() method. I googled but did't find any article for this, not sure why this NE, even after mocking the queryfacotry
Here is the trace :
java.lang.NullPointerException
at com.querydsl.core.DefaultQueryMetadata.addJoin(DefaultQueryMetadata.java:154)
at com.querydsl.core.support.QueryMixin.from(QueryMixin.java:163)
at com.querydsl.jpa.JPAQueryBase.from(JPAQueryBase.java:77)
at com.querydsl.jpa.impl.JPAQueryFactory.from(JPAQueryFactory.java:116)
at
As I mentioned in the comment, your problem is that you do not use a mock, but the real object instead.
Remove the queryFactory initialisation from your setup method.
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Provider<EntityManager> provider = new Provider<EntityManager>() {
#Override
public EntityManager get() {
return entityManager;
}
};
// remove this line
// queryFactory = new JPAQueryFactory(JPQLTemplates.DEFAULT, provider);
}
Also you need to change your implementation, you can not use
queryFactory = new JPAQueryFactory(em); inside your code, as it can not be mocked.
What you could do instead is having a method that returns the JPAQueryFactory,
either from another class - which you can mock -
or in the same method, then you would need to spy on your class instead.
As you didnt add the code for the class you want to test (MyClass - hopefully a different one from the identical named UnitTest?), another possibility would be that you try to use Field or Constructor Injection (as indicated by the use of your annotations), but then there should not be an object creation for the JPAQueryFactory in your code at all.
This also seems to be wrong:
You should inject mocks into your class under test, not in your UnitTest class.
#RunWith(PowerMockRunner.class)
public class MyClass{
...
#InjectMocks
MyClass myClass;

how to clear this programming error in getCellData in keyword driven framework for selenium webdriver?

I'm using this program in Keyword driven framework for selenium web driver tool. But due to this program i'm getting null pointer exception every time i tried to debug the code but cant find any solution. please suggest me the solution for that error.
package utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
public class ExcelUtils {
private static HSSFSheet ExcelWSheet;
private static HSSFWorkbook ExcelWBook;
private static HSSFCell Cell;
//This method is to set the File path and to open the Excel file
//Pass Excel Path and SheetName as Arguments to this method
public static void setExcelFile(String Path,String SheetName) throws Exception
{
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new HSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
//This method is to read the test data from the Excel cell
//In this we are passing parameters/arguments as Row Num and Col Num
public static String getCellData(int RowNum, int ColNum) throws Exception{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
System.out.println(Cell);
String CellData = Cell.getStringCellValue();
System.out.println("."+CellData);
return CellData;
}
}

How can I make Selenium tests inside my JSF project?

I have quite big JSF 1.2 project and I want to write some integration tests to it.
The perfect situation will be, when I can run these tests from my project and it opens my browser and makes all the actions (with Selenium), which are written in my test cases. Ofc opening browser is not required when It will run these tests anyway :)
I've tried a few possibilities, anyway I still can't attach any selenium library to my project and I realized that I just dont know where to start - can you give me some direction?
might help you ,
you can write you test logic inside test method
package com.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
public class test1 {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new InternetExplorerDriver();
driver = new ChromeDriver();
baseUrl = "http://www.google.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Ignore
#Test
public void test1() throws Exception {
// your test code
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
you just need call test1 class which you want to test it .
it will be automatically working on it .

PowerMocking static does not return expected object

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?
It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.
I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}
It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.

Resources