Cannot resolve symbol 'Before' - Intellij jUnit - java

I am new to Intellij IDEA. I'm trying to use jUnit annotations #Before and #After for my selenium tests. Even though I'm importing jUnit in my class, I 'm not able to use the annotations. Any help?
package Config;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
public class browserConfig {
public static WebDriver driver = null;
public static Properties config = new Properties();
public static FileInputStream fis;
#Before
public void initBrowser(){
if (driver ==null){
try{
fis = new FileInputStream(System.getProperty("user.dir") + "//src//main//java//Config//config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Your test should be in the test folder, otherwise idea will ignore the test annotations.
Make sure the class is placed in the src/test/ folder.
Also check in Project Settings -> Modules that your tests folder is present in the structure and has green color (marked as Tests). If it is missing - add it to the modules and mark as Tests.

If you are using gradle to build in Intellij, try adding this to build.gradle.
testCompile('org.springframework.boot:spring-boot-starter-test')
If you aren't using gradle do something similar with whatever controls your dependencies.

Related

Why am I asked to refactor code and include org.testng.AssertJUnit when creating testng.xml suite?

I have two TestNG classes containing a few #Test annotations, nothing fancy, and test methods just under them. When I select both of my class files in Eclipse, right-click, choose TestNG - Convert to TestNG, I am presented with a refacotoring wizard in Eclipse to create said testng.xml suite. But when I cliked Next, I'm asked to refactor my code and include org.testng.AssertJUnit.
Why JUnit? What does JUnit have to do with this?
Here's a code sample:
package seleniumTestovi.Pages; import org.testng.Assert;
import org.testng.annotations.Test;
public class NewTest {
#Test
public void foo() {
Assert.assertTrue(true);
}
}
And here is the code Eclipse wants me to refactor when i try to create testng.xml suite.
package seleniumTestovi.Pages;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class NewTest {
#Test
public void foo() {
AssertJUnit.assertTrue(true);
}
}

Cucumber framework scenarios not found when picocontainer jar is added to java build path

I am trying to build a Cucumber BDD framework with multiple step definition files. I am still trying to understand how to use picocontainer to run the step definition files. My problem is that once I have added the picocontainer jar into a project's build path, when executing the test runner it is unable to find any scenarios or steps.
Console
Java project build path
My project contains:
• A feature file
• 2 step definition files
• 1 test runner
• Utilities package with a webdriver initializer method
My feature file has the following steps:
The first 2 gherkin steps are glued to methods in following step definition class:
package stepDefinitions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import cucumber.api.java.en.Given;
public class SD_HomePage {
WebDriver driver;
#Given ("^the user is on the websites homepages$")
public void user_is_on_the_websites_homepage() {
driver = utilities.WebDriverInitializer.openWebdriver("Chrome");
driver.get("https://www.forExample.com/");
}
#Given("^then clicks on AboutUs title$")
public void then_clicks_on_AboutUs_title() throws Throwable {
driver.findElement(By.xpath("//a[#href='/en/about-us'][1]")).click();
}
}
The third gherkin step is glued to this separate step def class:
package stepDefinitions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import cucumber.api.java.en.When;
public class SD_AboutUsPage {
WebDriver driver;
#When("^the user clicks on Contact widget$")
public void the_user_clicks_on_Contact_widget() throws Throwable {
driver.findElement(By.xpath("//span[#class='icon-envelope listCta__img'][1]")).click();
}
}
When executing the test from the test runner no scenarios or steps will be found by the runner:
package testRunners;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features = "Features", glue = "stepDefinitions")
public class TestRun_NewsletterForm {
}
Console results from the Testrunner
However, when I remove the picocontainer the scenario and steps will be found. This will leave me with the original problem of not being able to make use of a shared state Webdriver.
Test Run after picocontainer jar is removed
I am aware that in this project I have not yet set up a class that will contain the shared state Webdriver, and constructors on the step definition pages. I have another project that has that is affected by this same issue but I felt that it would make this issue more complicated if I used that example.

Unit Testing with different behaviour on existance of a file

There are some cases that the software shall behave differently according to some environmental conditions, for example whether a file exists at some place or not.
In my case, I'm developing a library, and it is configured according to a configuration file in classpath, (and falls back to default behavior if the config file does not exists).
How shall I unit test this class?
I need to write tests for evaluating the class in following cases:
the file does not exists on classpath
the file with content A exist on classpath
the file with content B exist on classpath
But I don't know how to configure environment to justify all of them. And execute the test one after each other.
By the way I'm using Java, and I have both JUnit and TestNG on the test classpath.
Edit:
One of the problems is that the config file resides in classpath, so if the normal ClassLoader finds and loads it, it returns the same content as long as the same class loader is used.
And I believe using a custom ClassLoader for testing is so complicated, that it needs tests to validate the tests!
You can use a temporary file created by your test to mock out the path in your class.
ConfigurationTest.java:
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeThat;
import java.nio.file.Files;
import org.junit.Test;
public class ConfigurationTest {
private Configuration config = new Configuration();
#Test
public void testWithConfigFile() throws Exception {
config.configFile = Files.createTempFile("config_",".ini");
config.configFile.toFile().deleteOnExit();
assertFalse(config.isInDefaultMode());
}
#Test
public void testWithoutConfigFile() throws Exception {
assumeThat(Files.exists(config.configFile), is(false));
assertTrue(config.isInDefaultMode());
}
}
Configuration.java:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Configuration {
Path configFile = Paths.get("config.ini");
public boolean isInDefaultMode() {
return !Files.exists(configFile);
}
}

Why is my import of the containsString method not working?

I've written the simple Java script below in order to learn more about TDD, IntelliJ and Java itself.
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.both;
public class JUnit_Dummy {
private StringJoiner joiner;
private List<String> strings;
#Before
public void setUp() throws Exception {
strings = new ArrayList<String>();
joiner = new StringJoiner();
}
....
#Test
public void shouldContainBothStringsWhenListIsTwoStrings() {
strings.add("one");
strings.add("two");
assertThat(joiner.join(strings),
both(containsString("A")).
and(containsString("B")));
}
}
_____________
import java.util.List;
public class StringJoiner {
public String join(List<String> strings) {
if(strings.size() > 0) {
return (strings.get(0);
}
return "";
}
}
I'm trying to use the "containsString" method inside an assertion, but IntelliJ keeps telling me that it "cannot resolve method 'containsString(java.lang.String)". This despite the fact that the jUnit docs (http://junit.sourceforge.net/javadoc/org/junit/matchers/JUnitMatchers.html#containsString(java.lang.String)) tell me that this method does accept a String parameter.
I've tried swapping out various import statements, including the following:
import static org.hamcrest.Matcher.containsString;
import static org.hamcrest.Matcher.*;
import static org.hamcrest.CoreMatchers.*;
The best that I get is a greyed-out import statement telling me that the import statement is unused. Not sure what the problem is, any help would be appreciated.
UPDATE:
Here is the exact compiler error:
java: cannot find symbol
symbol: method containsString(java.lang.String)
location: class JUnit_Dummy
I thought I had tried every worthwhile import statement already, but this one did the trick:
import static org.junit.matchers.JUnitMatchers.*;
I faced the same issue with a Spring Boot app.
Seems like this is a dependency ordering issue.. one of the dependencies mentioned in pom.xml before the "spring-boot-starter-test" artifact was overriding the hamcrest version.
So all I did was change the order (moved this dependency up):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I'm using Spring Boot 1.5.7.RELEASE.
We are supposed to use containsString method of hamcrest library.
My suggestion would be to stick to Junit 4 and import hamcrest library 1.3 in your build path. This would do the trick.
This will allow you to access other features of hamcrest library as well.
The solution can also be found by adding the required static imports manually. Or you can configure the required static imports in favorites tab of eclipse.
try this instead
import static org.hamcrest.CoreMatchers.*;
I'm working with MAVEN - doing a tutorial and I ran into this same issue.
I used the "import static org.hamcrest.CoreMatchers.*;" solution and that failed.
So I then moved JUNIT to be first on the list in the POM file - and that solved it.

Powermock with Mockito

Im trying to use PowerMock with Mockito, but PowerMock.replayAll(); and PowerMock.verifyAll(); is not found in my Eclipse environment. Used this download link:
http://code.google.com/p/powermock/downloads/detail?name=powermock-mockito-junit-1.5.zip&can=2&q=
And downloaded EasyMock here:
http://sourceforge.net/projects/easymock/files/EasyMock/3.1/easymock-3.1.zip/download
Added all the jars to my libs directory (removed it from my build path). Anyone? Thanks!
Source code Android project and test project:
https://github.com/powder366/test
https://github.com/powder366/testtest
example.
package com.test
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.PowerMockUtils;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Greeter.class)
public class MockStaticExampleTest {
#Test
public void mockStaticExample() throws Exception {
String expectedGreeting = "greeting";
String nameToGreet = "name";
PowerMockito.mockStatic(Greeter.class);
EasyMock.expect(Greeter.getGreeting(nameToGreet)).andReturn(expectedGreeting);
PowerMock.replayAll();
String actualGreeting = Greeter.getGreeting(nameToGreet);
PowerMock.verifyAll();
assertEquals("Expected and actual greeting did not match", expectedGreeting, actualGreeting);
}
}
You have not to add your jars to the Eclipse build path, but you have to place the jars inside the libs folder. ADT will do what takes to import it.
I finally downloaded:
http://code.google.com/p/powermock/downloads/detail?name=powermock-easymock-1.5-full.jar&can=2&q=
and it worked with PowerMock.replayAll(); and PowerMock.verifyAll();

Categories