0

RestAssuredMockMvc を使用してレスト コントローラーをテストしています。これは私のコードです

/*Repository*/
package com.rest.api.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
import com.mysema.query.types.Predicate;

@Repository
public interface ClientRepository extends JpaRepository<Client, Long>,
    QueryDslPredicateExecutor<Client> {

    Client findByClientId(Integer clientId);
    Client findOne(Predicate predicate);
    List<Client> findAll(Predicate predicate);
}

/*Services to be offered*/   
package com.rest.api.service;

import java.util.List;
import com.mysema.query.types.Predicate;
import com.rest.api.model.Client;
import com.rest.api.repository.ClientRepository;

public interface ClientService {
    Boolean saveEnterprise(Client client, ClientRepository clientRepository);
}

/*Implementation*/
package com.rest.api.service.implementations;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.mysema.query.types.Predicate;
import com.rest.api.logging.LoggingManager;
import com.rest.api.model.Client;
import com.rest.api.repository.ClientRepository;
import com.rest.api.service.ClientService;

@Service
public class ClientImpl implements ClientService {

    @Override
    public Boolean saveEnterprise(Client client,
            ClientRepository clientRepository) {
        try {
            LoggingManager.info(getClass(), "CLIENT="+client);
            if(clientRepository == null){
                LoggingManager.info(getClass(), "CLIENT REPO NULL");
            }
            if (client != null) {
                clientRepository.save(client);
            }
        } catch (Exception e) {
            LoggingManager.debug(getClass(),
                        "Error while saving assistance details");
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

/* CONTROLLER*/
@Controller
public class ClientController {
    @Autowired
    ClientRepository clientRepository;

    @Inject
        public void setRepository(ClientRepository clientRepository) {
            this.clientRepository = clientRepository;
    }

    // Get Service Handle - A Singleton 
    private ClientService enterpriseServicehandle = EnterpriseClient
        .getInstance().getEnterpriseService();

    @RequestMapping(value = ApiEndpointConstants.CREATE_NEW_CLIENT, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, headers = "content-type=application/x-www-form-urlencoded")
    @ResponseBody
    public EnterpriseResponse saveEnterprise(@RequestBody Client client) {

        EnterpriseResponse enterpriseResponse = new EnterpriseResponse();
        enterpriseServicehandle.saveEnterprise(client, clientRepository);

        enterpriseResponse.setEnterprise(client);
        enterpriseResponse
                .setResponseCode(212);
        enterpriseResponse
                .setResponseMessage("Client creation Successful");

        return enterpriseResponse;
    }
}

/* Test Class*/
import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.module.mockmvc.response.MockMvcResponse;
import com.rest.api.model.util.ResponseCodeConstants;
import com.rest.api.repository.AccesscodeRepository;
import com.rest.api.repository.ClientRepository;

public class ClientControllerTest {

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private AccesscodeRepository accesscodeRepository;

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public final void testFunctionality() {

         String clientJson = "{\"name\":\"Client1\",\"clientId\":1000,\"fromEmailAddress\":\"goutham@atreya.in\"}";

         MockMvcResponse clientCreationResponse = given()
             .standaloneSetup(new ClientController())
                    .body(clientJson)
                 .contentType(ContentType.JSON)
             .when()
                 .post("api/client/save")
             .then()
                 .statusCode(200)
                .extract().response();

         System.out.println(clientCreationResponse.asString());
         Integer clientResponseCode = clientCreationResponse.path("responseCode");
         String clientResponseMessage = clientCreationResponse.path("responseMessage");
         System.out.println("INT:" + clientResponseCode);
         Assert.assertEquals(clientResponseCode, 211);
         Assert.assertEquals(clientResponseMessage,"Client Creation Successful");       
    }
}


テスト ケースを実行すると、このエラーが発生します (注: clientRepository は NULLであり、NPE をスローしますが、最後の行は、クライアントが正常に作成されたことを示しています。

    Oct 26, 2014 8:50:16 PM com.rest.api.logging.LoggingManager log
INFO: CLIENT={"clientId":1000,"name":"Client1","fromEmailAddress":"goutham@atreya.in","insertionTime":"Oct 26, 2014 8:50:16 PM"}
 Oct 26, 2014 8:50:16 PM com.rest.api.logging.LoggingManager log
INFO: CLIENT REPO NULL
java.lang.NullPointerException
    at com.rest.api.service.implementations.ClientImpl.saveEnterprise(ClientImpl.java:46)
    at com.rest.api.controller.ClientController.saveEnterprise(ClientController.java:99)
    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:483)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:170)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:137)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:145)
    at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.performRequest(MockMvcRequestSenderImpl.java:127)
    at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.sendRequest(MockMvcRequestSenderImpl.java:327)
    at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.post(MockMvcRequestSenderImpl.java:407)
    at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.post(MockMvcRequestSenderImpl.java:51)
    at com.rest.api.controller.ClientControllerTest.testFunctionality(ClientControllerTest.java:107)
    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:483)
    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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    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: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)
{"responseMessage":"Client creation Successful","responseCode":212,"enterprise":{"id":null,"clientId":1000,"name":"-Client1","fromEmailAddress":"trace-support@.net","insertionTime":1414336816443}}
INT:212


誰でも私を案内してもらえますか?私は何を間違っていますか?リポジトリが null になっているのはなぜですか?
Curl コマンドとテストを使用すると、エンドポイントは機能しますが、単体テスト用の junit を作成できません。助けてください

4

1 に答える 1

1

I meet exactly same problem. When I run the project, it works fine. But when I test controller some autowired variable becomes null, which failed the test.

In my code, I have a userWebController which does "signup" job. There is another class CustomedUserDetailsService which work with a JdbcTemplate object to add a new user to database. the JdbcTemplate object is autowired with a bean. When I test the controller, this JdbcTemplate object is null which means it is not injected successful.

I tried this following method(the jdbc bean is defined in class OnlineDBConfig), but does not work:

@ContextConfiguration( classes = {OnlineDBConfig.class})

I solve my problem with following solution: 1, move the failed_autowired object to the Test class (StandaloneUserControllerTest) directly.
2, pass the object to the controller class which use it.

Following is the final test class:

public class StandaloneUserControllerTest extends AbstractSpringJunit4Tests { @Autowired @Qualifier("jdbcOnline") protected JdbcTemplate jdbc;
@Before public void before(){ RestAssuredMockMvc.standaloneSetup(new UserWebController(jdbc) ) ; if( jdbc == null ) fail("autowired failed again") ; } }

It is terrible, but it works. Hope there will be better solution.

于 2015-08-22T03:40:16.223 に答える