I have a class which compiles and runs as expected (adds one test node per execution):
public class ReqsDb {
private final String STORE_DIR;
public GraphDatabaseService graphDb;
private static enum RelTypes implements RelationshipType {
IDENTIFIES, SATIFIES
}
public ReqsDb(String dbPath) {
STORE_DIR = dbPath;
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIR);
registerShutdownHook(graphDb);
}
public void createTestNode() {
Transaction tx = graphDb.beginTx();
Node newNode;
try {
newNode = graphDb.createNode();
newNode.setProperty("test", "test");
tx.success();
} finally {
tx.finish();
}
}
private static void registerShutdownHook(final GraphDatabaseService graphDb) {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
graphDb.shutdown();
}
});
}
void shutDown() {
graphDb.shutdown();
}
public static void main(String[] args) {
ReqsDb testDb = new ReqsDb("target/testDb");
testDb.createTestNode();
}
}
However the test function, testCreateTestNode() causes error:
java.lang.RuntimeException: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.StoreLockerLifecycleAdapter#4e3a2be1' was successfully initialized, but failed to start.
Since the function works as called from main(), I think there is something wrong with the test class.
package com.github.dprentiss;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ReqsDbTest extends TestCase {
protected ReqsDb testDb = new ReqsDb("target/testDb");
public ReqsDbTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(ReqsDbTest.class);
}
public void testDbService() {
assertNotNull(testDb);
}
public void testCreateTestNode() {
testDb.createTestNode();
}
public void tearDown() {
testDb.shutDown();
}
Is there something wrong with my test set up?
Try to put
protected ReqsDb testDb = new ReqsDb("target/testDb");
in an init method . Follow this example:
Is there a basic template I can use to create a test?
Related
I have a Java class as follow
public class MyClass {
private final ShowFactory showFactory;
private SomeShow someShow;
public MyClass(ShowFactory showFactory) {
this.showFactory = showFactory;
startShow();
}
public void startShow() {
someShow = showFactory.createShow();
someShow.start();
}
public void showSomething() {
MagicBox magicBox = new MagicBox();
someShow.showSomething(magicBox);
}
public void stopShow() {
someShow.stop();
}
}
and trying to test showSomething method. Complete test file is as follow
public class MyClassTest {
private ShowFactory showFactory;
private SomeShow someShow;
#Before
public void setUp() {
showFactory = mock(ShowFactory.class);
someShow = mock(SomeShow.class);
when(showFactory.createShow()).thenReturn(someShow);
}
#Test
public void shouldStartShow() {
new MyClass(showFactory);
verify(someShow).start();
}
#Test
public void shouldShowSomething() throws Exception {
MagicBox magicBox = mock(MagicBox.class);
PowerMockito.whenNew(MagicBox.class).withAnyArguments().thenReturn(magicBox);
doNothing().when(someShow).showSomething(magicBox);
InOrder inOrder = inOrder(someShow);
MyClass myClass = new MyClass(showFactory);
myClass.showSomething();
inOrder.verify(someShow).start();
inOrder.verify(someShow).showSomething(magicBox);
}
#Test
public void shouldStopShow() {
MyClass myClass = new MyClass(showFactory);
myClass.stopShow();
verify(someShow).start();
verify(someShow).stop();
}
}
But test shouldShowSomething is failing with error Wanted but not invoked. Any thing I am missing here? Any suggestion?
It was simple fix. After reading through https://github.com/powermock/powermock/wiki/MockConstructor#quick-summary (thanks to #roby) turns out I was missing the #PrepareForTest annotation for the class.
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class MyClassTest {
...
}
before refactor:
public interface Service {
public void hello(Person p);
}
public class BlackPersonServiceImpl implements Service {
#Override
public void hello(Person p) {
//...
}
}
public class WhitePersonServiceImpl implements Service {
#Override
public void hello(Person p) {
//...
}
}
public class BeforeRefactor {
public static void main(String[] args) {
String str = args[0];
Person p = JSON.parseObject(str, Person.class);
Service service = getServiceFromSpringContainer();
service.hello(p);
}
private static Service getServiceFromSpringContainer() {
//...
return null;
}
}
after refactor:
public interface Service {
public void hello(String str);
}
public class WhitePersonServiceImpl implements Service {
#Override
public void hello(String str) {
Person person = JSON.parseObject(str, Person.class);
//do something to person...
//...
}
}
public class AfterRefactor {
public static void main(String[] args) {
String str = args[0];
Service service = getServiceFromSpringContainer();
service.hello(str);
}
private static Service getServiceFromSpringContainer() {
//...
return null;
}
}
That's what I want(I think "pull down" is not the "right" word to describe it...).
I tried "introduce parameter object" in eclipse, and it does not work.
There are many implementations of "Service". I dont want to change them one by one.
Is there a good way to solve this problem?
Thanks!
You can do it somewhat for a single class and a single method (although it's akward and a succession of small refactoring steps), but not across several types at the same time.
I am new to jmockit and trying to execute the following online example.
The #MockClass is not working. My BookStore's getBookTitle() method is calling the function of orginal class instead of the mock class.
BookStore class:
public class BookStore {
public String getBookTitle(String isbn){
return BookStoreService.getBookTitle(isbn);
}
}
BookStoreService class:
public class BookStoreService {
public static String getBookTitle(String isbn){
return "Random";
}
}
Test class:
public class BookStoreTest {
private static Map<String, String> bookMap = new HashMap<String, String>(2);
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
}
#MockClass(realClass = BookStoreService.class)
public static class MockBookstoreService {
#Mock
public static String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
}
#Test
public void testGetBookTitle() throws Exception {
System.out.println("in testGetBookTitle()");
final String isbn = "0553293354";
final String expectedTitle = "Foundation";
BookStore store = new BookStore();
String title = store.getBookTitle(isbn);
System.out.println(title); // This prints "Random" instead of "Foundation"
Assert.assertEquals(title, expectedTitle);
}
}
PS: I am using TestNG
Using the latest stable version of jmockit you could do it like this:
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
new MockUp<BookStoreService>() {
#Mock
public String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
};
}
Remove the obsolete block:
public static class MockBookstoreService{...}
I am trying to use Google ThreadWeaver to write a unit test for concurrent code. No matter what I do, I will get an IllegalArgumentException. I am still working with an example, but even that does not work. This is what I tried:
public class ExampleTest {
public static class ExampleMain implements MainRunnable<Example> {
private Example example;
#Override
public Class<Example> getClassUnderTest() {
return Example.class;
}
#Override
public String getMethodName() {
return null;
}
#Override
public Method getMethod() throws NoSuchMethodException {
return null;
}
#Override
public void initialize() throws Exception {
example = new Example();
}
#Override
public Example getMainObject() {
return example;
}
#Override
public void terminate() throws Exception {
}
#Override
public void run() throws Exception {
example.test("second");
}
}
public static class ExampleSecondary implements SecondaryRunnable<Example, ExampleMain> {
private ExampleMain exampleMain;
#Override
public void initialize(ExampleMain main) throws Exception {
exampleMain = main;
}
#Override
public void terminate() throws Exception {
}
#Override
public boolean canBlock() {
return false;
}
#Override
public void run() throws Exception {
exampleMain.getMainObject().test("main");
}
}
public static class Example {
private List<String> list = new ArrayList<String>();
public String test(String s) {
System.out.println("1" + s);
list.add(s);
System.out.println("2" + s);
return list.get(0);
}
}
#Test
public void testThreadWeaver() throws Exception {
ClassInstrumentation instrumentation = Instrumentation.getClassInstrumentation(Example.class);
Method tested = Example.class.getDeclaredMethod("test", String.class);
Method breakpoint = List.class.getDeclaredMethod("add", Object.class);
CodePosition codePosition = instrumentation.afterCall(tested, breakpoint);
InterleavedRunner.interleave(new ExampleMain(), new ExampleSecondary(), Arrays.asList(codePosition)).throwExceptionsIfAny();
}
}
The stack trace says:
java.lang.IllegalArgumentException: Class Example is not instrumented
at
com.google.testing.threadtester.CallLoggerFactory.getClassInstrumentation(CallLoggerFactory.java:108)
at
com.google.testing.threadtester.Instrumentation.getClassInstrumentation(Instrumentation.java:65)
at MyTest.testThreadWeaver(MyTest.java:92
I followed the instructions at the official Google code webpage, but it does not seem to work. Any ideas?
ThreadWeaver needs to instrument your classes in order to add breakpoints to your methods. Therefore, you cannot run the tests with JUnit directly but you must run your test from a specific test runner. For your case this would be ThreadedTestRunner. The actual test methods must then be annotated with #ThreadedTest instead of #Test. This should work:
#Test
public void startTest() throws Exception {
new ThreadedTestRunner().runTests(getClass(), Example.class);
}
#ThreadedTest
public void testThreadWeaver() throws Exception {
// here comes your test
}
Sorry, if this is a stupid question.
I would like to find out how to call the run method that is located in
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FereastraPrincipala().setVisible(true);
from the class AdaugaComanda.java.
The run method is declared in FereastraPrincipala.java and I want to call this from AdaugaComanda.java, so that changes can be seen to FereastraPrincipala after introducing values in the textfields from AdaugaChitanta.java. If I don't call a method, then I have to run FereastraPrincipala.java again, in order to see the new info in the JTabbedPane.
Here is the code for FereastraPrincipala.java
package sakila.ui;
import java.util.List;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;
import sakila.entity.*;
import sakila.util.HibernateUtil;
public class FereastraPrincipala extends javax.swing.JFrame {
public FereastraPrincipala() {
initComponents();
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AdaugaComanda ac = new AdaugaComanda();
ac.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FereastraPrincipala().setVisible(true);
Session session = HibernateUtil.getSessionFactory().openSession();
try{
List<Comanda> comenzi = session.createQuery("from Comanda").list();
Vector<String> tableHeaders = new Vector<String>();
Vector tableData = new Vector();
tableHeaders.add("IdComanda");
tableHeaders.add("Depozit");
tableHeaders.add("Furnizor");
tableHeaders.add("Client");
tableHeaders.add("Produs");
tableHeaders.add("Cantitate");
tableHeaders.add("Unit de mas");
for (Comanda comanda : comenzi) {
Vector <Object> oneRow = new Vector <Object>();
oneRow.add(comanda.getIdcomanda());
oneRow.add(comanda.getDepozit() == null ? "" : comanda.getDepozit().toString());
oneRow.add(comanda.getFurnizor() == null ? "" : comanda.getFurnizor().toString());
oneRow.add(comanda.getClient() == null ? "" : comanda.getClient().toString());
oneRow.add(comanda.getProdus() == null ? "" : comanda.getProdus().toString());
oneRow.add(comanda.getCantitate());
oneRow.add(comanda.getUnitmas());
tableData.add(oneRow);
}
ComandaTable.setModel(new DefaultTableModel(tableData, tableHeaders));
}catch (Exception he){
he.printStackTrace();
}
}
});
}
}
Here is the code for AdaugaComanda.java
package sakila.ui;
import java.io.EOFException;
import java.util.List;
import sakila.entity.*;
import sakila.service.Functie;
import sakila.entity.Client;
public class AdaugaComanda extends javax.swing.JDialog {
public AdaugaComanda() {
initComponents();
initComboBoxes();
}
private void initComboBoxes() {
DepozitComboBox.removeAllItems();
FurnizorComboBox.removeAllItems();
ClientComboBox.removeAllItems();
ProdusComboBox.removeAllItems();
System.out.println("sterge itemurile");
List<Depozit> depozite = (List<Depozit>) sakila.client.Client.citeste(Functie.LISTEAZA_DEPOZITE);
for (Depozit depozit : depozite)
DepozitComboBox.addItem(depozit);
List<Furnizor> furnizori = (List<Furnizor>) sakila.client.Client.citeste(Functie.LISTEAZA_FURNIZORI);
for (Furnizor furnizor : furnizori)
FurnizorComboBox.addItem(furnizor);
List<Client> clienti = (List<Client>) sakila.client.Client.citeste(Functie.LISTEAZA_CLIENTI);
for (Client client : clienti)
ClientComboBox.addItem(client);
List<Produs> produse = (List<Produs>) sakila.client.Client.citeste(Functie.LISTEAZA_PRODUSE);
for (Produs produs : produse)
ProdusComboBox.addItem(produs);
System.out.println("adaugaitemuri");
}
private void ClientComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void InsereazaButtonActionPerformed(java.awt.event.ActionEvent evt) {
runQueryBasedOnInsert();
}
private void runQueryBasedOnInsert(){
Comanda comanda = new Comanda();
Depozit depozit = (Depozit)DepozitComboBox.getSelectedItem();
comanda.setDepozit(depozit);
Furnizor furnizor = ((Furnizor)FurnizorComboBox.getSelectedItem());
comanda.setFurnizor(furnizor);
sakila.entity.Client client = ((sakila.entity.Client)ClientComboBox.getSelectedItem());
comanda.setClient(client);
Produs produs = ((Produs)ProdusComboBox.getSelectedItem());
comanda.setProdus(produs);
comanda.setCantitate(Integer.parseInt(CantitateTextField.getText()));
comanda.setUnitmas(UnitMasTextField.getText());
sakila.client.Client.scrie(Functie.CREAZA_COMANDA, comanda);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdaugaComanda().setVisible(true);
}
});
}
Maybe someone could help me. Thank you a lot!
You could make FereastraPrincipala a member variable of AnduagaChitanta.
public class AnduagaChitanta
{
FereastraPrincipala fPrincipala = new FereastraPrincipala (); //Or inject it into the constructor
private void SomeMethod()
{
fPrincipala.run();
}
}
in the run method()
public void run()
{
setvisible(true);
}
If you are wondering how to inject it:
public class AnduagaChitanta
{
FereastraPrincipala fPrincipala
public AnduagaChitanta(FereastraPrincipala fPrinicipala)
{
this.fPrinicipala = fPrinicipala;
}
private void SomeMethod()
{
fPrincipala.run();
}
}
If you like you can make FereastraPrincipala implement an interface so the definition of the constructor can be:
public AnduagaChitanta(ISomethingPrinicipala fPrinicipala)
But now we are going into design patterns so I will leave it at that.
Update
After your update I would do something like this:
FereastraPrincipala extends JFrame implements Runnable
{
public void run()
{
setvisible(true) ;
}
}
I don't know where but maybe in your AnduagaChitanta class I would do this
public void SomeMethod()
{
java.awt.EventQueue.invokeLater(fPrinicpala)
}
I hope that makes sense
Never call run() method of thread. It executes in the current thread it self !! Always call start() method. Coming to your case, create a new class so that you could invoke start() on it from other places