Java passing value - java

I have three programs,
first does a selenium test
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;
import junit.framework.*;
public class MyTest extends SeleneseTestCase {
int flag_eco;
public void setUp() throws Exception {
setUp("http://www.mysite.com/", "*iexplore");
}
public void testMyTest() throws Exception {
selenium.open("/pages/static/homepage_logout.html");
selenium.type("username", "myuser");
selenium.type("password", "password");
selenium.click("//input[#value='LOGIN']");
selenium.waitForPageToLoad("30000");
selenium.click("Confirm");
selenium.waitForPageToLoad("30000");
selenium.click("link=Applications");
selenium.waitForPageToLoad("30000");
selenium.click("link=Journey");
selenium.waitForPageToLoad("30000");
selenium.click("link=Launch Application (MUST BE LOGGED IN)");
selenium.waitForPageToLoad("30000");
if((selenium.isTextPresent("Please enter one of the following:")))
{
System.out.println("Journey Working Fine");
flag_test= 0;
}
else
{
System.out.println("Journey Failed");
flag_test = 1;
}
selenium.selectFrame("topmenu");
selenium.click("link=Home");
}
public static Test suite() {
//method added
return new TestSuite(MyTest.class);
}
public void tearDown(){
//Added . Will be called when the test will complete
selenium.stop();
}
}
then a sendmail gettin the values from the selenium test
import java.util.*;
public class SendMail
{
public void send()
{
MyTest Test = new MyTest();
if (Test.flag_test==1)
{
System.out.println("Journey Failed");
}
else if(Test.flag_test==0)
{
System.out.println("Journey Working Fine");
}
}
}
main class calling both
import java.io.*;
import javax.servlet.*;
public class Test
{
public static void main(String args[])
{
MyTest tes = new MyTest();
junit.textui.TestRunner.run(tes.suite());
SendMail se = new SendMail();
se.send();
}
}
how do i pass the flag value from MyTest to SendMail

The flag should be public static (I don't see it defined in the code you provided) - i.e.
public class MyTest {
public static int flag;
// the rest of the code
}
in send() you can refer to it with MyTest.flag_test
Note, that this is not a good way of passing data, but in your case there isn't anything better.
I think you are doing something that shouldn't be done at all. Here's what I propose:
move the code that is changing the flag outside the test
include it in the test, in the appropriate place (as if it is there)
include it in SendMail as well.
Thus you won't need to invoke the test in order to obtain a flag.

Three ways of achieving this
1. Pass the test as parameter to SendMail (already mentioned)
2. Write a listener on test, (Observable pattern/ PropertyChangeSupport in java) and hook it up. (Best IMO)
3. Write to a Static object which acts as white board and read from there. ( a poor man's message queue)

Related

How To Write a Java Unit Test for the Method inside Another Method?

Public Class DailyJob(){
public void runJob(ScheduleJob currentJob) {
try {
int employee = employeeService.getEmployeeNum();
JobPerformance jobPerformance = performanceService.searchJobPerformance(employee);
if(jobPerformance.size() >0 ) {
currentJob.setRecord("success");
}
else {
currentJob.setRecord("failed");
}
}
catch{
//catch error
}
}
}
By now I want to write a Junit test for runJob(). But how can I setup the value I prefer into 'employee' parameter in Junit Test while I test runJob()? Anyone know how to implement it?
You can use Mockito. You setup stubbing, which will return desired value. Also you can stub for multiple calls by
.thenReturn(9, 10, 7);
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MyTest {
#Test
void test() {
EmployeeService employeeService = mock(EmployeeService.class);
when(employeeService.getEmployeeNum()).thenReturn(9);
}
}

How to keep cucumber Scenario object alive?

How can I create Scenario object in cucumber framework and keep alive through all test run?
First Class:
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import io.cucumber.java.en.Given;
public class TestStepDefinitionOne {
Scenario scenario;
#Before
public void keepScenario(Scenario scenario) {
this.scenario = scenario;
}
Given("First step")
public void first_step() {
// Some code
scenario.log("Some text");
}
Given("Second step")
public void second_step() {
// Some code
scenario.log("Some text");
}
}
Second Class:
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import io.cucumber.java.en.Given;
public class TestStepDefinitionTwo {
Scenario scenario;
#Before
public void keepScenario(Scenario scenario) {
this.scenario = scenario;
}
Given("First step")
public void first_step() {
// Some code
scenario.log("Some text");
}
Given("Second step")
public void second_step() {
// Some code
scenario.log("Some text");
}
}
If I create #Before method in each step definition class everything works fine.
My question: Is there any way to create Scenario object in one place (like Hooks class) and keep it alive through all test run?

Error when using the same string in different tests

I have the following scenario:
I perform several tests (#Test) and tests in Cucumber, in Selenium Webdriver, Java.
The tests are going well. However, I want to leave a string stored in one #Test (public void) in another #Test (public void). I cannot.
Could anyone help?
First test:
#Test
public void testDocuments() {
OneClass oneClass = new OneClass();
oneClass.one();
oneClass.two();
}
Second test:
#Test
public void testDocuments() {
OneClass oneClass = new OneClass();
oneClass.one();
oneClass.two();
}
Method one
public String one() {
if (this.cnpj == null) {
this.cnpj = add.cnpj(false);
} else {
}
return this.cnpj;
}
Both tests I want you to use the same generated string !!!!
I look forward and thanks in advance!
I'm not sure what your method one() does, but assuming you want to use the same value for two different tests, why not just do this:
OneClass oneClass = new OneClass();
String yourGeneratedString = oneClass.one();
// First test
#Test
public void testDocuments() {
yourFunction(yourGeneratedString);
}
// Second test
#Test
public void testDocuments2() {
yourOtherFunction(yourGeneratedString);
}
If I understand correctly, you need this.cnpj value to be available within the second test?
Each time you do new OneClass() , it creates a new instance of it.
So you can do one of the following:
Use singleton instance of OneClass
Make cnpj a static field within OneClass
If I understand it right, you want to share data from one test to second one. If you user testNG then you can do it this way.
import org.testng.ITestContext;
import org.testng.annotations.Test;
public class MyTest {
#Test
public void testOne(ITestContext context){
context.setAttribute("myKey", "myValue");
}
#Test
public void testTwo(ITestContext context){
String valueFromTestOne = (String) context.getAttribute("myKey");
System.out.println("My key = " + valueFromTestOne);
}
}

PowerMock: How to unmock a method?

I have a static method that is mocked using PowerMock to throw an exception. (It deletes files.) Unfortunately, during my #After (after-each-test) method, I need to call this method without the mocks. How can I umock a method?
I don't see an equivalent to Mockito.reset(). [ Ref: mockito : how to unmock a method? ]
Example:
#RunWith(PowerMockRunner.class)
#PrepareForTest(PathUtils.class) // Important: This class has a static method we want to mock.
public class CleaningServiceImplTest2 extends TestBase {
public static final File testDirPath = new File(CleaningServiceImplTest2.class.getSimpleName());
#BeforeClass
public static void beforeAllTests() throws PathException {
recursiveDeleteDirectory(testDirPath);
}
#AfterClass
public static void afterAllTests() throws PathException {
recursiveDeleteDirectory(testDirPath);
}
private File randomParentDirPath;
private CleaningServiceImpl classUnderTest;
#Before
public void beforeEachTest() {
randomParentDirPath = new File(testDirPath, UUID.randomUUID().toString()).getAbsoluteFile();
classUnderTest = new CleaningServiceImpl(randomParentDirPath);
}
#After
public void afterEachTest() throws PathException {
recursiveDeleteDirectory(randomParentDirPath);
}
public static void recursiveDeleteDirectory(File dirPath) throws PathException {
// calls PathUtils.removeFile(...)
}
#Test
public void run_FailWhenCannotRemoveFile() throws IOException {
// We only want to mock one method. Use spy() and not mockStatic().
PowerMockito.spy(PathUtils.class);
// These two statements are tightly bound.
PowerMockito.doThrow(new PathException(PathException.PathExceptionReason.UNKNOWN, randomParentDirPath, null, "message"))
.when(PathUtils.class);
PathUtils.removeFile(Mockito.any(File.class));
classUnderTest.run();
}
}
This took me a while to figure out, so I am answering my own question.
AFAIK, you need to "undo" each mock. Mockito.reset() will not work with Class<?> references. At the end of the test method, add:
// Undo the mock above because we need to call PathUtils.removeFile() within #After.
PowerMockito.doCallRealMethod().when(PathUtils.class);
PathUtils.removeFile(Mockito.any(File.class));
The only way you can undo mocking of a static method with PowerMock is when you mock a class at the beginning of a test and then undo the mock at the end of a test. It doesn't matter if you use SPY or a regular mocking.
Tested with:
"org.powermock" % "powermock" % "1.5" % Test,
"org.powermock" % "powermock-api-mockito" % "1.6.1" % Test,
Test class
package mytests;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.fest.assertions.Assertions.assertThat;
#RunWith(PowerMockRunner.class)
#PrepareForTest({StaticTest.class})
public class TestTest {
#Before
public void checkIfOriginalMethodGetsCalled() {
// PowerMockito.mockStatic(StaticTest.class); if you do this in #Before you are not going to be able to undo it
assertThat(StaticTest.staticMethod()).isEqualTo("ORIGINAL VALUE");
assertThat(StaticTest.otherStaticMethod()).isEqualTo("SPY TEST ORIGINAL");
}
#Test
public void test1() {
assertThat(StaticTest.staticMethod()).isEqualTo("ORIGINAL VALUE");
}
#Test
public void test3_mocking() {
mock(); // mock or spy static methods in a test, not in #Before
Mockito.when(StaticTest.staticMethod()).thenReturn("MOCKED VALUE");
assertThat(StaticTest.staticMethod()).isEqualTo("MOCKED VALUE");
assertThat(StaticTest.otherStaticMethod()).isEqualTo("SPY TEST ORIGINAL");
undoMock(); // undo the mock at the end of each test, not in #After
}
private void mock() {
// PowerMockito.mockStatic(StaticTest.class); both, spy and mockStatic work ok
PowerMockito.spy(StaticTest.class);
}
private void undoMock() {
PowerMockito.doCallRealMethod().when(StaticTest.class);
assertThat(StaticTest.staticMethod()).isNull(); // the undo is going to work in the next test, not here yet.
}
#Test
public void test2() {
assertThat(StaticTest.staticMethod()).isEqualTo("ORIGINAL VALUE");
}
#After
public void checkIfOriginalMethodGetsCalled_AfterMockUndo() {
// undoMock(); in #After doesn't work with static methods
assertThat(StaticTest.staticMethod()).isEqualTo("ORIGINAL VALUE");
assertThat(StaticTest.otherStaticMethod()).isEqualTo("SPY TEST ORIGINAL");
}
}
class StaticTest {
public static String staticMethod() {
return "ORIGINAL VALUE";
}
public static String otherStaticMethod() {
return "SPY TEST ORIGINAL";
}
}

How to get the name of the class that is acted upon by listener of TestNG?

Hello I have a simple testNG project which has a SampleTest.java class file which has 2 test cases and I have added a listener called MyListener to it . For this I have a MyListener.java class file which extends the TestListener of TestNG where in I'm printing pass or fail or skipped depending upon the test case execution. So every time i run SampleTest I can see Pass/fail in the console.. But I want it with the classname
My problem statement is, How can i get the Test Case file name (i.e. Sampletest here) in the MyListener class??? I tried with stacktrace but no help.. As I guess its not being called but its just acting upon/listening to the testcases in the file.. Please let me know how can I get the name of that class in listener????
SampleTest.java:
package com.abc;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
#Listeners({ com.mindtree.MyListener.class})
public class SampleTest {
#Test
public void SampleTest() throws Exception{
System.out.println("Hello world");
}
#Test
public void SampleTest1() throws Exception{
System.out.println("Hello Swarna");
}
}
MyListener.java:
package com.abc;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
public class MyListener extends TestListenerAdapter {
private int m_count = 0;
#Override
public void onTestFailure(ITestResult tr) {
log("Fail");
}
#Override
public void onTestSkipped(ITestResult tr) {
log("Skipped");
}
#Override
public void onTestSuccess(ITestResult tr) {
log("\nSuccess\n");
## WANT TO PRINT HERE THE TESTCASE CLASS NAME
}
private void log(String string) {
System.out.print(string);
if (++m_count % 40 == 0) {
System.out.println("");
}
}
}
but wont work for multiple testcase files.. Just create an object of SampleTest in MyListener access the classname through getters and setters
From your description I understand you want to get the name of the class where your #Test annotated test-methods reside, and only the class name without the package name
In your case that would be the output: "SampleTest".
You can achieve this the following way:
public void onTestSuccess(ITestResult tr) {
log("\nSuccess\n");
String className = tr.getTestClass().getRealClass().getSimpleName()
log(className);
}
The solution of #JacekM also works fine but in your case would return "com.abc.SampleTest"
None of the solution posted worked for me, however I found that it is possible to get the required information by accessing the "ITestResult" object in the following manner:
public void onTestSuccess(ITestResult result) {
log("\nSuccess\n");
String className = result.getInstanceName();
log(className);
}
NOTE: The above code was tested on my environment successfully
You can find out by examining the stacktrace like:
StackTraceElement trace[] = Thread.currentThread().getStackTrace();
you can get the the calling class by trace[i].getClassName().
Note this is pretty expensive, so don't use in loggers etc.
Use a beforeMethod method in which you can get the name of the method
#BeforeMethod
public void beforeMethod(final Method method) throws Exception {
String testName = method.getName();
}
You have the access to ITestResult object, so you should be able to do:
public void onTestSuccess(ITestResult tr) {
String className = tr.getMethod().getTestClass().getName();
System.out.println(className);
}

Categories