junit annotation - junit4

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.

Related

OneTimeSetUp runs multiple times in NUnit

The NUnit docs describe how to use SetUpFixture so a chunk of code will execute only once. I'm failing to get this working.
I have read Is it possible to have a [OneTimeSetup] for ALL tests? and https://docs.nunit.org/articles/nunit/writing-tests/attributes/setupfixture.html
I have the following structure for my tests
The actual tests (note the inheritence)
namespace net.UiTests
{
[TestFixture]
[NonParallelizable]
internal class SanityTests : TestBase
{
[SetUp]
public void Initialize()
{
//do stuff
}
[TearDown]
public void TestCleanUp()
{
//do stuff
}
[Test]
public void SomeTest()
{
//do stuff
}
}
}
And the base class, which is where the SetUpFixture lives
namespace net.UiTests
{
[NonParallelizable]
[SetUpFixture]
internal class TestBase
{
[OneTimeSetUp]
public static void AssemblyInit()
{
//do stuff
}
[OneTimeTearDown]
public static void AssemblyCleanup()
{
//do stuff
}
}
}
I am unsure why the AssemblyInit() method executes multiple times. The stack trace gives me no clues other than [External Code]
You have made your base class a SetUpFixture, which is causing the problem.
The SetUpFixture runs once before and once after all the fixtures in your UiTests namespace.
But due to inheritance, each TestFixture now "contains" a OneTimeSetUp and a OneTimeTearDown method. Those methods, when found in a TestFixture, are supposed to run once per fixture class and that's what they do.
To solve the problem, you have to stop using the SetUpFixture as a base class.

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(""));
}
}

NullPointerException when I changed all my methods to static

Using Selenium w Java and Test NG (POM format) Switched everything from not static to static and changed everything accordingly, getting NullPointerException. It worked when everything was not static, but making everything static requires less code so I'd prefer to have it that way.
Here is my code.. while trying to paste my code for some reason it did not recognize the import statements as code so I just did not include them, but rest assured everything has been imported that is needed! :)
Package pages;
public class locationPage {
WebDriver driver;
static #FindBy (id="btn_bogota") WebElement chooseBogota;
static #FindBy (id="btn_medellin") WebElement chooseMedellin;
static #FindBy (xpath="//title") WebElement pageTitle;
public locationPage (WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
public static void chooseLocation (String location) {
if (location.equals("Bogota"))
{
chooseBogota.click();
}
else if (location.equals("Medellin")){
chooseMedellin.click();
}
}
}
Package testcases;
public class selectLocation {
WebDriver driver;
#BeforeClass
public void setup() throws InterruptedException{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://dev01.juanregala.com.co/");
//Generating Alert Using Javascript Executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Select Location');");
Thread.sleep(2000);
driver.switchTo().alert().accept();
}
#AfterTest
public void quit(){
driver.quit();
}
#Test (priority=0)
public void location(){
locationPage.chooseLocation("Medellin");
}
}
It keeps giving me a NullPointerException referring to
chooseMedellin.click();
and
locationPage.chooseLocation("Medellin");
I am not really sure how else to describe my issue :( Please help!
You are getting a NullPointerException because the fields are not initialized. You can't use a page object in this way. Even if you could, you probably wouldn't want to since a page object is tied to a particular web driver and that would mean you could never use the same page object among multiple tests and run them in parallel.
Basically, the PageFactory only works on object instances. It won't initialize static fields and, even if it did, you are only calling the page factory from the constructor of your page and that is never being called since you only call a static method on that class.
You need to create an instance of the page object and then pass it to the PageFactory along with the driver that will be running the page object.
Simple example:
public class FooTest {
private WebDriver driver;
private FooPage page;
#BeforeMethod
public void setup() {
driver = new FirefoxDriver();
page = PageFactory.initElements(driver, FooPage.class);
}
#AfterMethod
public void tearDown() {
try {
driver.quit();
} catch ( Exception ignore ) { }
driver = null;
page = null;
}
#Test
public void testFoo() {
}
}
public class FooPage {
#FindBy(id="foo")
private WebElement fooElement;
public void clickFoo() {
fooElement.click();
}
}
Note the line:
page = PageFactory.initElements(driver, FooPage.class);
That method will actually call the default construct of FooPage. You can also instantiate the object yourself and pass it to the page factory like this:
page = new FooPage();
PageFactory.initElements(driver, page);

How to make NUnit stop executing tests on first failure

We use NUnit to execute integration tests. These tests are very time consuming. Often the only way to detect a failure is on a timeout.
I would like the tests to stop executing as soon as a single failure is detected.
Is there a way to do this?
Using nunit-console, you can achieve this by using the /stoponerror command line parameter.
See here for the command line reference.
For nunit-console v3, it changes to --stoponerror (see here for the command line reference).
I'm using NUnit 3 and the following code works for me.
public class SomeTests {
private bool stop;
[SetUp]
public void SetUp()
{
if (stop)
{
Assert.Inconclusive("Previous test failed");
}
}
[TearDown]
public void TearDown()
{
if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
{
stop = true;
}
}
}
Alternatively you could make this an abstract class and derive from it.
This is probably not the ideal solution, but it does what you require i.e. Ignore remaining tests if a test has failed.
[TestFixture]
public class MyTests
{
[Test]
public void Test1()
{
Ascertain(() => Assert.AreEqual(0, 1));
}
[Test]
public void Test2()
{
Ascertain(() => Assert.AreEqual(1, 1));
}
private static void Ascertain( Action condition )
{
try
{
condition.Invoke();
}
catch (AssertionException ex)
{
Thread.CurrentThread.Abort();
}
}
}
Since TestFixtureAttribute is inheritable, so you could potentially create a base class with this attribute decorated on it and have the Ascertain protected Method in it and derive all TestFixture classes from it.
The only downside being, you'll have to refactor all your existing Assertions.

Capturing timing data from Junit tests on 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(){
//...
}
}