RestAssuredMockMvc - Autowire存储库为null

时间:2014-10-26 16:06:16

标签: junit rest-assured spring-mvc-test mockmvc

我正在使用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


有人可以指导我吗?我究竟做错了什么?为什么我的存储库为空?
当我使用Curl命令和测试时,端点确实有效,但是,我无法为单元测试编写junit,请帮忙

1 个答案:

答案 0 :(得分:1)

我遇到了完全相同的问题。 当我运行该项目时,它工作正常。 但是当我测试控制器时,一些自动装配的变量变为空,这使测试失败。

在我的代码中,我有一个userWebController执行“注册”工作。还有另一个类CustomedUserDetailsS​​ervice,它与JdbcTemplate对象一起使用,以将新用户添加到数据库。 JdbcTemplate对象使用bean自动装配。当我测试控制器时,这个JdbcTemplate对象为null,这意味着它没有注入成功。

我尝试了以下方法(jdbc bean在类OnlineDBConfig中定义),但不起作用:

@ContextConfiguration( classes = {OnlineDBConfig.class})

我用以下解决方案解决了我的问题: 1,直接将failed_autowired对象移动到Test类(StandaloneUserControllerTest) 2,将对象传递给使用它的控制器类。

以下是最终的测试课程:

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") ; } }

这很糟糕,但它确实有效。 希望能有更好的解决方案。