Capturing timing data from Junit tests on Eclipse - eclipse

Running on Eclipse Galileo (3.5), I noticed my tests show the timing of each test run. Is there a way to capture and this information? Is there an API or is it stored in a result file?
Screenshot
http://ge.tt/3ylDyiq

We could use Rule to get time durations for each test method:
class TimeConsumeRule implements MethodRule {
#Override
public Statement apply(final Statement base, final FrameworkMethod method, Object target) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
long start = System.currentTimeMillis();
try {
base.evaluate();
} finally {
System.out.println(method.getName()+ " used "+ (System.currentTimeMillis() - start)+" ms;");
}
}
};
}
}
public class TimeConsume {
//Just declare customized Rule in your test case.
#Rule
public MethodRule rule = new TimeConsumeRule();
#Test
public void test1(){
//...
}
#Test
public void test2(){
//...
}
}

Related

How beforeScenario and afterScenario works in JBehave

Can someone show examples of how beforeScenario and afterScenario works in JBehave?
I created a class with two methods gearUp with #BeforeScenario and tearDown with #AfterScenario annotations.
But these methods are never invoked in JBehave.
What extra configurations are needed. Any code examples will help us.
Whereas this simple and neat in Cucumber.
Following is my story file with single step(src/test/resources/storeis):
Scenario: SampleTest
Given I am test
Following is my Steps file
public class jbehavetc {
#Given("I am test")
public void startOnUrl(String url) {
System.out.println("I am actual test");
}
}
Following is my Hooks file which contains BeforeScenario and AfterScenario methods
public class Hooks {
#BeforeScenario
public void startSystem() throws Exception {
System.out.println("I am before scenario");
}
#AfterScenario
public void stopSystem() throws Exception {
System.out.println("I am after scenario");
}
}
To run the above story i created a runner file and wanted to run as JUnit Test(Correct me this is not the right approach)
public class JBehaveRunner extends JUnitStory{
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(
new LoadFromClasspath(getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML));
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new jbehavetc(),
new Hooks());
}
public List<String> storyPaths() {
return new StoryFinder().findPaths(
CodeLocations.codeLocationFromClass(this.getClass()),
Arrays.asList("**/*.story"),
Arrays.asList(""));
}
#Test
public void run() throws Throwable {
super.run();
}
}
When i run above runner as JUnit test, nothing is getting executed. How can i run above story? I want Before and After Scenario methods needs to be invoked when i run this runner or story file.
You should treat class with #BeforeScenario/#AfterScenario as classes with step implementations: you should register them in your steps factory.
BeforeAndAfterSteps.java
public class BeforeAndAfterSteps {
#BeforeScenario
public void beforeScenario() throws Exception {
// setup
}
#AfterScenario
public void afterScenario() throws Exception {
// teardown
}
}
Example of steps factory configuration
new InstanceStepsFactory(configuration, new BeforeAndAfterSteps())
Official JBehave examples:
Example of the class containing various before/after implementations: BeforeAfterSteps
Examples of this class references and usages:
CoreEmbedder
CoreStory
CoreStories
Following runner file started working for me:
public class JBehaveRunner extends JUnitStories {
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(
new LoadFromClasspath(getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML));
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new HomePageSteps(),
new BaseEngine());
}
#Test
public void run() throws Throwable {
super.run();
}
#Override
public List<String> storyPaths() {
return new StoryFinder().findPaths(
CodeLocations.codeLocationFromClass(this.getClass()),
Arrays.asList("**/*.story"),
Arrays.asList(""));
}
}

Guava EventBus: pause event posting

Is there any way to pause event posting by the EventBus from the guava library.
I have a method changeSomething() that posts an event (e.g. SomethingChangedEvent). Now this method is called in a loop by another method doStuff().
The problem is that the SomethingChangedEvent is posted on every call to changeSomething() even though only the last change matters. Due to the fact that the handlers of the event execute some heavy-weight calculations, the performance of the application degrades fast.
After the last time changeSomething() is executed I would like to tell guava to resume event processing.
Is there any way to tell guava to ignore all SomethingChangedEvents except the very last one?
I tried this pattern, derived from the poison pill pattern using sub-classing :
public class SomethingChangedEvent {
private final String name;
public SomethingChangedEvent(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
public class IgnoreSomethingChangedEvent extends SomethingChangedEvent {
public IgnoreSomethingChangedEvent(String name) {
super(name);
}
}
public class HandleSomethingChangedEvent extends SomethingChangedEvent {
public HandleSomethingChangedEvent(String name) {
super(name);
}
}
private void eventBusTest() {
EventBus eventBus = new EventBus();
eventBus.register(new EventBusSomethingChanged());
eventBus.post(new SomethingChangedEvent("process this one"));
eventBus.post(new IgnoreSomethingChangedEvent("ignore"));
eventBus.post(new SomethingChangedEvent("don't process this one"));
eventBus.post(new HandleSomethingChangedEvent("handle"));
eventBus.post(new SomethingChangedEvent("process this one bis"));
}
public class EventBusSomethingChanged {
private boolean ignore;
#Subscribe
public void SomethingChanged(SomethingChangedEvent e) {
if (e instanceof IgnoreSomethingChangedEvent) {
ignore = true;
return;
}
if (e instanceof HandleSomethingChangedEvent) {
ignore = false;
return;
}
if (!ignore) {
System.out.println("processing:" + e);
}
}
}

CDI - Injecting objects dynamically at runtime

How do I inject objects at runtime? For example, if I want to inject DerviedOne, DerivedTwo objects at runtime into the Test class in the following example, how do I do that? I found a few examples in Spring, but I'm not using Spring. This is a Dynamic Web Project with CDI using Java EE 6.
public abstract class Base
{
public Base(String initiator)
{
this.initiator = initiator;
}
public abstract void process();
public void baseProcess()
{
System.out.println("base process");
process();
}
public String getInitiator()
{
return initiator;
}
private String initiator;
}
public class BaseUtil
{
public long start()
{
return System.currentTimeMillis();
}
public long stop()
{
return System.currentTimeMillis();
}
}
public class DerivedOne extends Base
{
public DerivedOne(String initiator)
{
super(initiator);
}
#Override
public void process()
{
long start = baseUtil.start();
System.out.println(getInitiator() + " process");
long stop = baseUtil.stop();
System.out.println(stop - start);
}
#javax.inject.Inject
private BaseUtil baseUtil;
}
public class DerivedTwo extends Base
{
public DerivedTwo(String initiator)
{
super(initiator);
}
#Override
public void process()
{
long start = baseUtil.start();
System.out.println(getInitiator() + " process");
long stop = baseUtil.stop();
System.out.println(stop - start);
}
#javax.inject.Inject
private BaseUtil baseUtil;
}
#Startup
#Singleton
public class Test
{
#PostConstruct
public void init()
{
String initiator = "two";
Base base = null;
if("one".equals(initiator))
{
base = new DerivedOne("DerivedOne");
}
else if("two".equals(initiator))
{
base = new DerivedTwo("DerivedTwo");
}
base.baseProcess();
}
}
If you want to select one implementation based on runtime conditions You can use a producer method with qualifiers.
For testing CDI application I highly recommend Arquillian.
http://arquillian.org/

junit annotation

I wish to launch the GUI application 2 times from Java test. How should we use #annotation in this case?
public class Toto {
#BeforeClass
public static void setupOnce() {
final Thread thread = new Thread() {
public void run() {
//launch appli
}
};
try {
thread.start();
} catch (Exception ex) { }
}
}
public class Test extends toto {
#Test
public void test() {
setuptonce();
closeAppli();
}
#test
public void test2()
{
setuptonce();
}
}
To launch it a second time, which annotation should I use? #afterclass?
Method annotated with #BeforeClass means that it is run once before any of the test methods are run in the test class. Method annotated with #Before is run once before every test method in the class. The counterparts for these are #AfterClass and #After.
Probably you are aiming for something like the following.
#BeforeClass
public static void setUpClass() {
// Initialize stuff once for ALL tests (run once)
}
#Before
public void setUp() {
// Initialize stuff before every test (this is run twice in this example)
}
#Test
public void test1() { /* Do assertions etc. */ }
#Test
public void test2() { /* Do assertions etc. */ }
#AfterClass
public static void tearDownClass() {
// Do something after ALL tests have been run (run once)
}
#After
public void tearDown() {
// Do something after each test (run twice in this example)
}
You don't need to explicitly call the #BeforeClass method in your test methods, JUnit does that for you.
The #BeforeClass annotation is used to run something once, before test actually runs.
So, depending on what do you want to get (and why), you can simply wrap launch code in a cycle, move launch code in other method and call it from somewhere else or write separate test case.

GWT Void remote services fail for seemingly no reason

I'm working on a GWT project and have several void remote services that seem to execute just fine, but on the client side, end up firing the onFailure() method. No exceptions are thrown anywhere, and the expected behavior is observed on the backend. I have no idea what could be going wrong. Here is the relevant code:
Interfaces and implementation...
#RemoteServiceRelativePath("DeleteSearchService")
public interface DeleteSearchService extends RemoteService {
/**
* Utility class for simplifying access to the instance of async service.
*/
public static class Util {
private static DeleteSearchServiceAsync instance;
public static DeleteSearchServiceAsync getInstance(){
if (instance == null) {
instance = GWT.create(DeleteSearchService.class);
}
return instance;
}
}
public void delete(SearchBean search);
}
public interface DeleteSearchServiceAsync {
public void delete(SearchBean bean, AsyncCallback<Void> callback);
}
public class DeleteSearchServiceImpl extends RemoteServiceServlet implements DeleteSearchService {
private static final long serialVersionUID = 1L;
#Override
public void delete(SearchBean search) {
try {
Connection conn = SQLAccess.getConnection();
String sql = "DELETE FROM `searches` WHERE `id`=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
sql = "DELETE FROM `searchsourcemap` WHERE `search-id` = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
return;
} catch (Exception e) {
// TODO Log error
e.printStackTrace();
}
}
}
Calling code...
private class DeleteListener implements ClickListener {
public void onClick(Widget sender) {
DeleteSearchServiceAsync dss = DeleteSearchService.Util.getInstance();
SearchBean bean = buildBeanFromGUI();
dss.delete(bean, new AsyncCallback<Void>(){
//#Override
public void onFailure(Throwable caught) {
// TODO log
SearchNotDeleted snd = new SearchNotDeleted();
snd.show();
}
//#Override
public void onSuccess(Void result) {
SearchDeleted sd = new SearchDeleted();
sd.show();
searchDef.getParent().removeFromParent();
}
});
}
}
I know I'm a jerk for posting like 500 lines of code but I've been staring at this since yesterday and can't figure out where I'm going wrong. Maybe a 2nd set of eyes would help...
Thanks,
brian
LGTM I'm afraid.
Are you using the hosted mode or a full-fledged browser? You can try switching and see if it helps.
Also, it might help listening to that //TODO and perform a GWT.log when onFailure is invoked.