javax.ws.rs.NotFoundException: HTTP 404 не найден для инфраструктуры тестирования junit + jersy - PullRequest
0 голосов
/ 14 мая 2018
Controller java file (LogControllerLua.java):
-----------
@Api(value = "/")
@Path("/")
public class LogControllerLua

{

    private Logger logger = LoggerFactory.getLogger(LogControllerLua.class);
    private LoggerServiceLua loggerServiceLua = new LoggerServiceLua();

    @GET
    @Path("/getLogServerInfo")
    public String getLogServerInfo(@Context HttpHeaders httpheaders) throws Exception {
//..code }



service class ::(LoggerServiceLua.java) ::
------------------------------
package com.koopid.apex.API.rest.service;

public class LoggerServiceLua {

public String getLogServerInfo() throws Exception { //..code }


web.xml ::
------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

 <!--  <web-app> -->
  <display-name>jerseysample</display-name>
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>
            com.adaequare.resource.config.JerseyResourceInitializer
        </param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

Если я не использую JerseyConfig.class в configure (), он говорит, что файл для инъекций не найден.

Junit test case :logControllerLuaTest.java
----------------------------

package Tests;


import static org.junit.Assert.*;
import Tests.serviceinfo2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import com.koopid.apex.API.rest.controller.LogControllerLua;

//import static com.jayway.restassured.RestAssured.expect;
//import static com.jayway.restassured.RestAssured.get;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import com.google.gson.Gson;
import com.koopid.apex.API.rest.service.LoggerServiceLua;




import static org.mockito.Mockito.*;


import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import javax.ws.rs.core.Application;

import java.util.Arrays;
import java.util.List;


public class LogControllerLuaTest extends JerseyTest {


    @Mock
    private LoggerServiceLua loggerServiceLua;

    @InjectMocks
    private LogControllerLua logControllerLua;

    @Override
    protected Application configure() {
        return new ResourceConfig(JerseyConfig.class);
    }



    @Before
    public void init(){

        System.out.println("in here 1");
        MockitoAnnotations.initMocks(this);     
        System.out.println("in here 1 end");
        }


        @Test
        public void testgetLogServerInfo() throws Exception
        {
            System.out.println("executing in test");
            String serviceinfo = new String("some data");

            //serviceinfo2 serviceinfo2 = mock(serviceinfo2.class);
            when(loggerServiceLua.getLogServerInfo()).thenReturn(serviceinfo);
            System.out.println("in test 1 end");
            String response = target("/API/rest/getLogServerInfo").request().get(String.class);
            System.out.println("in test 2 end");
            Assert.assertTrue(serviceinfo.equals(response));
            System.out.println("in test 3 end");
            System.out.println(serviceinfo);

        }
    }



JersyConfig.java :
--------------------
package Tests;


import org.glassfish.jersey.server.ResourceConfig;

import com.koopid.apex.API.rest.controller.*;
import com.koopid.apex.API.rest.service.LoggerServiceLua;


public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(LogControllerLua.class);
        register(LoggerServiceLua.class);
    }

}

Я пишу юнит-тестовый пример, чтобы проверить остальные API и нажать на запрос get, я занимаюсь издевательствами


javax.ws.rs.NotFoundException: HTTP 404 Not Found
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1008)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:816)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at Tests.LogControllerLuaTest.testgetLogServerInfo(LogControllerLuaTest.java:92)
    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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    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:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Пожалуйста, помогите мне решить эту проблему? Заранее спасибо. Пожалуйста, прокомментируйте, если требуется какая-либо другая информация. Также, кто-нибудь может объяснить, почему нам нужно переопределить метод configure ()?

1 Ответ

0 голосов
/ 24 мая 2018

Устранена вышеуказанная проблема путем внесения 1 изменения .. 1. путем инициализации mockitoAnnotation в защищенном приложении configure () {MockitoAnnotations.initMocks (this);

и регистрации контроллеров и классов служб 1. @Override защищенного приложения настроить() {

    MockitoAnnotations.initMocks(this);
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(MultiPartFeature.class);
    resourceConfig.register(DBRestClient.class);
    resourceConfig.register(LoggerServiceLua.class);
    resourceConfig.register(LogControllerLua.class);

return resourceConfig;}

...