I am creating a Spring Framework to automate the Google Calculator
I have a feature file that has some values as defined below
Feature: Google Calculator
Calculator should calculate correct calculations
Scenario Outline: Add numbers
Given I am on google calculator page
When I add number "<number1>" to number "<number2>"
Then I should get an answer of "<answer>"
Examples:
| number1 | number2 | answer |
| 1 | 2 | 3 |
| 4 | 5 | 9 |
I am trying to use the Given, When , Then to create a test that any number from this feature file could be used in the Calculator
My Steps are as follows:
#Scope("test")
#ContextConfiguration("classpath:spring-context/test-context.xml")
public class GivenSteps {
#Autowired
private WebDriver webDriver;
#Given("^I am on google calculator page$")
public void iAmOnGoogleCalculatorPage() throws Throwable {
webDriver.get("https://www.google.ie/search?q=calculator");
}
#When("^I add number \"([^\"]*)\" to number \"([^\"]*)\"$")
public void i_add_number_to_number(Integer number1, Integer number2) throws Throwable {
WebElement googleTextBox = webDriver.findElement(By.id("cwtltblr"));
googleTextBox.sendKeys(Keys.ENTER);
throw new PendingException();
}
#Then("^I should get the correct answer again$")
public void thecorrectanswertest2() throws Throwable{
WebElement calculatorTextBox = webDriver.findElement(By.id("cwtltblr"));
String result = calculatorTextBox.getText();
}}
My question is how do I code the piece where an number can be choosen and an answer verified from the table in the feature ?
Did you try to use the #Then like as below to compare the answer from table?-
#Then("^I should get the correct answer \"([^\"]*)\" again$")
public void thecorrectanswertest2(String answer) throws Throwable{
WebElement calculatorTextBox = webDriver.findElement(By.id("cwtltblr"));
String result = calculatorTextBox.getText();
if(answer.equalsIgnoreCase(result))
System.out.println("Test Passed");
}
Try this once. It should work
Related
I am using Smallrye Mutiniy reactive library in my Quarks application as it is supported natively in Quarks applications.
I'am trying to write unit tests for a service class. I am not sure how to write unit tests for a method that returns Uni/Multi.
A method returning Uni<String>
public Uni<String> hello(final String name) {
final String message = "Hello " + name;
return Uni.createFrom().item(message);
}
Unit implemented for the above method
#Test
void testHello() {
final Uni<String> casePass = hello("Ram");
// assertion passes and all good with this.
casePass.subscribe().with(message -> Assertions.assertEquals("Hello Ram", message));
final Uni<String> caseFail = hello("Ravan");
// It is expected to fail the assertion, and it does. But the test is not failing, instead aseertion fail message simply logged to the console.
caseFail.subscribe().with(message -> Assertions.assertEquals("Hello Sita", message));
}
Console logs
[-- Mutiny had to drop the following exception --]
Exception received by: io.smallrye.mutiny.helpers.UniCallbackSubscriber.onItem(UniCallbackSubscriber.java:71)
org.opentest4j.AssertionFailedError: expected: <Hello Sita> but was: <Hello Ram>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
...
There are several approaches. You can use the utility methods provided in smallrye.io/smallrye-mutiny/guides/testing. However, if, according to your comment, you need more, I would recommend the following approach:
final Uni<Greeting> casePass = hello("Ram");
Greeting g = casePAss.await().atMost(Duration.ofSeconds(5)); // To be sure we don't stay tucked
// Assertions come here
So basically, you block until the item is sent. Avoid await().indefinitely() because it may block your test if the Uni never send an item. Not that await()... throws an exception if the Uni sends a failure.
I would really recommend using the way of testing from SmallRey.
https://smallrye.io/smallrye-mutiny/1.7.0/guides/testing/
You still can get the object out of the multi/uni
use invoke, for example.
public static Uni<String> hello(final String name) {
final String message = "Hello " + name;
return Uni.createFrom().item(message);
}
#Test
public void testUnit() {
UniAssertSubscriber<String> tester = hello("someone")
.invoke( i -> Assertions.assertEquals("Hello someone", i))
.invoke(i -> Assertions.assertNotNull(i))
.subscribe().withSubscriber(UniAssertSubscriber.create());
tester.assertCompleted();
}
#Test
public void secondUnit() {
UniAssertSubscriber<String> tester = hello("none")
.invoke( i -> Assertions.assertEquals("Hello someone", i))
.invoke(i -> Assertions.assertNotNull(i))
.subscribe().withSubscriber(UniAssertSubscriber.create());
tester.assertCompleted();
}
I hope you can use it like that
This function is used to query the database to search for a specific category. The testcase which i wrote for this function covers the entire code by when I see the code coverage using eclipse ecelma it shows red for a specific line. Can someone help me to rectify this?
#Override
public List<Services> searchCategory(String name) throws CategoryNameNotFoundException{
logger.info("{}.{}",new ServicesBoImpl().getClass().getPackageName(), new ServicesBoImpl().getClass().getName());
logger.info("Function: searchCategory(), Information: querying the database for the search categories");
List<Services> searchCategory = jdbcTemplate.query(env.getProperty("searchCategory"), new PreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, name+"%");
}
} ,new SearchCategoryRowMapper());
if(searchCategory.size()==0) {
logger.info("Function: searchCategory(), Information: Throwing CategoryNameNotFoundException because the paticular category is not found");
throw new CategoryNameNotFoundException("Category Not Found");
}
return searchCategory;
}
What logic are you trying to cover by writing this UT ? No logic is executed inside test...
Assuming that serviceBoImpl is mock:
#Test(expected = CategoryNameNotFoundException.class)
public void testIfSearchCategoryThrowsException() {
Mockito.doThrow(CategoryNameNotFoundException).when(serviceBoImpl).searchCategory("a!#")
...here execution which calls this method...
}
Remember that this test will not cover logic of searchCategory method as it is throwing an error once it is executed
I am trying to write a few SONARQUBE custom rules for my project.
After reading up the below document -
https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101
and
https://github.com/SonarSource/sonar-custom-rules-examples,
I created a custom rule like these classes below -
The Rule file:
#Rule(key = "MyAssertionRule")
public class FirstSonarCustomRule extends BaseTreeVisitor implements JavaFileScanner {
private static final String DEFAULT_VALUE = "Inject";
private JavaFileScannerContext context;
/**
* Name of the annotation to avoid. Value can be set by users in Quality
* profiles. The key
*/
#RuleProperty(defaultValue = DEFAULT_VALUE, description = "Name of the annotation to avoid, without the prefix #, for instance 'Override'")
protected String name;
#Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
System.out.println(PrinterVisitor.print(context.getTree()));
scan(context.getTree());
}
#Override
public void visitMethod(MethodTree tree) {
List<StatementTree> statements = tree.block().body();
for (StatementTree statement : statements) {
System.out.println("KIND IS " + statement.kind());
if (statement.is(Kind.EXPRESSION_STATEMENT)) {
if (statement.firstToken().text().equals("Assert")) {
System.out.println("ERROR");
}
}
}
}
}
The Test class:
public class FirstSonarCustomRuleTest {
#Test
public void verify() {
FirstSonarCustomRule f = new FirstSonarCustomRule();
f.name = "ASSERTION";
JavaCheckVerifier.verify("src/test/files/FirstSonarCustom.java", f);
}
}
And finally - the Test file:
class FirstSonarCustom {
int aField;
public void methodToUseTestNgAssertions() {
Assert.assertTrue(true);
}
}
The above Test file would later be my Project's source code.
As per the SONAR documentation - the // Noncompliant is a mandatory comment in my Test file. Thus my first question is should I add this comment everywhere in my Source code too?
If yes - is there any way I can avoid adding this comment, because I do not want to add that code refactoring exercise all over.
Can someone suggest me what I need to do here?
I am using SONARQUBE 6.3.
This comment is only used by the test framework (JavaCheckVerifier class) to test the implementation of your rule. It is not mandatory in any way and for sure you don't need it in your real code.
In jFugue 4.0 there's a nice function:
Transforming Patterns with PatternTransformer
but all pattern transformers are removed in jFugue 5.0. I understand it must be replaced with something cool. but what to do in jFugue 5.0 please? i get no clue. I googled but have so far had no outcome.
The class "PatternTransformer" has gone, but transforming patterns has never been easier!
In older versions of JFugue, there was actually very little difference between a PatternTransformer and a ParserListener. Older versions of JFugue also referred to a PatternTool, which was like a Transformer but instead of transforming a pattern, it would just measure it; for example, you could write a tool to tell you what instruments were used in a piece.
To transform a Pattern in JFugue, just create a class that implements ParserListener (or extends ParserListenerAdapter), and add it as a listener to a parser - such as a StaccatoParser:
For example, here's a tool that finds what instruments are used in a piece:
public class InstrumentTool extends ParserListenerAdapter
{
private List<String> instrumentNames;
public InstrumentTool() {
super();
instrumentNames = new ArrayList<String>();
}
#Override
public void onInstrumentParsed(byte instrument) {
String instrumentName = MidiDictionary.INSTRUMENT_BYTE_TO_STRING.get(instrument);
if (!instrumentNames.contains(instrumentName)) {
instrumentNames.add(instrumentName);
}
}
public List<String> getInstrumentNames() {
return this.instrumentNames;
}
}
and here's how to use it:
MidiParser midiParser = new MidiParser();
InstrumentTool instrumentTool = new InstrumentTool();
midiParser.addParserListener(instrumentTool);
midiParser.parse(MidiSystem.getSequence(new File("filename")));
List<String> instrumentNames = instrumentTool.getInstrumentNames();
for (String name : instrumentNames) {
System.out.println(name);
}
There's a new class in JFugue 5 that lets you chain ParserListeners together. This would let you create a chain of listeners that each modify a pattern before sending events to the next listener in the chain. For example, suppose you have a pattern, and you want to transform all of the instruments (say, change GUITAR to PIANO); then you want to take any note played with PIANO and stretch its duration by two; then you want to take any note with a new duration greater than 2.0 (two whole notes) and you want to change its octave. A bit of a crazy example, but it shows the need for a "chaining" series of parser listeners.
Here's a demo example that uses chaining. This class reads a MIDI pattern; it then changes all of the instruments, and then it creates a Staccato pattern from the original MIDI.
public class ChainingParserListenerDemo {
public static void main(String[] args) throws InvalidMidiDataException, IOException {
MidiParser parser = new MidiParser();
InstrumentChangingParserListener instrumentChanger = new InstrumentChangingParserListener();
StaccatoParserListener staccatoListener = new StaccatoParserListener();
instrumentChanger.addParserListener(staccatoListener);
parser.addParserListener(instrumentChanger);
parser.parse(MidiSystem.getSequence(new File("filename")));
System.out.println("Changed "+instrumentChanger.counter+" Piano's to Guitar! "+ staccatoListener.getPattern().toString());
}
}
class InstrumentChangingParserListener extends ChainingParserListenerAdapter {
int counter = 0;
#Override
public void onInstrumentParsed(byte instrument) {
if (instrument == MidiDictionary.INSTRUMENT_STRING_TO_BYTE.get("PIANO")) {
instrument = MidiDictionary.INSTRUMENT_STRING_TO_BYTE.get("GUITAR");
counter++;
}
super.onInstrumentParsed(instrument);
}
}
Goal : testing TDD in a typical enterprise Java environment.
Context :
Frameworks used (even if it's overkill, I practice project based learning) :
DAO : Hibernate
Spring IoC
Front : Spring MVC + Twitter Boostrap (if possible)
TDD : JUnit
DB : PostgreSQL
My project is a simple billing system which would help freelancers create, edit and print/send bills to customers.
Once my project is created and configured, I don't know where to start.
Let's say my first my first feature is to create a bill with a unique number and a title.
Question : What should I test first ?
the Domain layer with a createBill(String title) method which would generate a unique Serial Number ? I'd mock the DB layer.
the UI first, mocking the service layer ? I don't know how to do it.
Thanks in advance for your answers,
Cheers
Start with a test :-)
What does your system do?
public class BillingSystemTest {
#Test
public void generatesBills() {
Bill bill = new BillingSystem().generate()
assertNotNull(bill)
}
}
First test complete!
Make it pass, move on to the next test...
#Test
public void generatesAnInvoiceNumberForEachBill() {
Bill bill = new BillingSystem().generate()
assertEquals(1, bill.getNumber())
}
// ...and the next
#Test
public void generatesUniqueInvoiceNumbersForEachBill() {
BillingSystem bs = new BillingSystem()
assertEquals(1, bs.generate().getNumber())
assertEquals(2, bs.generate().getNumber())
}
#Test
public void generatesAnInvoiceSubjectWhenNoneIsSpecified() {
Bill bill = new BillingSystem().generate()
assertEquals("Invoice #1 from ACME Corp.", bill.getSubject())
}
#Test
public void allowsForCustomSubjectsOnBills() {
Bill bill = new BillingSystem().generate("Custom subject")
assertEquals("Custom subject", bill.getSubject())
}
I've obviously skipped the refactoring steps here, but now that you have the tests, and the code that goes with it, you need to evaluate it for more opportunity. I'm imagining the code looking something like this.
public class BillingSystem {
private nextInvoiceNumber = 1;
public Bill generate() {
return generate("Invoice #" + nextInvoiceNumber + " from ACME Corp.");
}
public Bill generate(String subject) {
Bill bill = new Bill(nextInvoiceNumber, subject)
nextInvoiceNumber++
return bill;
}
}
Looking at this code, it seems ok, but may violate the Single Responsibility Principle (SRP). Here the BillingSystem generating a bill as well as managing the invoice number. This is an opportunity for refactoring. After the refactoring, your design may look something like this:
public class BillingSystem {
private InvoiceNumbering invoiceNumbering = new InvoiceNumbering()
public Bill generate() {
return generate("Invoice #" + invoiceNumbering.peekNext() + " from ACME Corp.");
}
public Bill generate(String subject) {
Bill bill = new Bill(invoiceNumbering.generateNext(), subject)
nextInvoiceNumber++
return bill;
}
}
Your design is better and your tests all pass. Next thing to do is refactor out the tests to remove the implementation details from them. They may end up looking something like:
#Test
public void generatesBills() {
Bill bill = new BillingSystem().generate()
assertNotNull(bill)
}
#Test
public void generatesAnInvoiceNumberForEachBill() {
// Using hand rolled mocks
MockInvoiceNumbering in = new MockInvoiceNumbering()
in.generateNextShouldReturn(4)
Bill bill = new BillingSystem(in).generate()
assertEquals(4, bill.getNumber())
}
#Test
public void generatesUniqueInvoiceNumbersForEachBill() {
MockInvoiceNumbering in = new MockInvoiceNumbering()
BillingSystem bs = new BillingSystem(in)
bs.generate();
bs.generate();
assertEquals(2, in.numberOfTimesGenerateNextWasCalled)
}
#Test
public void generatesAnInvoiceSubjectWhenNoneIsSpecified() {
Bill bill = new BillingSystem().generate()
assertEquals("Invoice #1 from ACME Corp.", bill.getSubject())
}
#Test
public void allowsForCustomSubjectsOnBills() {
Bill bill = new BillingSystem().generate("Custom subject")
assertEquals("Custom subject", bill.getSubject())
}
As a part of this refactoring, you would likely create some tests around your InvoiceNumbering class.
Hope that's enough of a start. Left a lot out. :-)
Hope that helps!
Brandon