Jersey Test fails when running method from main package -> NullPointerException at target(...) - java

So I have tested it with this example:
Path: pkg > src > test > java > rest > SimpleJerseyTest
public class SimpleJerseyTest extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void test() {
Response response = target("hello").request().get();
assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class);
System.out.println("Gotten response: " + content);
assertEquals("Content of ressponse is: ", "Hello World!", content);
}
}
This is the output of the test:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jul 24, 2020 11:29:07 AM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Gotten response: Hello World!
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]
Process finished with exit code 0
But when I put the REST service class at in the main package, it doesnt work anymore (NullPointerException):
Package: pkg > src > main > java > rest > BookService
#Path("books")
public class BookService {
#GET
public String getAll() {
return "test";
}
}
And then the Test:
Package: pkg > src > test > rest > BookServiceTest
class BookServiceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(BookService.class);
}
#Test
void get() {
Response response = target("books").request().get();
}
}
This is the output of the test:
java.lang.NullPointerException
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:541)
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:555)
at rest.BookServiceTest.get(BookServiceTest.java:21)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
// ...
Process finished with exit code -1
What is the difference? Does anyone have a clue, why it works with a static inner class, but not with a external one?

Figured it out - I used the wrong import.
Instead of import org.junit.jupiter.api.Test it should be import org.junit.Test.

Related

Weld container doesn't inject proper object, it returns NULL

I am playing around with Weld CDI configuration. I got stuck with NULL being returned. Theoritically my configuration should make proper object instance created but I can't find reason it doesn't...
I looked up for similar questions, but most issues were related to use of new keyword while instantating the object. The other advise is to use application server. I'm running wildfly, so it's not the case as well.
Log:
Feb 17, 2021 12:12:18 AM org.jboss.weld.bootstrap.WeldStartup <clinit>
INFO: WELD-000900: 4.0.0 (Final)
Feb 17, 2021 12:12:19 AM org.jboss.weld.bootstrap.WeldStartup startContainer
INFO: WELD-000101: Transactional services not available. Injection of #Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Feb 17, 2021 12:12:19 AM org.jboss.weld.environment.se.WeldContainer fireContainerInitializedEvent
INFO: WELD-ENV-002003: Weld SE container 75c04868-bd06-4acb-874c-db603ada27b0 initialized
Exception in thread "main" java.lang.NullPointerException
at MessagePrinter.printMessage(MessagePrinter.java:9)
at Main.main(Main.java:10)
Weld SE container 75c04868-bd06-4acb-874c-db603ada27b0 shut down by shutdown hook
Process finished with exit code 1
Here's my setup:
beans.xml simple as can be
<?xml version="1.0"?>
<beans bean-discovery-mode="all" version="1.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"/>
Main class - creating Weld container
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class Main {
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
MessagePrinter printer = container.select(MessagePrinter.class).get();
printer.printMessage();
weld.shutdown();
}
}
MessagePrinter class
import javax.inject.Inject;
public class MessagePrinter {
#Inject
private MessageProducer messageProducer;
public void printMessage() {
String message = messageProducer.getMessage();
System.out.println(message);
}
}
So above MessageProducer variable is always null although one only existing MessageProducer implementation (mark as #default) should be injected...
MessageProducer interface
public interface MessageProducer {
public String getMessage();
}
SimpleMessageProducer class (MessageProducer implementation)
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
#Default
#Any
public class SimpleMessageProducer implements MessageProducer {
#Override
public String getMessage() {
return "Example message " + System.currentTimeMillis();
}
}
Project structure:
-src
--java
---FileMessage
---FileMessageProducer
---Main
---MessagePrinter
---MessageProducer
---SimpleMessageProducer
-resources
--META-INF
---beans.xml
As you are using Weld 4.0.0.Final, you should use jakarta.inject namespace instead of javax.inject.
You probably are having issues due overlapping classpaths. Keep only the org.jboss.weld.se:weld-se-core:4.0.0.Final dependency and you will probably be fine.

Cannot run parallel tests with #Factory testng annotation on java

So I use #Factory to run one test with 5 different emails, but I get wrong number of arguments exception and I can't see the full error trace on console. I use TestNG. Here's my code:
package com.task.lab.facadetask;
public class GmailTest {
private WebDriver driver;
private static List<User> usersList;
static List<TestMessage> mess;
public GmailTest(){}
#Factory(dataProviderClass = GmailTest.class, dataProvider = "getData")
public GmailTest(WebDriver driver,List<User> usersList, List<TestMessage> mess ){
this.driver = driver;
GmailTest.usersList = usersList;
GmailTest.mess = mess;
}
#BeforeMethod
public void setUpDriver(){
driver = DriverObject.getDriver();
}
#DataProvider
public static Object[][] getData() {
File usersXml = new File("src\\\\main\\\\java\\\\com\\\\task\\\\lab\\\\facadetask\\\\testdata\\\\users.xml");
try {
usersList = JAXB.unmarshal(usersXml);
} catch (JAXBException e) {
e.printStackTrace();
}
TestMessages messages = UnMarshell.unmarshaller();
assert messages != null;
mess = messages.getTestMessages();
return new Object[][]{
{mess.get(0), usersList.get(0)},
{mess.get(1), usersList.get(1)},
{mess.get(2), usersList.get(2)},
};
}
#Test
public void testGmail(TestMessage message, User users) {
String gmailURL = "https://accounts.google.com/signin";
driver.get(gmailURL);
Login loginPage = new Login();
loginPage.login(users.getEmail(), users.getPassword());
GmailMessage gmailPage = new GmailMessage();
gmailPage.sendMessage(message.getReceiver(), message.getSubject(), message.getMessage());
gmailPage.removeMessage();
Assert.assertTrue(gmailPage.isRemoved());
}
#AfterMethod
public void quitBrowser(){
try{
driver.close();
}finally{
driver.quit();
}
}
}
My assumption is that it could be caused by changing the original non static lists of users and messages to static, but DataProvider method needs to be static. Could someone guide me on what am I doing wrong?
UPD:So, I removed #BeforeMethod and included driver in #DataProvider as Krishnan suggested but it gives me the same error, wrong number of arguments. Here's what the DataProvider starts with for now:
#DataProvider
public static Object[][] getData() {
driver = DriverObject.getDriver();
File usersXml = new File //The rest remains the same
Also, I tried to initialize driver in BeforeMethod but in this case Test doesn't see it. It looks like this:
#BeforeMethod
public void setUpDriver(){
WebDriver driver = DriverObject.getDriver();
}
Maybe someone can provide me with a valid analogue of Factory so I can run 5 parallel tests simultaniously? I am open for suggestions.
Your factory method is defined to accept 3 arguments.
#Factory(dataProviderClass = GmailTest.class, dataProvider = "getData")
public GmailTest(WebDriver driver,List<User> usersList, List<TestMessage> mess ){
this.driver = driver;
GmailTest.usersList = usersList;
GmailTest.mess = mess;
}
Your data provider is only providing 2 parameters. WebDriver is not being provided by your data provider.
You can do one of the following :
Either enhance your data provider to include the WebDriver object via a call to DriverObject.getDriver() and remove your #BeforeMethod method (or)
Alter your constructor's signature to not accept a WebDriver instance, but initialize the class's WebDriver instance via the #BeforeMethod.
That should fix your problem.
EDIT: The question has been updated. So updating my answer as well.
Looking at the updates to the question, the answer is still the same on a high level. Now including a sample as well, which explains the answer.
Mocking how the User class could look like
import java.util.ArrayList;
import java.util.List;
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static List<User> newUsers(String... names) {
List<User> users = new ArrayList<>();
for (String name : names) {
users.add(new User(name));
}
return users;
}
}
Mocking how the TestMessage class could look like
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class TestMessage {
private String text;
public TestMessage(String text) {
this.text = text;
}
public String getText() {
return text;
}
public static List<TestMessage> newMessages(int howMany) {
List<TestMessage> msgs = new ArrayList<>();
for (int i = 0; i < howMany; i++) {
msgs.add(new TestMessage(UUID.randomUUID().toString()));
}
return msgs;
}
}
Here's how the test class should look like
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.List;
public class GmailTest {
private WebDriver driver;
private List<User> users;
private List<TestMessage> testMessages;
#Factory(dataProvider = "getData")
public GmailTest(WebDriver driver, List<User> users, List<TestMessage> testMessages) {
this.driver = driver;
this.users = users;
this.testMessages = testMessages;
}
#Test
public void testMethod() {
Assert.assertNotNull(driver);
Assert.assertNotNull(users);
Assert.assertNotNull(testMessages);
}
#AfterClass
public void cleanupDrivers() {
if (driver != null) {
driver.quit();
}
}
#DataProvider(name = "getData")
public static Object[][] getData() {
List<User> users = User.newUsers("Jack", "Daniel", "John");
int size = users.size();
List<TestMessage> testMessages = TestMessage.newMessages(size);
Object[][] data = new Object[size][1];
for (int i = 0; i < size; i++) {
data[i] = new Object[]{new FirefoxDriver(), Collections.singletonList(users.get(i)),
Collections.singletonList(testMessages.get(0))};
}
return data;
}
}
Here's the execution logs
1518271888011 geckodriver INFO geckodriver 0.19.1
1518271888131 geckodriver INFO Listening on 127.0.0.1:14727
1518271888627 mozrunner::runner INFO Running command: "/Applications/Firefox.app/Contents/MacOS/firefox-bin" "-marionette" "-profile" "/var/folders/mj/81r6v7nn5lqgqgtfl18spfpw0000gn/T/rust_mozprofile.5mkpumai11hO"
1518271889362 Marionette INFO Enabled via --marionette
2018-02-10 19:41:30.336 plugin-container[53151:969522] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0xad33, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271890773 Marionette INFO Listening on port 52891
1518271890793 Marionette WARN TLS certificate errors will be ignored for this session
Feb 10, 2018 7:41:30 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1518271890961 geckodriver INFO geckodriver 0.19.1
1518271891060 geckodriver INFO Listening on 127.0.0.1:6639
2018-02-10 19:41:31.225 plugin-container[53152:969613] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0xaa37, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271891259 mozrunner::runner INFO Running command: "/Applications/Firefox.app/Contents/MacOS/firefox-bin" "-marionette" "-profile" "/var/folders/mj/81r6v7nn5lqgqgtfl18spfpw0000gn/T/rust_mozprofile.npquNnysdwGI"
1518271891832 Marionette INFO Enabled via --marionette
2018-02-10 19:41:32.786 plugin-container[53155:969741] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0xab3f, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271893243 Marionette INFO Listening on port 53150
1518271893342 Marionette WARN TLS certificate errors will be ignored for this session
Feb 10, 2018 7:41:33 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1518271893499 geckodriver INFO geckodriver 0.19.1
1518271893590 geckodriver INFO Listening on 127.0.0.1:48408
2018-02-10 19:41:33.681 plugin-container[53156:969822] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x7c37, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271893810 mozrunner::runner INFO Running command: "/Applications/Firefox.app/Contents/MacOS/firefox-bin" "-marionette" "-profile" "/var/folders/mj/81r6v7nn5lqgqgtfl18spfpw0000gn/T/rust_mozprofile.65SomKttNwQP"
1518271894377 Marionette INFO Enabled via --marionette
2018-02-10 19:41:35.326 plugin-container[53159:969958] *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x1523b, name = 'com.apple.tsm.portname'
See /usr/include/servers/bootstrap_defs.h for the error codes.
1518271895785 Marionette INFO Listening on port 53451
1518271895824 Marionette WARN TLS certificate errors will be ignored for this session
Feb 10, 2018 7:41:35 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
[GFX1-]: Receive IPC close with reason=AbnormalShutdown
1518271896172 addons.xpi WARN Exception running bootstrap method shutdown on activity-stream#mozilla.org: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIObserverService.removeObserver]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: resource://activity-stream/lib/SnippetsFeed.jsm :: uninit :: line 125" data: no] Stack trace: uninit()#resource://activity-stream/lib/SnippetsFeed.jsm:125 < onAction()#resource://activity-stream/lib/SnippetsFeed.jsm:141 < _middleware/</<()#resource://activity-stream/lib/Store.jsm:51 < Store/this[method]()#resource://activity-stream/lib/Store.jsm:30 < uninit()#resource://activity-stream/lib/Store.jsm:153 < uninit()#resource://activity-stream/lib/ActivityStream.jsm:278 < uninit()#resource://gre/modules/addons/XPIProvider.jsm -> jar:file:///Applications/Firefox.app/Contents/Resources/browser/features/activity-stream#mozilla.org.xpi!/bootstrap.js:80 < shutdown()#resource://gre/modules/addons/XPIProvider.jsm -> jar:file:///Applications/Firefox.app/Contents/Resources/browser/features/activity-stream#mozilla.org.xpi!/bootstrap.js:196 < callBootstrapMethod()#resource://gre/modules/addons/XPIProvider.jsm:4406 < observe()#resource://gre/modules/addons/XPIProvider.jsm:2270 < GeckoDriver.prototype.quit()#driver.js:3381 < despatch()#server.js:560 < execute()#server.js:534 < onPacket/<()#server.js:509 < onPacket()#server.js:508 < _onJSONObjectReady/<()#transport.js:500
===============================================
Default Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================
Process finished with exit code 0

java.util.logging doesn't working properly "bug or feature"

Why logging "1 MAIN INFO" doesn't working when I disabled all logging from core libraries by .level=OFF. But for my package I am enabled all logging. Why it works only after I have second logger is instantiated by string?
LibClass libClass = new LibClass();
package com.mycompany;
public class Main {
private final static Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("log.prop")
LogManager.getLogManager().readConfiguration(fis);
logger.info("1 MAIN INFO");
LibClass libClass = new LibClass();
libClass.doWork();
logger.info("3 MAIN INFO");
}
}
package com.mycompany;
public class LibClass {
private final static Logger logger = Logger.getLogger(LibClass.class.getName());
public void doWork() {
System.out.println("doWork");
logger.info("2 doWork INFO");
}}
handlers= java.util.logging.ConsoleHandler
.level = OFF
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
com.mycompany.level = ALL
Output
doWork
[Пт июл 01 22:37:29 EEST 2016] INFO: com.mycompany.LibClass doWork - 2 doWork INFO
[Пт июл 01 22:37:29 EEST 2016] INFO: com.mycompany.Main main - 3 MAIN INFO
Thank you all. Thank Andreas for correct answer.
The Problem was here: Logger.getLogger(Main.class.getName()) executes when class is loading before Logger loads configuration LogManager.getLogManager().readConfiguration(fis).
Here is solution
package com.mycompany;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("log.prop");
LogManager.getLogManager().readConfiguration(fis);
MainClass mainClass = new MainClass();
}
}
package com.mycompany;
public class MainClass {
private final static Logger logger = Logger.getLogger(MainClass.class.getName());
public MainClass() throws IOException {
logger.info("1 MAIN INFO");
LibClass libClass = new LibClass();
libClass.doWork();
URL url = new URL("http://google.ru");//I don't want see
url.openStream(); // fine, finest logs from this code
logger.info("3 MAIN INFO");
}
}
package com.mycompany;
public class LibClass {
private final static Logger logger = Logger.getLogger(LibClass.class.getName());
public void doWork() {
System.out.println("doWork");
logger.info("2 doWork INFO");
}
}
handlers= java.util.logging.ConsoleHandler
.level = OFF
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
com.mycompany.level = ALL
Output
[Сб июл 02 04:32:11 EEST 2016] INFO: com.mycompany.MainClass <init> - 1 MAIN INFO
doWork
[Сб июл 02 04:32:11 EEST 2016] INFO: com.mycompany.LibClass doWork - 2 doWork INFO
[Сб июл 02 04:32:12 EEST 2016] INFO: com.mycompany.MainClass <init> - 3 MAIN INFO

Arquillian does not find classes

I set up a arquillian test to test my EJB and JPA layer:
#RunWith(Arquillian.class)
public class ClientTest {
#EJB
private ClientService client;
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(Client.class.getPackage())
.addPackage(ClientService.class.getPackage())
.addPackage(Client_.class.getPackage())
.addAsLibrary(new File("C:\\...\\ojdbc6.jar"))
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource("test-persistence.xml", "persistence.xml");
}
#Test
public void testCreate() {
Assert.assertNotNull("Client not null", client);
Client c = client.getClientById(1L);
assertNotNull(c);
}
}
Now, the log is telling me that the classes could not be found:
Okt 12, 2015 9:43:17 AM org.glassfish.weld.BeanDeploymentArchiveImpl handleEntry
WARNUNG: Error while trying to load Bean Class WEB-INF.classes.com.xyz.aip.common.AbstractEntity : java.lang.ClassNotFoundException: WEB-INF.classes.com.xyz.aip.common.AbstractEntity
Okt 12, 2015 9:43:17 AM org.glassfish.weld.BeanDeploymentArchiveImpl handleEntry
WARNUNG: Error while trying to load Bean Class WEB-INF.classes.com.xyz.aip.common.AbstractEntity_ : java.lang.ClassNotFoundException: WEB-INF.classes.com.xyz.aip.common.AbstractEntity_
I looked into the generated WAR-File and there is a
- META-INF
- WEB-INF
- classes
- com
- xyz
- aip
- common
- AbstractEntity.class
Any ideas?
what I would try is:
.addPackage(Client.class.getPackage().getName())

Java rest server : make a unit test

I try to make a unit test for a standalone rest server. If I run the rest server it work nice. But I don't know how to make the UnitTest running.
My main class :
public class Main {
private static final int DEFAULT_PORT = 8080;
private final int serverPort;
private final Server restServer;
public Main(final int serverPort) throws Exception {
this.serverPort = serverPort;
restServer = configureServer();
restServer.start();
restServer.join();
}
public void close() throws Exception {
if (restServer != null) {
restServer.stop();
}
}
private Server configureServer() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages(Main.class.getPackage().getName());
resourceConfig.register(JacksonFeature.class);
ServletContainer servletContainer = new ServletContainer(resourceConfig);
ServletHolder sh = new ServletHolder(servletContainer);
Server server = new Server(serverPort);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(sh, "/*");
server.setHandler(context);
return server;
}
public static void main(String[] args) throws Exception {
int serverPort = DEFAULT_PORT;
if (args.length >= 1) {
try {
serverPort = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
new Main(serverPort);
}
The resource class :
#Path("builder")
public class ReportBuilderResource {
#POST
#Path("/build")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({MediaType.TEXT_PLAIN})
public String makeReport(final ReportDescription reportDescription) {
return reportDescription.getName();
}
}
My Unit test class :
public class ReportBuilderResourceTest extends JerseyTest {
#Override
public AppDescriptor configure() {
return new WebAppDescriptor.Builder()
.initParam(WebComponent.RESOURCE_CONFIG_CLASS, ClassNamesResourceConfig.class.getName())
.initParam(ClassNamesResourceConfig.PROPERTY_CLASSNAMES, ReportBuilderResource.class.getName())
.build();
}
#Test
public void testBuildReport() throws Exception {
System.out.println("Test Build Report");
ReportDescription reportDescription = new ReportDescription();
JSONObject jsonObject = new JSONObject(reportDescription);
resource().path("builder/").post(jsonObject.toString());
}
And the output log :
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer <init>
INFO: Creating low level InMemory test container configured at the base URI http://localhost:9998/
Running com.fdilogbox.report.serveur.ReportBuilderResourceTest
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer start
INFO: Starting low level InMemory test container
juil. 31, 2015 9:48:53 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
Test Build Report
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter filter
INFO: 1 * Server in-bound request
1 > POST http://localhost:9998/builder/
1 > Content-Type: text/plain
1 >
{"name":null,"report":null}
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 405
1 < Allow: OPTIONS
1 <
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.497 sec <<< FAILURE! - in com.fdilogbox.report.serveur.ReportBuilderResourceTest
testBuildReport(com.fdilogbox.report.serveur.ReportBuilderResourceTest) Time elapsed: 0.496 sec <<< ERROR!
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 405
at com.sun.jersey.api.client.WebResource.voidHandle(WebResource.java:709)
at com.sun.jersey.api.client.WebResource.post(WebResource.java:238)
at com.fdilogbox.report.serveur.ReportBuilderResourceTest.testBuildReport(ReportBuilderResourceTest.java:47)
I think the server is not "running" for the test. How can'I do this?
Your resource listens to "/builder", but the only method inside listens to "/builder/build". Since there is no method listening to #post and "/builder" you get a Http 405 - Method not allowed.
You can either remove #Path("/build") from the "makeReport" method, or change resource().path("builder/build")... in your test.
Btw:
You only need to add one of these contatiner adapters and this snippet to run a unit tests with Jersey 2:
public class ReportBuilderResourceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(ReportBuilderResource.class);
}
...
}

Categories

Resources