java.lang.AssertionError: Cassandra daemon did not start within timeout - java

My Test Class :
public class NetworkSettingsDaoTest {
#Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet("simpleWithCreateKeyspace.cql"));
public static Session session;
public static NetworkSettingsDao networkSettingsDao;
#Before
public void init() throws ConfigurationException, TTransportException, IOException, InterruptedException{
EmbeddedCassandraServerHelper.startEmbeddedCassandra(5600000L);
//Thread.sleep(4*1000); //workaround for weak machine
session = cassandraCQLUnit.getSession();
networkSettingsDao = new NetworkSettingsDao();
}
#Test
public void should_have_started_and_execute_cql_script() throws Exception {
ResultSet result = session.execute("select * from mytable WHERE id='myKey01'");
assertThat(result.iterator().next().getString("value"), is("myValue01"));
}
}
My simpleWithCreateKeyspace.cql file :
CREATE KEYSPACE NETWORKSETTINGS WITH replication={'class' : 'SimpleStrategy', 'replication_factor':1};
USE NETWORKSETTINGS;
CREATE TABLE STBDevice(
KEY varchar,
SETTINGS_COLUMN varchar,
AMSIP varchar,
PRIMARY KEY(KEY));
INSERT INTO STBDevice(KEY, SETTINGS_COLUMN,AMSIP) values('myKey01','myColumn1','myAMSIP1');
Exception :
java.lang.AssertionError: Cassandra daemon did not start within
timeout at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:130)
at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:85)
at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:64)
at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:56)
at
org.cassandraunit.BaseCassandraUnit.before(BaseCassandraUnit.java:28)
at
org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:46)
at org.junit.rules.RunRules.evaluate(RunRules.java:20) at
org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at
org.junit.runners.ParentRunner.run(ParentRunner.java:309) at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

In my case, the server ALWAYS started within the default 10 sec window until yesterday. Today, it takes 50 to 70 secs. No valid explanation. So, looks like the only option is to increase the timeout.

Looks, It depends on the number of queries you fire on Cassandra.. If you have too many queries to run then you need to increase the timeout in EmbeddedCassandra annotation. #EmbeddedCassandra(timeout = 100000L)

This class helped to solve problems
package org.cassandraunit.test.spring.cql;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import org.cassandraunit.spring.CassandraDataSet;
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
import org.cassandraunit.spring.EmbeddedCassandra;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
#RunWith(SpringJUnit4ClassRunner.class)
#TestExecutionListeners({ CassandraUnitTestExecutionListener.class })
#CassandraDataSet(value = { "simple.cql" })
#EmbeddedCassandra
public class SpringCQLScriptLoadTest {
#Test
public void should_have_started_and_execute_cql_script() throws Exception {
Cluster cluster = Cluster.builder()
.addContactPoints("127.0.0.1")
.withPort(9142)
.build();
Session session = cluster.connect("cassandra_unit_keyspace");
ResultSet result = session.execute("select * from mytable WHERE id='myKey01'");
assertThat(result.iterator().next().getString("value"), is("myValue01"));
}
}

Related

Cant apply rest controllers junit tests correctly

I am trying to apply junit test for my rest controllers.
I've tried to apply junit 4 but I got 404 error instead 200.
It looks like something is not initialized but cant't figured what.
Here is tutorial I have tried to apply.
https://www.youtube.com/watch?v=8S8o46avgAw
I also tried some different tutorials with junit 5 but the result was the same.
Here you can find the whole project.
https://github.com/WojciechWeg/tiny-bank/tree/tests
Just before publishing this post I've applied the following:
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
But the result of it is:
Customers from service: []
So it returns nothing. Above snippet is not in repo link.
Rest controller class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Account;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.model.CustomerResource;
import com.tinybank.tinybankapi.services.CustomerService;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
#RestController
#RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
public static final String BASE_URL = "api/customers";
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resources<List<Customer>>> getListOfCustomers() {
Resources<List<Customer>> resources = new Resources(customerService.getAllCustomers());
String uri = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
resources.add(new Link(uri,"self"));
return ResponseEntity.ok(resources);
}
#GetMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public Customer getCustomer(#PathVariable Long id) {
return customerService.getCustomerById(id);
}
#DeleteMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public void deleteCustomer(#PathVariable Long id) {
customerService.deleteCustomerById(id);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<CustomerResource> createNewCustomer(#RequestBody #Valid Customer Customer) {
Customer customer = customerService.createNewCustomer(Customer);
URI uri = MvcUriComponentsBuilder.fromController(getClass())
.path("/{id}")
.buildAndExpand(customer.getId())
.toUri();
return ResponseEntity.created(uri).body(new CustomerResource(customer));
}
#PutMapping({"/{id}/open_account"})
#ResponseStatus(HttpStatus.OK)
public void openAccount(#PathVariable Long id, #RequestBody Account account) {
customerService.openAccount(id, account);
}
}
Test class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.services.CustomerService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.Date;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
public class CustomerControllerTest {
private MockMvc mockMvc;
#Mock
private CustomerService customerService;
#InjectMocks
private CustomerController customerController;
Customer customer;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
#Test
public void getCustomer() throws Exception {
when(customerService.getCustomerById(any())).thenReturn(customer);
mockMvc.perform(get("api/customers/1"))
.andExpect(status().isOk());
}
}
This is how stack trace looks like:
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at com.tinybank.tinybankapi.controllers.CustomerControllerTest.getCustomer(CustomerControllerTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Have you tried below approach without injecting mocks?
MockMvcBuilders.standaloneSetup(new CustomerController())
.build();
EDIT:
I've ran your code locally.
Do this:
mockMvc = MockMvcBuilders.standaloneSetup(new CustomerController(customerService))
.build();
And add slash to the beginning of URL
mockMvc.perform(get("/api/customers/1"))
.andExpect(status().isOk());

NullPointerException on running selenium script with JUnit

I am using pageObject Model for my selenium automation.
Consider following browser config class.
package BrowserConfig;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class crossBrowserConfiguration {
By logInPanel = By.xpath("//div[#id='logInPanelHeading']");
public static WebDriver driver = null;
WebDriverWait wait = new WebDriverWait(driver,30);
#Before
public void initBrowser(){
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("Website that contains Login Page");
wait.until(ExpectedConditions.visibilityOfElementLocated(logInPanel));
}
#After
public void closeBrowser(){
driver.quit();
}
}
I have a page object of Log in screen.
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import BrowserConfig.crossBrowserConfiguration;
public class LoginScreen extends crossBrowserConfiguration {
WebDriverWait wait = new WebDriverWait(driver,30);
By userName = By.xpath("//input[#id='txtUsername']");
By password = By.xpath("//input[#id='txtPassword']");
By loginButton = By.xpath("//input[#id='btnLogin']");
By welcomeNote = By.xpath("//a[#id='welcome']");
By empListVerify = By.xpath("//div[#id='employee-information']/a");
public void logIN(String UserName, String Password){
driver.findElement(userName).sendKeys(UserName);
driver.findElement(password).sendKeys(Password);
driver.findElement(loginButton).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(welcomeNote));
//Employee List Verification
String empListBtnText = driver.findElement(empListVerify).getText();
System.out.println(empListBtnText);
}
}
And finally, I have the following test case script:
package TestCases;
import org.junit.Test;
import BrowserConfig.crossBrowserConfiguration;
import PageObjects.LoginScreen;
public class initiateBrows extends crossBrowserConfiguration{
LoginScreen Obj1 = new LoginScreen();
#Test
public void runThis() throws Exception{
Obj1.logIN("admin", "123456");
}
}
When I run my test as JUnit Test, it gives nullPointerException without running at all. Stack trace for the exception is:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:212)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:102)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
at BrowserConfig.crossBrowserConfiguration.<init>(crossBrowserConfiguration.java:15)
at TestCases.initiateBrows.<init>(initiateBrows.java:8)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
at BrowserConfig.crossBrowserConfiguration.<init>(crossBrowserConfiguration.java:15)
refers to WebDriverWait wait = new WebDriverWait(driver,30);
Any insight into why am I facing this exception?
The wait field is initialized when the an object of the class is created. This happens before JUnit calls the #Before method. Therefore the driver object is null. There are different ways of fixing the issue. One is making the driver object a simple field and initialize it immediately.
public class crossBrowserConfiguration {
By logInPanel = By.xpath("//div[#id='logInPanelHeading']");
public final WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,30);
#Before
public void initBrowser(){
driver.manage().window().maximize();
driver.get("Website that contains Login Page");
wait.until(ExpectedConditions.visibilityOfElementLocated(logInPanel));
}
#After
public void closeBrowser(){
driver.quit();
}
}

Spring controller unit testing with spring-test-mvc is failing

I am learning unit testing of spring controller with EasyMock and Spring test framework. I have done a simple unit testing for my controller.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.firstmav.domain.Employee;
import com.firstmav.service.EmployeeService;
#Controller
public class DataController {
#Autowired
EmployeeService employeeservice;
#RequestMapping("form")
public ModelAndView getform(#ModelAttribute Employee employee){
return new ModelAndView("form");
}
#RequestMapping("reguser")
public ModelAndView registeruser(#ModelAttribute Employee employee){
employeeservice.insertRow(employee);
return new ModelAndView("redirect:list");
}
#RequestMapping("list")
public ModelAndView getlist(){
List<Employee> employeelist = employeeservice.getList();
return new ModelAndView("list", "employeeList", employeelist);
}
#RequestMapping("delete")
public ModelAndView deleteitem(#RequestParam int id){
employeeservice.deleteRow(id);
return new ModelAndView("redirect:list");
}
#RequestMapping("edit")
public ModelAndView edititem(#ModelAttribute Employee employee, #RequestParam int id){
Employee employeeObject = employeeservice.getRowByID(id);
return new ModelAndView("edit", "employeeObject", employeeObject);
}
#RequestMapping("update")
public ModelAndView updaterow(#ModelAttribute Employee employee){
employeeservice.updateRow(employee);
return new ModelAndView("redirect:list");
}
}
and i have my failing test case here.
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.firstmav.controller.DataController;
public class DataControllerTest {
private MockMvc mockmvc;
#Before
public void setup(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
mockmvc = MockMvcBuilders.standaloneSetup(new DataController()).setViewResolvers(viewResolver).build();
}
#Test
public void main() throws Exception{
mockmvc.perform(get("/form")).andExpect(status().isOk()).andExpect(view().name("form"));
}
}
I have included the controller import in the test case but i always getting the noclassdeffound exception.
java.lang.NoClassDefFoundError: javax/servlet/ServletException
at org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup(MockMvcBuilders.java:71)
at com.ada.test.DataControllerTest.setup(DataControllerTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 25 more
I don't understand where i am making the mistake. Can any one help me or point me to right direction?
The issue is not related with your code.You're missing the library(jar) which contains javax.servlet.ServletException.So at runtime you're getting this exception.Check you class path if you have the servlet-api.jar in that location.
Though adding servlet-api.jar into your class path location should resolve the issue but if you want you can also check the jars that have this class here

UISpec4J tests in Eclipse are not found

I am trying to run tests using the UISpec4J library, but Eclipse says it can not find them. I have tried restarting Eclipse, cleaning the project, etc.
The class gives no errors and I have followed the examples given on the website.
package com.health.gui;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uispec4j.Button;
import org.uispec4j.Panel;
import org.uispec4j.UISpec4J;
import org.uispec4j.UISpecTestCase;
import org.uispec4j.Window;
import org.uispec4j.interception.WindowInterceptor;
import com.health.gui.input.xmlwizard.XmlFilePanel;
public class TestXmlFilePanel extends UISpecTestCase {
static {
UISpec4J.init();
}
private Panel panel;
#BeforeClass
public void setUp() {
panel = new Panel(new XmlFilePanel());
}
#Test
public void editWithoutSelectedTest() {
Button edit = panel.getButton("Edit selected");
Window popup = WindowInterceptor.run(edit.triggerClick());
popup.titleEquals("Warning!");
}
}
I get the following stacktrace:
junit.framework.AssertionFailedError: No tests found in com.health.gui.TestXmlFilePanel
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.TestCase.fail(TestCase.java:227)
at junit.framework.TestSuite$1.runTest(TestSuite.java:100)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I really have no clue what is wrong. Maybe you have some suggestions?
just for fun. you can remove "extends UISpecTestCase" in your class and give it a try see if it works or not :)
Junit 4.X should support annotation well and I didn't see any reason you need to extends UISpecTestCase.

On accessing database through test I get play.exceptions.JPAException: The JPA context is not initialized

I am trying to access the database through a class using PlayFremwork and writing a test
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import models.com.vlist.entity.classes.Playlist;
import org.junit.Test;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.jobs.OnApplicationStart;
import play.mvc.Scope.Session;
public class PlaylistTest {
#Test
#Transactional
public void insertIntoPlaylist() {
Playlist playlist = new Playlist();
playlist.setId(1);
playlist.setName("test");
EntityManager em = JPA.em();
em.persist(playlist);
}
}
The error stacktrace is:
play.exceptions.JPAException: The JPA context is not initialized. JPA Entity Manager automatically start when one or more classes annotated with the #javax.persistence.Entity annotation are found in the application.
at play.db.jpa.JPA.get(JPA.java:22)
at play.db.jpa.JPA.em(JPA.java:51)
at PlaylistTest.insertIntoPlaylist(PlaylistTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
How can I resolve this issue while writing test?
Thank you
FIXED!! By extending FunctionalTest
public class PlaylistTest extends FunctionalTest {
#Test
#Transactional
public void insertIntoPlaylist() {
Playlist playlist = new Playlist();
playlist.setName("new_playlist_again");
EntityManager em = JPA.em();
em.persist(playlist);
}
}
public class PlaylistTest extends FunctionalTest {
#Test
#Transactional
public void insertIntoPlaylist() {
Playlist playlist = new Playlist();
playlist.setName("new_playlist_again");
EntityManager em = JPA.em();
em.persist(playlist);
}
}

Categories

Resources