I am having problem running testrunner with cucumber. I need someone to help me check the #CucumberOptions. Thank you
package stepDefinition;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith (Cucumber.class)
#CucumberOptions (features = "Feature"
,glue={"stepDefinition"})
public class testRunner {
}
#RunWith(Cucumber.class) is for JUnit integration.
If you want to use Cucumber with TestNG, you have to extends your class with AbstractTestNGCucumberTests.
You should have a look on https://github.com/lionhearth/cucumber-testng which is a perfect sample.
Here is my Test. I have both step definitions/featurefiles in src as packages. Also, i downloaded the cucumber plugin yet i can't see the colors showing in my features. How do reference feature and step definitions #cucumberoptions.
package stepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class aptitudeTest {
#Given ("^I have successfully ([^\"]*)$")
public void I_have_(String str)
{
if (str.equals("registered"))
{
System.out.println("registered Automation");
}
if (str.equals("unregistered"))
{
System.out.println("unregistered");
}
}
#When ("^I enter my valid ([^\"]*)$")
public void I_enter_(String str)
{
if (str.equals("credentials"))
{
System.out.println("credentials Automation");
}
if (str.equals("details"))
{
System.out.println("details");
}
}
#Then ("^I should see the welcome([^\"]*)him $")
public void I_should_(String str)
{
if (str.equals("message"))
{
System.out.println("message Automation");
}
if (str.equals("information"))
{
System.out.println("infomation");
}
}
}
Here is my feature
Feature: Login to account
#tester
Scenario:I should see a message when i successfully logged in
Given I have successfully registered
When I enter my valid credentials
Then I should see the welcome message
Given I have successfully unregistered
When I enter my valid detail
Then I should see the welcome message
Related
I use Cucumber/Playwright in my project and want to use Allure Reporting Tool for my tests.
This is how my step-definition looks like:
import { ICustomWorld } from '../support/custom-world';
import { config } from '../support/config';
import { Given, When, Then } from '#cucumber/cucumber';
import { expect } from '#playwright/test';
import { allure } from 'allure-playwright';
Given('Go to the playwright website', async function (this: ICustomWorld) {
const page = this.page!;
allure.description('test');
await page.goto(config.BASE_URL);
await page.locator('nav >> a >> text="Playwright"').waitFor();
});
I imported allure and wanted to add allure.description
But while test running, i received a message:
Error: test.info() can only be called while test is running
What it could be? I really appreciate each answer
Thank you
I'm trying to write a unit test case for the below function in the service class
#Service
public class currencyHandler {
public boolean isNoDecimal(String currency) {
return "JPY".equalsIgnoreCase(currency) || "KRW".equalsIgnoreCase(currency);
}
}
Below is the unit case:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.svc.it.handlers;
#ExtendWith(SpringExtension.class)
public class CurrencyTests {
#Mock
CurrencyHandler currencyHandlerTest;
#Test
public void isNoCurrency() throws Exception {
assertTrue(currencyHandlerTest.isNoCurrency("ABC"));
assertTrue(currencyHandlerTest.isNoCurrency("XYZ"));
assertFalse(currencyHandlerTest.isNoCurrency("BOGUS"));
assertFalse(currencyHandlerTest.isNoCurrency(""));
assertFalse(currencyHandlerTest.isNoCurrency(null));
}
}
Below is the error when I run above unit test case:
org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:40)
at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:35)
at org.junit.jupiter.api.Assertions.assertTrue(Assertions.java:162)
I guess I'm doing something wrong with #Mock object.
Appreciate your help. Thanks in advance!
To write a unit test for the CurrencyHandler class, you must test against an instance of that class. You must not test against an instance of a mock of that class.
The following shows how to write such a unit test.
package example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CurrencyHandlerTests {
private CurrencyHandler currencyHandler = new CurrencyHandler();
#Test
void isNoDecimal() {
assertTrue(currencyHandler.isNoDecimal("JPY"));
assertTrue(currencyHandler.isNoDecimal("KRW"));
assertFalse(currencyHandler.isNoDecimal("BOGUS"));
assertFalse(currencyHandler.isNoDecimal(""));
assertFalse(currencyHandler.isNoDecimal(null));
}
}
To better understand the concepts here, I recommend that you read some articles or books on unit testing, mocks, and the SUT (subject under test).
In addition, you do not need to register the SpringExtension if you are writing a pure unit test like the one above, since a pure unit test does not need to interact with components in a Spring ApplicationContext.
Below is the Test Runner File
package runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="D:/InstalledSoftwares/Eclipse_Photon/workspace/March26/src/test/resources/features/login.Feature",
glue= {"D:/InstalledSoftwares/Eclipse_Photon/workspace/March26/src/test/java/stepDefinitions/LoginSteps.java"})
public class TestRunner {
}
Below is the Feature File-
Feature: Create Account on Facebook
Scenario: Check First Name
Given: User is already on Login Page
When: Enter First Name
And: Enter Last Name
Then: Check if value of First Name is there
Below is the Step Definition-
package stepDefinitions;
import cucumber.api.java.en.Given;
public class LoginSteps {
#Given("^User is already on Login Page$")
public void User_is_already_on_Login_Page()
{
}
}
Below is the Snapshot of Eclipse.
This is how my Project structures look like
I am trying to add JUnit tests to a Tomee web-application that uses CDI and JPA. Leaving out the different hurdles of the last two weeks (including very intensive research on stackoverflow as well as other sources), my problem appears to be quite concrete:
Running the unit test gives this error message:
org.apache.openejb.Injector$NoInjectionMetaDataException:
org.demo.service.GenericServiceTest : Annotate the class with #javax.annotation.ManagedBean so it can be discovered in the application scanning process
at org.apache.openejb.Injector.inject(Injector.java:54)
at org.apache.openejb.OpenEjbContainer$GlobalContext.bind(OpenEjbContainer.java:656)
...
This I don't understand, for I have annotated the class just as required. Any idea what I can do to resolve this?
(Or does the error refer to the injected class - GenericService? I cannot annotate this #ManagedBean, for it is already #Stateless).
Here are some details of my project:
gradle dependencies:
dependencies {
compile 'org.apache.commons:commons-lang3:3.3.2'
compile "com.googlecode.json-simple:json-simple:1.1.1"
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.8.6'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.6'
compile 'log4j:log4j:1.2.16'
testCompile "org.apache.openejb:tomee-embedded:1.7.3"
compile "javax:javaee-api:7.0"
compile 'mysql:mysql-connector-java:5.1.16'
}
(I have put the testCompile inbetween, because there is a ticket stating the importance of the order: EJB testing with TomEE embedded EJBContainer api: java.lang.ClassFormatError exception)
My Test class is this:
package org.demo.service;
import java.io.File;
import java.util.Properties;
import javax.annotation.ManagedBean;
import javax.ejb.embeddable.EJBContainer;
import javax.inject.Inject;
import javax.naming.NamingException;
import org.apache.openejb.OpenEjbContainer;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
#ManagedBean
public class GenericServiceTest {
private static EJBContainer ejbContainer;
#Inject
private GenericService service;
#Test
public void test() throws NamingException {
System.out.println("service: " + service);
}
#BeforeClass
public static void start() {
Properties p = new Properties();
try {
p.put(EJBContainer.MODULES, new File("bin"));
} catch (Exception e1) {
e1.printStackTrace();
}
p.put(OpenEjbContainer.Provider.OPENEJB_ADDITIONNAL_CALLERS_KEY, GenericService.class.getName());
ejbContainer = javax.ejb.embeddable.EJBContainer.createEJBContainer(p);
}
#Before
public void inject() throws NamingException {
ejbContainer.getContext().bind("inject", this);
}
#AfterClass
public static void shutdownContainer() {
if (ejbContainer != null) {
ejbContainer.close();
}
}
}
Maybe I'm running totally in the wrong direction here - Please let me know if I should choose a different approach - All I want is to add unit tests to my web application (preferably without introducing Weld/JBoss or other implementations as alternatives to the implementations I already use in the application itself).
Thank you very much in advance!
I would recommand you to read http://tomee.apache.org/developer/testing/index.html , there are some examples
Regarding your test it uses openejb embedded and not tomee embedded and deploys bin/ as an application. the hack bind("inject") only works with classpath deployment (no module).
I'm developing an application with RESTEasy and JBOSS 5.1.
For specific situations, I have to return 404 error (not found).
In the sources, I'm using
import org.jboss.resteasy.spi.NotFoundException;
throw new NotFoundException(...);
The problem is that, in the header response, I have
Status Code: 500 internal server error
even if in the body the exception is:
org.jboss.resteasy.spi.UnhandledException: org.jboss.resteasy.spi.NotFoundException
This is a normal behavior? It's not possible to return Status Code: 404?
I encounter some problem. I found the root cause. The built-in exception handle is only occur in resteasy newest version build 2.3.1 GA. If you upgrade to this version.You can get the expected result.
It does seem a bit strange that RestEASY does not handle the NotFoundException out of the box. It should, according to the docs:
Resteasy has a set of built-in exceptions that are thrown by it when it encounters errors during dispatching or marshalling.
Anyways, you can work around it by adding an ExceptionMapper:
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.spi.NotFoundException;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ExceptionTest {
#Path("/")
public static class Service {
#GET
public String notFound() throws NotFoundException {
throw new NotFoundException("");
}
}
public static class FailureExceptionMapper implements ExceptionMapper<NotFoundException> {
#Override
public Response toResponse(NotFoundException exception) {
return Response.status(exception.getErrorCode()).build();
}
}
#Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().addExceptionMapper(new FailureExceptionMapper());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(404, response.getStatus());
}
}
I believe that instead of throwing an exception you should use:
import javax.ws.rs.core.Response;
return Response.status(404).build();
in your rest method when you need to return a not found.
regards.
Maybe a custom javax.servlet.Filter can help.