ASM Bytecode to trace Thread.start() method - bytecode

I want to trace, which method invokes java.lang.Thread.start() method.
How do achieve it using ASM Bytecode Library...?

You can write your own javaagent which transforms all methods. It should search for java.lang.Thread.start() invocations and add logging before them.
So, you should inspect all methods and look for the following bytecode instruction:
INVOKEVIRTUAL java/lang/Thread start ()V
and insert something like this before the instruction:
GETSTATIC java/lang/System out Ljava/io/PrintStream;
LDC ${current_method_name_and_desc}
INVOKEVIRTUAL java/lang/PrintStream println (Ljava/lang/String;)V

Well, that highly depends on what amount of code you want to trace:
Do you want to know where the classes of your application are calling Thread.start: Then you need to instrument all classes of your application.
Do you want to know where any class is calling Thread.start, including those of the Java standard API: Then you need to instrument Thread what is however difficult to achieve.
In order to achieve the (1) goal, you can register a Java agent (tutorial attached) that parses any method of classes that are loaded and checks them for calls to Thread.start. Whenever you discover such a method, you need to add some sort of tracing mechanism to these methods as for example a call to System.out.println. ASM has an excelent tutorial where they even provide a similar example in the chapter on method byte code. Also, you can use the ASMifier in order to print out what code you actually would have to implement.
The (2) goal is way harder to achieve. In order to get this done, you would have to redefine the class for Thread which can cause some serious trouble since it is a system class. From within the Thread class, you could call Thread.getStackTrace and check the name of the method on top of the current call stack which is represented by a StackTraceElement. You would then again have to enable tracing this method by for example calling System.out.println.
I would recommend you the first strategy since this is easier to make work. Also, you might break the usage license of the JDK, depending on where you run your application.

Related

How can I manually compile something inside Eclipse?

One way of doing seemed to be to use the java.lang.Compiler
I tried to use the java.lang.Compiler inside Eclipse anddid not understand the Object any parameters for the methods of that class? And putting in a class did not seem to work either.
Compiler.command(any) // what is meant by any? What are valid objects to put there?
Compiler.compileClass(clazz) // Nothing happens when I out a class in there?
Compiler.compileClasses(string) // hm?
How to can I print a hello message with a Compiler inside Eclipse...?
Reading the documentation is a very important skill you need to learn.
Whenever you come across a class or a method that you don't know the functionality of, simply look at the documentation first.
Here is the docs for java.lang.Compiler: https://docs.oracle.com/javase/7/docs/api/java/lang/Compiler.html
This is the first sentence of the document:
The Compiler class is provided to support Java-to-native-code compilers and related services. By design, the Compiler class does nothing; it serves as a placeholder for a JIT compiler implementation.
So, the answer to your question is, it does nothing. According to the documentation, it does nothing. It is used to start up the Java compiler when the JVM starts. You are not meant to use this.

Get method object with method references

Is it possible to get an instance of java.lang.reflect.Method by using the new method reference feature of Java 8?
That way I would have a compile time check and refactoring would be also easier. Also, I wouldn't need to catch the exceptions (which shouldn't been thrown after all).
Short answer: No.
You will get a lambda of that method, not a java.lang.reflect.Method. You do not know the name of the method. Just as you can not have a reference to a "property" of a java bean.
You can have a reference to the getter or setter but that is also a lambda and you do not know the actual name.
In any case you'd have to provide the name as a String and that can't be checked by the compiler. I also tried this but failed. It simply can't be done unless you write something that checks the javacode/bytecode. But there are tools that do that.
Maybe the Criteria API could be used for that, but it depends on the requirements.
http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html
There you'd have a SingularAttribute or similar field on a "metamodel" and then the regular java compiler can check the (generic) type of it.

EasyMock aware debugger in Intellij?

Maybe this is counterproductive, I don't know, but right now I am in need of a debugger in IntelliJ that are aware of EasyMock mocks and especially what the mocks methods actually returns.
For example, I have a transport interface ITransport, which has some methods that had to be mocked, and where I only want some of methods returning something. E.g.
ITransport myTransport = createMock(ITransport.class);
I want myTransport.getID() to return a mocked ID 10.
expect(myTransport.getID()).andReturn(10);
With ID 10 I want a method to be invoked once,
expect(myTransport.publish(any(...)));
expectLastCall.once();
Something in the transport class breaks and myTransport isn't called, and my test fails. Know I just want to step through the code with the debugger to check why my test fails. So I add a breakpoint to verify the values of the mocked myTransport object. But they all say "null", even the ID. So I assume, with some brief investigation, that the cause of this is the EasyMock mock class, it doesn't really update the object with value (which sounds reasonable) and instead returns the mocked value at runtime when the method is called.
So, are there any mock aware debuggers for IntelliJ that lets me see which value the method will eventually return.
Yes, and before I receive responses saying that "The debugger is not required if you write unit tests for everything", I just want to state that I know about that. And this is legacy code, or at least code that wasn't written with testing in mind.
This may not be what you're looking for... but it feels like the problem is more on the debugging approach.
A mock object is really just that - a mock - meaning it's a fake empty object that doesn't do anything unless you specifically tell it. When your debugger inspects the mock object, it won't find any values that you did not specifically program it to return. It's not meant to hold values.
EasyMock has an argument capture feature, but since you just want it for debugging, this is probably the wrong approach. Mockito has a spying feature that could be suitable for what you want, but it would involve additional mock-programming statements.
I would say the easiest approach would be to implement your own ITransport just for use in your test class. That way you can implement getID() to always return 10 and put in an assert statement inside your publish(). And you can implement whatever other methods you need in order to capture additional data for debugging purposes. And you get to keep this test-only ITransport for either shared use or future debugging needs.
Indeed, the methods are mocked but the internal implementation of the class is left to itself.
Usually, you don't need to know what is returned since you're the one who recorded it in the first place.
You can also evaluate myTransport.getID() in your debugger. But doing this will consume the expectations.
However, it seems like a good idea to be able to list the all current pending expectations on a mock. And maybe to have a peek function. You can request such features on the EasyMock bug tracker: http://jira.codehaus.org/browse/EASYMOCK

Have Code Analysis ignore methods that throw a NotImplementedException

I know there are rules available that fire when a NotImplementedException is left in the code (which I can understand for a release build) (see this answer, or this question), but I would like to have the opposite: have Code Analysis ignore methods that throw a NotImplementedException, as they are known to be unfinished.
Background:
When I develop a block of code, I'd like to test what I have so far, before I'm completely done. I also want CA to be on, so I can correct errors early (like: didn't dispose of resources properly). But as I'm stil developing that code, there are still some stubs that I know will not be used by my test. The body of such a stub usually consists of no more than a throw new NotImplementedException();.
When I build the code, CA complains that the method could be 'static' and that parameters are unused. I know I can suppress the CA-errors, but that means I will have to remember to take those suppressions out when those methods are built and it's an extra build (one to get the messages so I can suppress them and one to really run the code).
My question:
Is there a way to have CA ignore methods that end in a NotImplementedException along (at least) one of the code paths? It would be extra nice if that could be set to only work in debug mode, so you can get warnings about that exception in a release build.
For the record, I'm using VS2010.
No. There is no such option in Code Analysis.
What you could do is write a custom rule which flags the throwing of a NotImplementedException and then process the Code Analysis outcome and remove any entry with the same target method as the NotImplemented custom rule. This rule should be pretty simple to implement. It would probably suffice to search for any Constructor call on the NotImplementedException class.
But this will only work if you run Code Analysis from the commandline and then post-process the xml file.
You could also mark the method using the GeneratedCodeAttribute, as these will be ignored by default.

BDD/TDD: can dependencies be a behavior?

I've been told not to use implementation details. A dependency seems like an implementation detail. However I could phrase it also as a behavior.
Example: A LinkList depends on a storage engine to store its links (eg LinkStorageInterface). The constructor needs to be passed an instance of an implemented LinkStorageInterface to do its job.
I can't say 'shouldUseLinkStorage'. But maybe I can say 'shouldStoreLinksInStorage'.
What is correct to 'test' in this case? Should I test that it stores links in a store (behavior) or don't test this at all?
The dependency itself is not an expected behavior, but the actions called on the dependency most certainly are. You should test the stuff you (the caller) know about, and avoid testing the stuff that requires you to have intimate knowledge of the inner workings of the SUT.
Expanding your example a little, lets imagine that our LinkStorageInterface has the following definition (Pseudo-Code):
Interface LinkStorageInterface
void WriteListToPersistentMedium(LinkList list)
End Interface
Now, since you (the caller) are providing the concrete implementation for that interface it is perfectly reasonable for you to test that WriteListToPersistentMedium() gets called when you invoke the Save() method on your LinkList.
A test might look like this, again using pseudo-code:
void ShouldSaveLinkListToPersistentMedium()
define da = new MockLinkListStorage()
define list = new LinkList(da)
list.Save()
Assert.Method(da.WriteListToPersistentMedium).WasCalledWith(list)
end method
You have tested expected behavior without testing implementation specific details of either your SUT, or your mock. What you want to avoid testing (mostly) are things like:
Order in which methods were called
Making a method, or property public just so you can check it
Anything that does not directly involve the expected behavior you are testing
Again, a dependency is something that you as the consumer of the class are providing, so you expect it to be used. Otherwise there is no point in having that dependency in the first place.
LinkStorageInterface is not an implementation detail - its name suggests an interface to to an engine. In which case the name shouldUseLinkStorage has more value than shouldStoreLinksInStorage.
That's my 2 pennies worth!

Resources