I am working on Behaviour Driven Development test - BDD test, for that i am using Cucumber with Gherkin.
In my test function i need to declare a matrix, so in the Given step i declared a table and in the function test i need to give it as a DATATABLE.
To transfer the dataTable elements to int and work with it as a matrix, i used a MAP, but the problem is when i use : List<Map<String,String>> rows = table.asMaps(String.class, String.class);
intellij makes asMaps in red and it shows the problem is : Cannot resolve method 'asMaps' in 'DataTable'
I didn't find a solution for that in google i will attach the code:
package EXO1.com;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import gherkin.ast.DataTable;
import java.util.List;
import java.util.Map;
public class DetStep {
#Given("I have a matrix")
public void iHaveAMatrix(DataTable table) {
List<Map<String,String>> rows = table.asMaps(String.class, String.class);
}
#When("I call function determinant\\(Matrix matrix)")
public void iCallFunctionDeterminantMatrixMatrix() {
}
#Then("I expect the result {int}")
public void iExpectTheResult(int arg0) {
}
}
For the feature class is :
Feature: Calcul Determinant
Scenario: determinant d'une matrice
Given I have a matrix
|col1|col2|col3|
|1|2|0|
|3|1|1|
|2|0|1|
When I call function determinant(Matrix matrix)
Then I expect the result -3
Related
Maybe what I am trying to do is not worthwhile, it sure feels that way after spending many days on it.
I have A Base Class shown here:
package jimmy.kilmer.com;
import java.awt.Color;
import jarPackageImports.AI;
import jarPackageImports.MovementAction;
import jarPackageImports.Info;
import jarPackageImports.PlayerAction;
public class GameAI extends AI {
public gameAI(Info info) {
super(info);
setJerseyNumber(32);
}
public Color getColor() {
return Color.RED;
}
public String getName() {
return "Usain Bolt";
}
public PlayerAction update() {
// TODO game movement actions
// all available methods not listed here...
info.getVelocity();
info.getX();
info.getY();
MovementAction steeringBehavior = null;
return steeringBehavior;
}
//basically used for testing setup
public int[][] populateAllPossibleNodes() {
int[][] allPossibleNodes = new int[screenWidth/20][screenHeight/20];
return allPossibleNodes;
}
}
I have been given a jar, that sets up the game environment. It uses reflection for the setup. I am not familiar with reflection, unfortunately, as I am more beginner level.
I have read a lot about TDD, and am convinced that can help me stay orderly, and code in a disciplined way. I have some say that TDD is not really useful for Game development, which the arguments may be true, in regard to making an "enjoyable game." But, from a purely coding standpoint, I remain steadfast in my believe that TDD is the way to go. But, that remains to be seen, since it is still theoretical. I would like to try it.
I have installed Junit 5, and have done many tutorials, but it's all pretty basic examples. My particular test case uses reflection, super classes, derived classes, dynamic data. My head is spinning.
My goal is just to get setup such that I can start doing some Test driven development.
Here is my Junit test class:
package jimmy.kilmer.com;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import jarPackageImports.Info;
class GameAITest {
private GameAITest AIObject;
private jarPackageImports.Info info;
#BeforeEach
void setUp() throws Exception {
AIObject = new GameAITest(info);
#AfterEach
void tearDown() throws Exception {
}
#Test
void testPopulateAllPossibleNodes() {
// 1. given/arrange
int[][] array1 = new int[80][65];
// 2. when/act
int[][] array2 = AIObject.populateAllPossibleNodes();
// 3. then/assert
assertArrayEquals(array1, array2);
}
}
That is my best stab so far, but it still get a compile error. Specifically:
java.lang.NullPointerException:Cannot invoke "jarPackageImports.Info.getScene()" because "this.info" is null
In summation:
maybe everything I am trying is rubbish?
Do I need to use dynamic junit testing? I would have to read up on that.
Do I need to mock (use Mockito?) to instantiate an object to test? I would need to read up on that as well.
Is it possible to instantiate an object from GameAI? Do I need to/how would I use relection to do that? class.getConstructors()? And, I would have to read up on that.
thanks in advance.
I want to build a custom renderer for some of my grids columns to hide the text if the user doesn't have the right to read it. It's still important that the data is accessible even if the user is not able to read it.
So I wrote a custom renderer which looks like this:
package <package>.util.renderer;
import com.vaadin.client.renderers.Renderer;
import com.vaadin.client.widget.grid.RendererCellReference;
import <package>.util.CustomSecurityConstants;
import <package>.BaseUI;
public class BlockedStringRendererClient implements Renderer<String> {
private boolean canReadBlocked = BaseUI.getCurrentPrincipal().get().getAuthorities().contains(CustomSecurityConstants.READ_PERMISSION_BLOCKED);
#Override
public void render(RendererCellReference rendererCellReference, String s) {
if (canReadBlocked) {
rendererCellReference.getElement().setInnerText(s);
} else {
rendererCellReference.getElement().setInnerText("");
}
}
}
Then I wrote the server side of the renderer, following this tutorial https://vaadin.com/docs/-/part/framework/clientsidewidgets/clientsidewidgets-grid.html
package <package>.util.renderer;
import com.vaadin.ui.Grid;
public class BlockedStringRendererServer extends Grid.AbstractRenderer<String> {
public BlockedStringRendererServer() {
super(String.class);
}
}
And finally the connector to connect these components:
package <package>.util.renderer;
import com.vaadin.client.connectors.AbstractRendererConnector;
import com.vaadin.shared.ui.Connect;
#Connect(BlockedStringRendererServer.class)
public class BlockedStringRendererConnector extends AbstractRendererConnector<String> {
#Override
public BlockedStringRendererClient getRenderer() {
return (BlockedStringRendererClient) super.getRenderer();
}
}
But now when I try to use the connector like follows:
grunddatenGrid.getColumn("name").setRenderer(new BlockedStringRendererServer());
The grid doesn't show any columns that contains strings anymore.
I really don't know what I'm doing wrong but I think it might has to do with the Connector-Annotation not working as expected because when I try to debug the client side logic it doesn't even get called.
Can somebody point me to what steps I'm missing?
Kind regards,
Fabian
Currently I'm using ExtentReport to generate automation reports.
The way I'm using ExtentReport is using the IReporter implementation to generate the report at the end of my tests, which is great.
However, now I'm looking at creating a way of monitoring my tests while they are being executed which is not possible with IReporter.
I want to create a separate listener for real time results using ITestListener.
Has anyone used this with ExtentReport? Or anything similar?
Any useful articals or guidelines in the right direction would be appreciated.
Thanks.
EDIT: Basically need a way to generate the ITestListener live console outputs to an actually HTML Reprot where I can view the test progress from there rather than the console
It should look something like:
import com.relevantcodes.extentreports.*;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.internal.IResultListener;
import java.util.Arrays;
import java.util.Locale;
/**
* Created by andrey.smirnov on 14.06.2016.
*/
public class ExtentListener implements IResultListener {
private ExtentReports reporter = new ExtentReports("build/SimpleReport.html", true, DisplayOrder.NEWEST_FIRST, NetworkMode.OFFLINE, Locale.ENGLISH);
private ExtentTest testReporter;
#Override
public void onTestStart(ITestResult result) {
testReporter = reporter.startTest(result.getMethod().getMethodName(), "Some description");
testReporter.log(LogStatus.INFO, "Starting test " + result.getMethod().getMethodName());
}
#Override
public void onTestSuccess(ITestResult result) {
testReporter.log(LogStatus.PASS, "Test PASSED");
reporter.endTest(testReporter);
reporter.flush();
}
#Override
public void onFinish(ITestContext context) {
reporter.close();
}
// Other interface methods
}
It will provide report updating on each test finish. Please refer to documentation about tests parallel running. Also it would be better to pass ExtentReports instance as TestNG context attribute e.g. iTestContext.setAttribute("reporter", reporter) and use it in listener.
// I want to use my own custom elements instead of selenium defined web elements //like webElement and WebDriver etc. So,I have created following custom wrapper classes :-
//custom webdriver wrapper
package org.rsf.wrapper.driver;
import org.openqa.selenium.WebDriver;
public interface RsfWebDriver extends WebDriver{
}
//custom webelement wrapper
package org.rsf.wrapper.element;
import org.openqa.selenium.WebElement;
public interface RsfElement extends WebElement{
}
// Now, I am calling my wrapper classes in below pageObject code .But it gives error.Pls //help me:-
package org.rsf.pages;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
import org.rsf.bean.EnterQuoteBean;
import org.rsf.utilities.Utility;
import org.rsf.wrapper.driver.RsfWebDriver;
import org.rsf.wrapper.element.RsfElement;
import org.testng.Assert;
//pageObject
public class EnterQuotePage extends PageBase {
public EnterQuotePage(RsfWebDriver driver) {
super(driver);
super.driver=driver;
}
//creating my custom wrapper object
private RsfElement element;
private static Logger log=Logger.getLogger(EnterQuotePage.class);
Utility utilities = new Utility();
EnterQuoteBean eqb= new EnterQuoteBean();
public void open(String url) {
System.out.println("Inside get url");
System.out.println("url is : " +url);
System.out.println(" PB : Driver value :-" + driver);
Assert.assertNotNull(this.driver);
this.driver.get(url);
System.out.println("After get url");
}
public void clickHit()
{
super.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//ERROR OCCURS IN BELOW TWO LINES [in element]
element=super.driver.findElement(By.id("hit"));
element.click();
}
public String getQuoteID(){
String quoteText =findMessage.getText();
String quoteText1[] = quoteText.split("\\=");
quoteText1[1]=quoteText1[1].trim();
System.out.println("Generated Quote Id :- " + quoteText1[1]);
return quoteText1[1];
}
public void checkSuccessMessage(){
String successMessage = findMessage.getText();
Assert.assertEquals(element.getText().contains(successMessage), eqb.getSuccessMessage());
}
}
To solve this problem do as below
Create a XML file with elements and add an XML parse class, you can find code online easily for XML parser. e.g.
<Element name="ElementSource">
<Sample>
<ElementTagName by="Xpth,id etc..">LocaterValue</ElementTagName>
<txtUserName by="id">username</txtUserName>
</Sample>
Create a class which have static web page elements Same as in the XML file e.g.
public static final String txtUserName = "txtUserName";
You can have page wise classes or a single class. Also, you can directly mention your elements in this class without XML file.
Create a class that contains modules to read this XML file or Element Class to get Element Locater and its locate by like xpath,id etc.. you can store them into Variables.
Finally, Create a class Named ElementLocater having function to locate elements as per its locate by using Switch case.
e.g.
public WebElement locateElement(WebDriver driver, String Locater,
String LocateBy) {
try {
switch (LocateBy.toLowerCase()) {
case "xpath":
return driver.findElement(By.xpath(Locater));
case "id":
return driver.findElement(By.id(Locater));
....
//So on
default:
return null;
}
}
catch (Exception e)
{
//Write to log or custom error message
}
return null;
}
You can create more functions in this class like isElementPreset etc...
By doing this you don't have to go into source code or in Tests every time any element HTML chages or Code update need to be done. Change any one function or variable will do :)
You need to catch a NoSuchElementException:
try
{
element=super.driver.findElement(By.id("hit"));
element.click();
}
catch (NoSuchElementException e)
{
// Do whatever you were planning to do if the element was not found
// (you can try again for example)
}
Alternatively, you can do the following (will "save" you the exception handling):
List<WebElement> elements = super.driver.findElements(By.id("hit"));
if (elements.size() > 0)
elements.get(0).click();
I want to verify that a collection contains at least one non-null element. I have tried is(not(empty())), however this passes in the test below.
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
public class SandBoxTest {
#Test
public void shouldTestThis() {
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(null);
assertThat(collection, is(not(empty())));
}
}
Is there an elegant/simple way to do this?
Things That Don't Work
#Test
public void should(){
Collection<String> collection = new ArrayList();
collection.add("gfas");
collection.add("asda");
assertThat(collection, contains(notNullValue()));
}
java.lang.AssertionError:
Expected: iterable containing [not null]
but: Not matched: "asda"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
...
assertThat(collection, hasItem(notNullValue(Integer.class)));
Unfortunately, there is a bug in Java 1.6 that means you might have to split it onto 2 lines as described here if you are using 1.6:
Matcher<Iterable<? super String>> matcher = hasItem(notNullValue(Integer.class));
assertThat(collection, matcher);
EDIT Here is the FEST Assert example you asked for:
import static org.fest.assertions.api.Assertions.assertThat;
...
assertThat(collection).doesNotContainNull();
FEST requires only a single static import so you get full IDE auto completion.
I just ran into the same problem and solved it as follows.
The basic idea is that if the collection has only null elements, converted to a set it will contain just one element and it will be null. If not so, then the collection contains at least one non-null element.
I wrote a matcher, and tried it with this test:
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static personal.CollectionOfNullsMatcher.collectionOfNulls;
public class SimpleTest {
#Test
public void should_check_collection_for_non_null_values() {
Collection<String> testedCollection = new ArrayList<String>();
testedCollection.add(null);
assertThat(testedCollection, is(collectionOfNulls()));
testedCollection.add("any");
assertThat(testedCollection, is(not(collectionOfNulls())));
}
}
class CollectionOfNullsMatcher extends TypeSafeMatcher<Collection> {
#Override
protected boolean matchesSafely(final Collection collection) {
Set<Object> set = new HashSet<Object>(collection);
return (set.size() == 1) && (set.toArray()[0] == null);
}
#Override
public void describeTo(final Description description) {
description.appendText("collection of nulls");
}
#Factory
public static <T> Matcher<Collection> collectionOfNulls() {
return new CollectionOfNullsMatcher();
}
}
Of course, in a real project, the matcher should be placed together with its brothers :)
Hope it helps.
You can try the following:
public void shouldTestThis() {
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(null);
collection.removeAll(Collections.singleton(null)); // remove all "null" elements from collection
assertThat(collection, is(not(empty())));
}
As ajb notices, if you want to left your array unmodified, you should use an iterator and check each element until the end of the collection or a non null one.
You're on the right track, chaining Matcher instances. You just need the hasItem matcher (like I've suggested here) instead of contains.
Creates a matcher for Iterables that only matches when a single pass
over the examined Iterable yields at least one item that is matched by
the specified itemMatcher. Whilst matching, the traversal of the
examined Iterable will stop as soon as a matching item is found.
For example,
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(null);
assertThat(collection, hasItem(is(not(nullValue()))));
will fail with
java.lang.AssertionError:
Expected: a collection containing is not null
but: was null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
at com.example.ExampleTest.should(ExampleTest.java:21)
at [...]
whereas
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(null);
collection.add("hey");
collection.add(null);
assertThat(collection, hasItem(is(not(nullValue()))));
// or shortened
assertThat(collection, hasItem(notNullValue()));
will succeed.