For some reason in the testEmployee method I am getting weird error messages saying illegal character.
I've looked at the code but can't find anything syntactically wrong with it.
Any help would be great thanks!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import ttp.Cache;
import ttp.DataException;
import ttp.EmployeeDAO;
import ttp.Employee;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* #author ericrea
*/
public class Tester {
public Tester() {
}
#BeforeClass
public static void setUpClass() throws Exception {
}
#AfterClass
public static void tearDownClass() throws Exception {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
// TODO add test methods here.
// The methods must be annotated with annotation #Test. For example:
//
// #Test
// public void hello() {}
// /** Test the Skeleton BO/DAO */
// #Test
// public void TestSkeleton() throws Exception {
// Skeleton s = SkeletonDAO.getInstance().create(“skeleton1”);
// s.save();
//
// // since skeleton1 is in the Cache, this tests reading from the cache
// Skeleton s2 = SkeletonDAO.getInstance().read(“skeleton1”);
// assertSame(s, s2);
//
// // now clear the cache (you’d never do this in the real world)
// // then we can test reading from the database
// Cache.getInstance().clear();
// Skeleton s3 = SkeletonDAO.getInstance().read(“skeleton1”);
// assertEquals(s.getId(), s3.getId());
// //assertEquals(s.getSomething(), s3.getSomething());
//
// // keep testing more methods, BOs, and DAOs
// }//TestSkeleton
// //5. Right-click the file and run the file. You’ll see it test. It will obviously have errors
// //because Skeleton isn’t a real BO/DAO.
// //6. Note in the above code the “assertEquals” methods. That is how you test that two things are equals.
#Test
public void TestEmployee() throws DataException {
Employee e = EmployeeDAO.getInstance().create(“Employee1”);
e.save();
// since skeleton1 is in the Cache, this tests reading from the cache
Employee e2 = EmployeeDAO.getInstance().read(“Employee1”);
assertSame(e, e2);
// now clear the cache (you’d never do this in the real world)
// then we can test reading from the database
Cache.getInstance().clear();
Employee e3 = EmployeeDAO.getInstance().read(“Employee1”);
assertEquals(e.getId(), e3.getId());
assertEquals(e.getName1(), s]e3.getName1());
}
You seem to use 'fancy' quotes (“) instead of normal ones (")
PS If Matt is right, please do not use Word to edit your programs. There're lots of IDEs, but even Notepad would be easier.
The fragment
s]e3.getName1()
(last line) doesn't look right: remove the "s]" fragment.
Edit: You are also missing the closing parenthesis for the class at the end of the code.
Related
I am trying to pass a list of classes as a parameter. (Can I do this?) I am using JUnit and Selenium, I have JUnit test classes that are called by a JUnit test suite class, using #SuiteClasses() and that test suite class is called by a class containing a main(). My idea is to allow the user to pick JUnit classes from the main class which will be stored in some kind of list. The Test Suite that calls the JUnit test classes to be run will use that list and call those JUnit classes.
Original Code: the test suite class that calls the JUnit test classes that should be run (works) ⬇
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
#RunWith(Suite.class)
#SuiteClasses({ TestCase1.class, TestCase2.class})
public class AllTests {
}
I am trying to change it to something like ⬇
#SuiteClasses(runnerClass.classesToTest)
and in the runner class I would have something like this. I was thinking, I can pull names of classes from prop file maybe, and allow the user to pick which classes will be added to variable classesToTest ⬇
public class runnerClass {
public static Class<?>[] classesToTest = { testCase1.class, testCase2.class };
public static void main(String[] args) {
...
}
}
When I try to do something like this, I get this error ⬇
The value for annotation attribute Suite.SuiteClasses.value must be a class literal
JavaDoc for #SuiteClasses()
So question being, can I make this work? Am I creating my classesToTest variable incorrectly?
I could not find any solution in the JUnit framework, so I wrote a quick and dirty Test runner. It just calls all Methods annotated with #Test, even non-accessible ones (just in case).
It won't work with any IDE included UnitTest result displaying tools.
It is used like the following:
public static void main(String[] args) {
Runner run = new Runner(TestCase.class, TestCase2.class);
for(Exception e : run.runUnchecked()) {
System.err.println(e.getCause());
}
}
You can pass the Classes either as vararg or a normal array, both will work. The Runner will return a List of Exceptions of the tests. If a test fails, it throws an Exception, either the exception that caused the fail, or if an assertion failed, then a AssertionFailedError is thrown. You can easily print a one line description with e.getCause(), this will display a message like this: org.opentest4j.AssertionFailedError: expected: <1> but was: <2>
My example Code works with JUnit Jupiter tests, you can adapt it by changing which Test class is imported in the Runner class. This has to be the same, that is used for your TestCases.
Here is the Code
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* A simple JUnit Test Case Runner, which can dynamically call TestCases by
* their class.
*
* #author Alexander Daum
*
*/
public class Runner {
private Class<?>[] testCases;
public Runner(Class<?>... testCases) {
this.testCases = testCases;
}
/**
* Run all TestCases given in the constructor of this Runner.
*
* #throws InvocationTargetException
* #throws IllegalArgumentException
* #throws IllegalAccessException
* #throws InstantiationException
*/
public List<Exception> run()
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
List<Exception> testErrors = new ArrayList<>();
for (Class<?> testClazz : testCases) {
Object testCase = testClazz.newInstance();
Method[] methods = testClazz.getDeclaredMethods();
methods = Arrays.stream(methods).filter(m -> m.isAnnotationPresent(Test.class)).toArray(Method[]::new);
for (Method m : methods) {
m.setAccessible(true);
try {
m.invoke(testCase);
} catch (InvocationTargetException e) {
testErrors.add(e);
}
}
}
return testErrors;
}
/**
* The same as {#link Runner#run()}, but all exceptions are wrapped in
* RuntimeException, so no try catch is neccessary, when Errorhandling is not
* required
*/
public List<Exception> runUnchecked() {
try {
return run();
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| InstantiationException e) {
throw new RuntimeException(e);
}
}
}
Overview: There are instances where in I want to stop the running cucumber test pack midway -- say for example when x number of tests failed.
I can do this just fine but I want the json file (plugin = {json:...}) to be generated when the test stops. Is this doable?
What I've tried so far:
Debug and see where the reporting / plugin generation happens. It seems to be when this line executes:
Cucumber.java: runtime.getEventBus().send.....
#Override
protected Statement childrenInvoker(RunNotifier notifier) {
final Statement features = super.childrenInvoker(notifier);
return new Statement() {
#Override
public void evaluate() throws Throwable {
features.evaluate();
runtime.getEventBus().send(new TestRunFinished(runtime.getEventBus().getTime()));
runtime.printSummary();
}
};
}
I was hoping to access the runtime field but it has a private modifier. I also tried accessing it via reflections but I'm not exactly getting what I need.
Found a quite dirty, but working solution and got what I need. Posting my solution here in case anyone might need.
Create a custom cucumber runner implementation to take the runtime instance.
public final class Foo extends Cucumber {
static Runtime runtime;
/**
* Constructor called by JUnit.
*
* #param clazz the class with the #RunWith annotation.
* #throws IOException if there is a problem
* #throws InitializationError if there is another problem
*/
public Foo(Class clazz) throws InitializationError, IOException {
super(clazz);
}
#Override
protected Runtime createRuntime(ResourceLoader resourceLoader, ClassLoader classLoader, RuntimeOptions runtimeOptions) throws InitializationError, IOException {
runtime = super.createRuntime(resourceLoader, classLoader, runtimeOptions);
return runtime;
}
}
Call the same line that generates the file depending on the plugin used:
public final class ParentHook {
#Before
public void beforeScenario(Scenario myScenario) {
}
#After
public void afterScenario() {
if (your condition to stop the test) {
//custom handle to stop the test
myHandler.pleaseStop();
Foo.runtime.getEventBus().send(new TestRunFinished(Foo.runtime.getEventBus().getTime()));
}
}
}
This will however require you to run your test via Foo.class eg:
#RunWith(Foo.class) instead of #RunWith(Cucumber.class)
Not so much value here but it fits what I need at the moment. I hope Cucumber provides a way to do this out of the box. If there's a better way, please do post it here so I can accept your answer once verified.
Why not quit?
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.When;
public class StepDefinitions {
private static int failureCount = 0;
private int threshold = 20;
#When("^something$")
public void do_something() {
// something
}
#After
public void after(Scenario s) {
if (s.isFailed()) ++failureCount;
}
#Before
public void before() {
if (failureCount > threshold) {
if (driver !=null) {
driver.quit();
driver = null;
}
}
}
In a Saving account for the withdraw variables i need to make sure it can't withdraw more than 3 in a month. I checked the criteria in the setter but I'm not sure how to do the testing in the JUintTesting. As both of them are void method and the testing method returns a boolean i am getting a error of void below is my code.
public void setNumberWithdrawals(int w)
{
if (getNumberWithdrawals() > 3)
{
System.out.println("You already have more than 3 withdraw!!");
}
else
{
numberWithdrawals = w;
}
}
For JUNit testing
SavingsAccount sa1;
#Test
public void testsetNumberWithdrawals()
{
assertEquals(true, sa1.setTest(4));
}
I am expecting it to return false since i pass 4 but i keep on getting the void and return type expected error, i even tried assigning the value to another int variable for number and tested it but i still got the error.
Assumption: You're using JUnit 4 (seems like a safe assumption given that the code you provided is using the #Test annotation).
You would want something like this for your test class:
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SavingsAccountTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
#Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
#After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
#Test
public void test() {
SavingsAccount savingsAcct = new SavingsAccount(...);
savingsAcct.setNumberWithdrawals(...);
assertEquals("You already have more than 3 withdraw!!\r\n", outContent.toString());
}
}
Other thoughts:
Given the code you posted in your question and code on github some things seem a little strange. It might just be that some of the code is still missing, but I want to point out a few things that stand out:
You posted this code:
assertEquals(true, sa1.setTest(4));
Now according to what I read on github, sa1 is an instance of SavingsAccount yet I don't see a definition for this setTest(...) method anywhere. I do see this SavingsAccount extends Account so I suppose setTest(...) could be defined in the Account class. The reason this stands out is that you said you were trying to test SavingsAccount.setNumberWithdrawals(...) but you're not invoking setNumberWithdrawals in your test. Again, I suppose that this setTest method could indirectly invoke setNumberWithdrawals but that's not clear from everything you posted.
You said in your question:
make sure it can't withdraw more than 3
The logic you have is if (getNumberWithdrawals() > 3) which means the number of withdrawals will have to be more than 3 to trigger this logic. This seems to violate your requirement.
This is a sample program:
public class FunctionalTest {
public int f(int r) {
int result = r * 5;
return result;
}
public static void main(String[] args) {
FunctionalTest funct = new FunctionalTest();
System.out.println(funct.f(5));
}
}
I'm a beginner.
How to write a functional test for this code?
How to write functional tests? Do I need to TestNG?
Is it enough to write the examination method?
Could someone explain to me and write a sample functional test for this program?
Well, if you're specifically asking for functional testing, there's not much you can do with that code snippet. You can do a unit test from the f method using JUnit like this:
#Test
public void testF(){
FunctionalTest t1 = new FunctionalTest();
assertEquals((t1.f(1) % 5), 0); //checks that is getting multiplied by 5.
}
However, you want functional testing, so by running your compiled app and assessing the result you're testing your app functionality by multiple units (AKA integration): your f method and your main method.
Regards!
First of all, you need to have a clear definition of contract you want to verify. From the code, I assume it is something like "the method should return the number equal to argument multiplied by 5".
TestNG, JUnit or other test frameworks is not mandatory for your case. The test may look like:
public void testF() {
int arg = 5;
int result = new FunctionalTest().f(arg);
assert result == arg * 5;
}
Also please keep in mind that to use assert you need JVM started with -ea flag.
Beware the terms you used:
the functional testing provide values to your user/customer
That implies:
black box testing: you have to test your whole system (hard+soft)
the test should target your user/customer needs (explicit report or test)
You can use whatever you want to test the feature (from unit test to jbehave).
In your case (using JUnit 4 and AssertJ):
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
As an user
I want have 25 whatever I sent
*/
public class NumberGenerationTest {
private static final String PATH = "directory of your class file";
private InputStream stdout;
/* Nominal case */
#Test
public void shall_return_number_25_when_called_with_5() throws Exception {
when_I_call_FunctionalTest_with("5");
then_it_returns("25");
}
/* Nominal case or potential error case */
#Test
public void shall_return_number_25_when_called_with_10() throws Exception {
when_I_call_FunctionalTest_with("10");
then_it_returns("25");
}
/* Nominal case or potential error case */
#Test
public void shall_return_number_25_when_called_with_ABC() throws Exception {
when_I_call_FunctionalTest_with("ABC");
then_it_returns("25");
}
private void when_I_call_FunctionalTest_with(String parameter) throws Exception {
ProcessBuilder builder = new ProcessBuilder("java" ,"-classpath", PATH,"FunctionalTest" , parameter);
builder.redirectErrorStream(true);
Process process = builder.start();
stdout = process.getInputStream ();
}
private void then_it_returns(String expectedResult) throws Exception {
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
String line = reader.readLine ();
Assertions.assertThat(line).isNotNull();
Assertions.assertThat(line).isEqualTo(expectedResult);
}
}
It seems you have an error in your main() ... or not.
I starting to use FEST to help me to perform unit test on my Java Swing GUI.
For now, I managed to get through the documentation (mostly deprecated) and help me by looking at the Javadoc and the code.
Right now I am stuck on a problem while using the NoExitSecurityManager. The documentation is quite out dated but we can understand the big lines of it.
I simply try to test if my "Quit" MenuItem is working well in my GUI. So, I need to block the System.exit(0) and map the exit status of the program to a JUnit test.
Here is a simplified code I use to perform the test (the tested class is GraphicalUserInterface).
import org.junit.Test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.edt.GuiQuery;
import org.fest.swing.edt.GuiActionRunner;
import org.fest.swing.fixture.FrameFixture;
import org.fest.swing.junit.testcase.FestSwingJUnitTestCase;
import org.fest.swing.security.NoExitSecurityManagerInstaller;
public class GraphicalUserInterfaceTest extends FestSwingJUnitTestCase {
private static FrameFixture gui;
private static NoExitSecurityManagerInstaller noExitSecurityManagerInstaller;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
NoExitSecurityManagerInstaller.installNoExitSecurityManager(new ExpectExitSuccess());
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
noExitSecurityManagerInstaller.uninstall();
}
#Override
protected void onSetUp() {
gui = new FrameFixture(robot(), createNewGUI());
gui.show();
}
#RunsInEDT
private GraphicalUserInterface createNewGUI() {
return GuiActionRunner.execute(new GuiQuery<GraphicalUserInterface>() {
protected GraphicalUserInterface executeInEDT() {
return new GraphicalUserInterface();
}
});
}
#Test
public final void testFileMenuQuitMenuItem() {
gui.menuItemWithPath("File", "Quit").click();
}
}
The ExitCallHook are coded like this (you can guess the other one easily).
import static org.junit.Assert.assertTrue;
import org.fest.swing.security.ExitCallHook;
public final class ExpectExitSuccess implements ExitCallHook {
#Override
public void exitCalled(int status) {
assertTrue(status == 0);
}
}
All the tests are performed well and everything seems to be ok except that I get a java.lang.NullPointerException at the end.
So, I wonder what did I do wrong (or what can I improve to not get this nullpointer exception at the end of the test).
I found the solution in the code. In fact, the proper way to do it is the following:
#Test
public final void testFileMenuQuitMenuItem() {
NoExitSecurityManagerInstaller noExitSecurityManagerInstaller =
NoExitSecurityManagerInstaller.installNoExitSecurityManager(new ExpectExitSuccess());
gui.menuItemWithPath("File", "Quit").click();
noExitSecurityManagerInstaller.uninstall();
}
This way prevent to pollute each test with a NoExitSecurityManager.