How to Clean resources using teardown of junit class - junit4

I am using Junit4 in eclipse.
The tests are running successfully. but at sometimes, the eclipse got hangs and closes the workspace.
And I have to deploy my code into sonar jenkins. Iam unable to do a stable build with the Junit classes.
My Junit test case goes as follows.
#RunWith(PowerMockRunner.class)
#PrepareForTest({UtilityFunctions.class,EmergencyDoDao.class,
EmergencyDoService.class,
EmergencyDoExport.class,EmergencyDoBusinessManager.class })
public class EmergencyDoServiceTest {
/**
* Run the EmergencyDoService() constructor test.
*
* #generatedBy CodePro at 9/19/13 12:00 PM
*/
#Test
public void testEmergencyDoService_1()
throws Exception {
EmergencyDoService result = new EmergencyDoService();
assertNotNull(result);
// add additional test code here
}
#Test
public void testGetEmergencyDoService_1()
throws Exception {
String dc = "5854";
String beginDate = "1/1/2011 00:00 AM";
String endDate = "9/18/2013 00:00 AM";
String doStr = "*";
String doStatus = "All";
String shipment = "*";
boolean isExport = false;
String sortBy = "CreatedDate,OrderId";
String fileType = "";
BigDecimal scheduleId = null;
BigDecimal jobId = null;
EmergencyDoInputDTO inputDto = new EmergencyDoInputDTO();
inputDto.setDc(dc);
inputDto.setBeginDate(CommonUtil.convertToSqlTimeStamp(beginDate));
inputDto.setEndDate(CommonUtil.convertToSqlTimeStamp(endDate));
inputDto.setDoStr(doStr);
inputDto.setDoStatus(doStatus);
inputDto.setShipment(shipment);
inputDto.setSortBy(sortBy);
inputDto.setExport(isExport);
inputDto.setFileType(fileType);
EmergencyDoMockDAO.mockgetEmergencyDo(inputDto,scheduleId,jobId);
Response result = EmergencyDoService.getEmergencyDoService(dc, beginDate, endDate, doStr, doStatus, shipment, isExport, sortBy, fileType, scheduleId, jobId);
String output = result.getEntity().toString();
Assert.assertEquals(true,output.contains("\"result\": \"Success\""));
}
#Before
public void setUp()
throws Exception {
// add additional set up code here
}
/**
* Perform post-test clean-up.
*
* #throws Exception
* if the clean-up fails for some reason
*
* #generatedBy CodePro at 9/19/13 12:00 PM
*/
#After
public void tearDown()
throws Exception {
// Add additional tear down code here
}
/**
* Launch the test.
*
* #param args the command line arguments
*
* #generatedBy CodePro at 9/19/13 12:00 PM
*/
public static void main(String[] args) {
new org.junit.runner.JUnitCore().run(EmergencyDoServiceTest.class);
}
After lot of struggling, I found that in the teardown of junit class, we can add code to clean the resources.
Can anybody suggest me how to clean the above resources in Junit, so that I can have a stable bulid in jenkins.

I don't see any suspicious code that can possibly block and/or close Eclipse. IIRC setUp() and tearDown() was to init/clean up unit test resources in Junit3. In JUnit 4, it totally depends on #Before and #After annotations.
And can I ask what do you mean "Iam unable to do a stable build with the Junit classes"? If it's unstable build with JUnit classes, that's probably your unit test is broken. Either fixing broken unit test or just disable/delete them(if you don't think those unit tests are useful) would allow you to build stable build.

Related

How to prevent spring batch to start new instance of job?

Idea is not to start job if already same job is running.
JobExplorer is simple injected in class where is scheduled method for running
public class JobClass {
private final Job job;
private final JobExplorer jobExplorer;
private final JobLauncher jobLauncher;
public JobMain(Job job,
JobLauncher jobLauncher,
JobExplorer jobExplorer) {
this.job = job;
this.jobLauncher = jobLauncher;
this.jobExplorer = jobExplorer;
}
and then it is executed
#Scheduled("0 */5 * ? * *")
public void startJob() {
JobParameters jobParameters = new JobParametersBuilder()
.addString("jobName", String.valueOf(instant.toEpochMilli()))
.toJobParameters();
jobLauncher.run(job, jobParameters);
}
This is not solution because if JVM stopped while job is running this will be same as current job running:
jobExplorer.findRunningJobExecutions("jobName")
It will find all jobs with exitCode ExitStatus.UNKNOWN.
There is 3 solutions as I see it:
Solution 1:
stop previous running not finished jobs and run new job
PROS: everything is clean, just one property
CONT: loosing current execution of current job
#Scheduled("0 */5 * ? * *")
public void startJob() {
(JobExecution jobExecution: jobExplorer.findRunningJobExecutions("jobName")) jobExecution.stop();
...
}
Solution 2
Calculate time between latest running job like it is here described and if it is any do not start new job:
https://stackoverflow.com/a/23218986/1182625
PROS: everything is clean
CONT: have to have doubled property (5 *60*1000 and "0 */5 * ? * *")
Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("jobName");
if(jobExecutions.size()>1){
Long currentTime = (new Date()).getTime();
for(JobExecution execution : jobExecutions) {
if((currentTime - execution.getStartTime().getTime()) < 5*60*1000) {
return;
} else {
execution.stop();
}
}
}
Solution 3
Idea is simple to add static (to share between instances of class) volatile (to share between threads) flag which will indicate is any job currently running
PROS: just one property
CONT: needs 2 listeners, and volatile static variable which i don't know how reacted in multi-nodes environment
private static volatile boolean FINISHED = true;
and then simple add listener and FINISHED modify method:
// reset FINISHED after job is done
#AfterJob
public void afterJob() {
FINISHED = true;
}
public void setFinished() {
this.FINISHED = true;
}
And simple add:
#Scheduled("0 */5 * ? * *")
public void startJob() {
if(!FINISHED) return;
FINISHED = false;
...
}
And finally add StepListener
public MyStepListener() {
...
#AfterStep
public ExitStatus afterStep(StepExecution stepExecution) {
if(stepExecution.getExitStatus().getExitCode().equalsIgnoreCase(ExitStatus.FAILED.getExitCode())) (new JobMain()).setFinished();
return null;
}
Ok, I think I go to far with something could be KISS.
Keep It Simple & Stupid.
So, to achieve this is simple to put fixedDelay or fixedStringDelay in #Scheduled annotation if you want to use value from properties file.
#Scheduled(initialDelay = 3*60*1000, fixedDelayString ="${job.fixed_delay}")
With this I achieve that I don't have more than 1 instance of same job at same time.
I only lose that job start at exactly time (like ad midnight or...)
Idea is not to start job if already same job is running.
By design, Spring Batch will prevent that. If you try to start the same job instance while it has a running job execution, you will get a JobExecutionAlreadyRunningException.

When using MockRestServiceServer cannot precisely test number of service calls

I am coding some retry logic for a service call, and attempting to test that the Rest Template is attempting to hit the service a certain number of times, in a unit test. I am using the following code to perform the test.
MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
mockServer.expect(ExpectedCount.times(5), method(HttpMethod.GET))
.andRespond(withServerError());
service.call();
I have the retry logic set to only make two attempts. The above test code requires that it occur five times, but the test always passes. In fact, the only way I can get this test to fail is by setting the expected count to one (anything less than the number of actual invocations). The same sort of problem occurs when I use ExpectedCount.min or ExpectedCount.between in that the test will only fail when actual invocations exceed expectation.
I need to be able to test for an exact number of service calls, preferably without the use of Mockito.
This is what finally worked for me, testing with a max attempts of 4:
MockRestServiceServer server;
#Before
public void setUp() {
server = MockRestServiceServer.bindTo(restTemplate).build();
}
#After
public void serverVerify() {
server.verify();
}
#Test
public void doWork_retryThenSuccess() throws Exception {
final String responseBody = "<some valid response JSON>";
final String url = BASE_URL + "/doWork";
server.expect(requestTo(url))
.andExpect(MockRestRequestMatchers.method(HttpMethod.POST))
.andRespond(ExceptionResponseCreator.withException(new SocketTimeoutException("first")));
server.expect(requestTo(url))
.andExpect(MockRestRequestMatchers.method(HttpMethod.POST))
.andRespond(ExceptionResponseCreator.withException(new IOException("second")));
server.expect(requestTo(url))
.andExpect(MockRestRequestMatchers.method(HttpMethod.POST))
.andRespond(ExceptionResponseCreator.withException(new RemoteAccessException("third")));
server.expect(requestTo(url))
.andExpect(MockRestRequestMatchers.method(HttpMethod.POST))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
final MyResponseClass response = myService.call();
assertThat(response, notNullValue());
// other asserts here...
}
We are constrained to use Spring Test 5.0.10, which doesn't have MockRequestResponseCreators.withException() (method was added in 5.2.2). Borrowing from Spring 5.2.7 code, this works well:
package com.company.test;
import java.io.IOException;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.test.web.client.ResponseCreator;
import org.springframework.test.web.client.response.MockRestResponseCreators;
public class ExceptionResponseCreator extends MockRestResponseCreators {
public static ResponseCreator withException(IOException ex) {
return request -> { throw ex; };
}
public static ResponseCreator withException(RemoteAccessException ex) {
return request -> { throw ex; };
}
}
You can create your own ResponseCreator with the logic you want. For example:
class DelegateResponseCreator implements ResponseCreator {
private final ResponseCreator[] delegates;
private int toExecute = 0;
public DelegateResponseCreator(final ResponseCreator... delegates) {
this.delegates = delegates;
}
#Override
public ClientHttpResponse createResponse(final ClientHttpRequest request) throws IOException {
ClientHttpResponse ret = this.delegates[this.toExecute % this.delegates.length].createResponse(request);
this.toExecute++;
return ret;
}
}
This delegator executes the ResponseDelegates in order.
So you can mock the response for the call number you want
mockServer.expect(ExpectedCount.times(5), MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(new DelegateResponseCreator(
MockRestResponseCreators.withServerError(),
MockRestResponseCreators.withServerError(),
MockRestResponseCreators.withServerError(),
MockRestResponseCreators.withServerError(),
MockRestResponseCreators.withSuccess()
));
In this example, the first four calls will return a server error whereas the fifth will be a success.
You need to call mockServer.verify() after making all your requests to check if the expectations are met. Otherwise, you can get away with never making any requests.

Timer in Drools Fusion not working

I am trying to run following rules in Drool Fusion( Version 5.4.1 ), but it's not working.
Ideally it should print "HELLO WORLD" every 7 seconds, it's not even triggering once.
Can anybody please help me to understand the timer in Drools?
import com.drools.message.Message
rule "Test"
timer(int: 7s 7s)
when
message:Message (type=="Hello")
then
System.out.println("Hello World, Drools! " + message.getMsgtext());
end
My code to run the above Rule is:
public class TestDrools {
private static String DRL_FILE = "test_drools.drl";
private static KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();
private static Collection pkgs;
private static KnowledgeBase kbase = KnowledgeBaseFactory
.newKnowledgeBase();
private static StatefulKnowledgeSession ksession;
private static WorkingMemoryEntryPoint entryPoint;
public static void main(String[] args) {
init();
while (true) {
Message msg = new Message();
msg.setType("Hello");
msg.setMsgtext("1");
ksession.insert(msg);
}
}
private static void init() {
initialiseDrools();
}
private static void initialiseDrools() {
kbuilder.add(ResourceFactory.newClassPathResource(DRL_FILE),
ResourceType.DRL);
if (kbuilder.hasErrors()) {
System.out.println(kbuilder.getErrors().toString());
throw new RuntimeException("Unable to compile drl\".");
}
pkgs = kbuilder.getKnowledgePackages();
KnowledgeBaseConfiguration config = KnowledgeBaseFactory
.newKnowledgeBaseConfiguration();
config.setOption(EventProcessingOption.STREAM);
kbase = KnowledgeBaseFactory.newKnowledgeBase(config);
kbase.addKnowledgePackages(pkgs);
KnowledgeSessionConfiguration conf = KnowledgeBaseFactory
.newKnowledgeSessionConfiguration();
conf.setOption(ClockTypeOption.get("pseudo"));
ksession = kbase.newStatefulKnowledgeSession(conf, null);
entryPoint = ksession.getWorkingMemoryEntryPoint("entryone");
new Thread() {
#Override
public void run() {
ksession.fireUntilHalt();
}
}.start();
}
}
Thank you
-Sanjay
As per #laune's comment, you've used the pseudo clock. If you want to use the realtime clock, change the following line:
conf.setOption(ClockTypeOption.get("realtime"));
Or just remove the line altogether - realtime is the default clock.
If you want to use the pseudo clock, you'll need to advance it yourself. This is typically use in unit testing, e.g.
SessionPseudoClock clock = ksession.getSessionClock();
// insert some facts ...
clock.advanceTime(1, TimeUnit.HOURS);
ksession().fireAllRules();
// Do your unit test asserts / verify mocks here to verify that
// time-reasoned rules were / weren't fired
then condition happens when when condition fulfills,so you need to at least put eval(true) in when condition and trigger an insert into knowledgeSession so that the rule engine figure out what to do when some condition fulfills.

Selenium test wont launch Firefox (java with Netbeans)

I have Selenium IDE installed on Firefox, I ran a simple test on it and I exported the test cases to Netbeans under Java/JUNIT4/WebDriver. When I put the code in Netbeans and try to run it, It doesn't launch firefox. I've another simple program that will launch Firefox and go to google and search for cheese but when I try to export a test that I've ran using Selenium IDE, I can't get it to run. I'm not getting any errors and I get "successful build" when I run it, just nothing happens. Here's my code. Thanks
> Blockquotepackage firstpackage;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
//import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;
public class FirstPackage {
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private boolean acceptNextAlert;
public static void main(String args[]){}
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.get("http://google.com");
baseUrl = "https://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// WebDriver driver = new FirefoxDriver();
System.out.println(driver.getTitle());
}
#Test
public void testGoogleSearch() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Google");
driver.findElement(By.id("gbqfb")).click();
}
#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;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
// TODO code application logic h
> Blockquote
This problem is likely due to incompatible versions of Firefox and Selenium Firefox WebDriver.
My guess is that your program that works (the one that goes to Google and searches for cheese) has a different version of Selenium in its path than the one that NetBeans ends up using for your imported tests from the IDE.
For more information on how to deal with the version compatibility issue, see my answer to this question.
I just ran your code on my machine and it worked as expected. Make sure you're using correct jar files and are correctly mapped in your project.

Problem on aboutBox() in java

I'm developing a javadesktop application in Netbeans 6.9 and everything is perfect but...it gives me an error on this :
#Action
public void showAboutBox()
{
if (aboutBox == null) {
JFrame mainFrame = Mp4App.getApplication().getMainFrame();
aboutBox = new mp4AboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
and this is the error :
Compiling 1 source file to Q:\Mp3 App\mp4-beta\mp4\build\classes
Q:\Mp3 App\mp4-beta\mp4\src\mp4\Mp4View.java:223: cannot find symbol
symbol : class mp4AboutBox
location: class mp4.Mp4View
aboutBox = new mp4AboutBox(mainFrame);
1 error
Q:\Mp3 App\mp4-beta\mp4\nbproject\build-impl.xml:603:
The following error occurred while executing this line:
Q:\Mp3 App\mp4-beta\mp4\nbproject\build-impl.xml:284: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 8 seconds)
the real problem is that this is the code generated from netbeans...also if you create a new Project->java->Destop Application and you leave it there without adding nothing,it gives always me the same problem... what to do ????????????
netbeans version: 6.9.1
jdk version: 7
O.S : Windows 7 32 bit
You shouldn't create your GUI using Netbeans because it generates unreadable code. The Swing-Package is pretty straight forward, so you should use it.
To the Error: Do you have a mp4AboutBox-class and what is in it?
You might be missing an import. Provide your imports in that file.
I had a similar question that I got the solution to by re-installing netbeans 6.9.1.
This is the solution I came up with from that:
TestProject class:
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
public class TestProject extends SingleFrameApplication {
#Override protected void startup() {
show(new AppView(this));
}
#Override protected void configureWindow(java.awt.Window root) { }
public static TestProject getApplication() {
return Application.getInstance(TestProject.class);
}
public static void main(String[] args) {
launch(TestProject.class, args);
}
}
AppView JFrame:
import org.jdesktop.application.FrameView;
import org.jdesktop.application.SingleFrameApplication;
public class AppView extends FrameView {
public AppView(SingleFrameApplication app) {
super(app);
JFrame mainFrame = TestProject.getApplication().getMainFrame();
AboutBox newAboutBox = new AboutBox();
newAboutBox.setLocationRelativeTo(mainFrame);
TestProject.getApplication().show(newAboutBox);
}
}