groovy is not finding annotated tests - groovy

Still new to Groovy and trying to figure out unit testing. I'm trying to use the Junit4 style of testing.
import org.junit.Test
import junit.framework.*
import junit.textui.TestRunner
class DegenerateTestCase {
#Test
void testAlwaysTrue() {
assert true
}
#Test
void someMethodName() {
assert true
}
}
TestRunner.run(DegenerateTestCase)
But when I run the script, I get
There was 1 failure:
warning(junit.framework.TestSuite$1)junit.framework.AssertionFailedError:> No tests found in DegenerateTestCase
This has to be something simple that I'm missing.

I am using Eclipse Java EE IDE for Web Developers, Oxygen.3a Release (4.7.3a). I have the Groovy plugin downloaded from the marketplace (compiler level 2.5).
I tried running it with junit5 which had only one difference which was instead of having import org.junit.Test I had import static org.junit.jupiter.api.Assertions.*. I didnt need import junit.framework.* or import junit.textui.TestRunner I just ran it as is and worked fine.
I then switched to Junit4 and did the same but switched import static org.junit.jupiter.api.Assertions.* to import org.junit.Test and it works.
my code looks like this:
import org.junit.Test
class DegenerateTestCase {
#Test
void testAlwaysTrue() {
assert true
}
#Test
void someMethodName() {
assert true
}
}

Related

Junit mockito unit test case gives null pointer exception

Hello i am new in Junit mockito i am trying to write a unit test
case but when i am run the test case i am getting null pointer
exception.
Code Snip:
package com.dataguise.webservices;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import com.dataguise.cache.CacheManager;
import com.dataguise.controller.CentralController;
import com.dataguise.webservices.beans.DgUserAuthorities;
class RestAPIsTest {
#InjectMocks
private CentralController controller;
#Mock
DgUserAuthorities dgUserAuthorities;
#Mock
private CacheManager cacheManager;
#BeforeEach
public void setup() {
when(this.cacheManager.getCache(anyString())).thenReturn(true);
MockitoAnnotations.initMocks(this);
}
#Test
void testSession() {
try {
dgUserAuthorities = controller.login("d", "d", "", false);
when(controller.login("d", "d", "", false)).thenReturn(dgUserAuthorities);
assertEquals(dgUserAuthorities, dgUserAuthorities);
} catch (Exception e) {
e.printStackTrace();
}
}
}
While the same method call in the rest api gives the appropriate result.
There are 2 errors in your test
Error 1: Mixing JUnit4 and JUnit5 annotations
org.junit.jupiter.api.Test is from JUnit 5
org.junit.Before is from JUnit 4
Thus, your #Before method is never executed. Use org.junit.jupiter.api.BeforeEach instead
Error 2: Using Spring annotations without Spring Extension
#Autowired comes from Spring's DI framework. It will be injected only if you use Spring Injection/ runner
If you want MockitoAnnotations.initMocks(this); to build object under test and inject all mocks, use #InjectMocks
Error 3: confusing way of initializing mocks
There are 2 ways to initialize your mocks:
Manually:
this.dgUserAuthorities = mock(DgUserAuthorities.class);
this.controller = new CentralController(this.dgUserAuthorities);
Using annotations
#InjectMocks
private CentralController controller;
#Mock
DgUserAuthorities dgUserAuthorities;
Annotations require a call to MockitoAnnotations.initMocks(this) or using a Mockito Extension: #ExtendWith(MockitoExtension.class)
I strongly discourage you to mix the 2 approaches.
Also, if you use annotations, do not initialize the fields yourself.

Running Groovy test cases with JUnit 5

Maybe this is very simple, but I couldn't find any examples on the web:
I'd like to use JUnit 5 to run a unit test implemented as a Groovy class. My current setup seems to launch JUnit 5, but fail to detect the test case. IntelliJ recognizes the test, but fails to run it. If I add a Java unit test, it is launched correctly.
Here's what I have now:
Project structure
src
main
groovy
# production code
test
groovy
UnitTest.groovy
build.gradle
...
build.gradle
plugins {
id 'groovy'
}
dependencies {
compile localGroovy()
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.1'
}
test {
useJUnitPlatform()
}
UnitTest.groovy
import org.junit.jupiter.api.Test
class UnitTest {
#Test
def shouldDoStuff() {
throw new RuntimeException()
}
}
I'm using Gradle 4.10.
Any ideas?
JUnit requires all testing method to use return type void. Groovy's def keyword is compiled to an Object type, so your method compiles to something like this in Java:
import org.junit.jupiter.api.Test
public class UnitTest {
#Test
Object shouldDoStuff() {
throw new RuntimeException();
}
}
If you try this out as a Java test, it won't find the test case neither. The solution is very simple - replace def with void and your Groovy
test case will be executed correctly.
src/test/groovy/UnitTest.groovy
import org.junit.jupiter.api.Test
class UnitTest {
#Test
void shouldDoStuff() {
throw new RuntimeException()
}
}
Demo:

How to launch browser using selenium with cucumber

I am newbie for cucumber framework, I have worked on selenium webdriver using testNG framework. I have to start cucumber framework, I have installed cucumber plugin to eclipse but dont know how to start writting code.
And what is the difference between cucumber and cucumber-jvm, and which is the best?
Could anyone pls help me out?
Thanks in advance.
You can find lots of info on what dependecies you should use for your project on the Cucumber main site Cucumber Documentation
Cucumber base is Ruby
Cucumber-JVM is Java
start with creating a src/test/resources
create a file named anything you want (keep it to the thing you want to test) and end it with .feature
Feature: Calculator should work accourding to standard calculator devices
Scenario: addition
Given a calculator I just turned on
When I add 4 and 5
Then the result is 9
put this in as a guide line and try to run it. it should give you a call missing steps.
create a new java file in src/test/java and call it RunCukesTest this wil later be the starter of all your features.
the output you just got from the feature in the console can be put in a .java call it something to do with the feature like CalculatorSteps.java put this in the same folder as your RunCukesTest.java
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(
monochrome = false,
plugin = {"pretty","json:target/cucumber.json"} ,
features = "src/test/resources/cucumber",
tags = "~#ignore"
)
public class RunCukesTest {
}
this is the basic you need to start using Cucumber (there is a start example on github)
Now the Selenium question
you will have to initiate a WebDriver _driver;
with driver you create a new ChromeDriver or FireFoxDriver etc
some browsers need a installation ChromeDriver firefox is built in (to my best knowledge)
see the code below
ask if there is anything you don't get
import java.util.concurrent.TimeUnit;
import cucumber.api.java.en.*;
import org.eclipse.jetty.util.thread.Timeout;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NavigationSteps {
WebDriver _driver;
#Given("^i am at \"([^\"]*)\"$")
public void i_am_at_home(String arg1) throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
_driver = new ChromeDriver();
_driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
_driver.get(arg1);
Thread.sleep(500);
}
#When("^i click on \"([^\"]*)\"$")
public void i_click_on(String arg1) throws Throwable {
_driver.findElement(By.linkText(arg1)).click();
Thread.sleep(500);
}
#Then("^i expect the title to be \"(.*?)\"\"(.*?)\"$")
public void i_expect_the_title_to_be(String arg1, String arg2) throws Throwable {
String result = (arg1 + " | " + arg2);
Thread.sleep(200);
assertEquals("Title should be",result,_driver.getTitle());
tearDown();
}
#Then("^Header should contain \"(.*?)\"$")
public void header_should_contain(String arg1) throws Throwable {
Thread.sleep(200);
assertEquals("Title should be", arg1, _driver.findElement(By.xpath(".//*[#id='main']/div[1]/div/h1")).getText());
tearDown();
}
#After
public void tearDown() throws InterruptedException
{
_driver.quit();
}
}
EDIT - answers to the questions in nicer format
feature file calls the java file (Run via RunCukesTest or feature file)
the methods to test go into je java steps file
Feature calculator has a CalculatorSteps.java file the scenario is in the feature file the methods in the steps
No, the console outputs this as a Regex to identify the corresponding step the test u write in the method below it.
Given a calculator I just turned on
results into
#Given ("^a calculator I just turned on$")
public void iCanCallThisAnythingIWant(){
#do something
}
see answer 2
Given When Then are the logical way to read a Scenario to keep things readable it should be used in that way. If you find yourself with a long Given When or Then u can split the sentence with a "and" in between. but it doesn't matter in what way u write them.

How can I make Selenium tests inside my JSF project?

I have quite big JSF 1.2 project and I want to write some integration tests to it.
The perfect situation will be, when I can run these tests from my project and it opens my browser and makes all the actions (with Selenium), which are written in my test cases. Ofc opening browser is not required when It will run these tests anyway :)
I've tried a few possibilities, anyway I still can't attach any selenium library to my project and I realized that I just dont know where to start - can you give me some direction?
might help you ,
you can write you test logic inside test method
package com.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
public class test1 {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new InternetExplorerDriver();
driver = new ChromeDriver();
baseUrl = "http://www.google.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Ignore
#Test
public void test1() throws Exception {
// your test code
}
#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;
}
}
}
you just need call test1 class which you want to test it .
it will be automatically working on it .

Unit tests - run task programmatically

I'm creating custom task for gradle. I don't know how I can create task which will use my custom task class. Is it possible? I want to create this task for functional tests which will be runned on jenkins.
This is my custom task:
package pl.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
class MyCustomTask extends DefaultTask {
public MyCustomTask() {
// do something
}
#TaskAction
def build() {
ant.echo(message: "only for tests")
}
}
And this is my test class:
package pl.gradle
import static org.junit.Assert.*
import org.gradle.testfixtures.ProjectBuilder
import org.gradle.api.Project
import org.junit.Before;
import org.junit.Test
class MyCustomTaskTest {
private Project project;
def task
#Before
public void setUp() {
project = ProjectBuilder.builder().build()
task = project.task("build", type: MyCustomTask)
}
#Test
public void taskCreatedProperly() {
assertTrue(task instanceof MyCustomTask)
}
#Test
public void shouldRunTask() {
// task.execute() // how to run this task? I want to run build() method from MyCustomTask class which is #TaskAction
}
}
ProjectBuilder is meant for lower-level tests that don't execute tasks. Its sweet spot is testing plugins. In addition you'd write higher-level tests that execute real builds (and therefore also tasks). You'd typically use the Gradle tooling API to kick off these builds. Check out the tooling API samples in the full Gradle distribution.
Call Action.execute yourself for each of the task actions:
project.tasks.getByName("myTask").with { Task task ->
assertEquals task.group, 'My Group'
task.actions.each { Action action ->
action.execute task
}
}
I've previously mentioned this here: https://stackoverflow.com/a/63613564/410939

Resources