为什么autowired变量为null?

时间:2015-09-07 05:17:17

标签: java spring junit

我正在使用spring framework4。我尝试开发一些服务器程序。所以,我想使用JUnit测试控制器类。但是,当我运行测试类时,会发生NullPionterException。我在这个网站上搜索了几个答案。但我无法修复我的代码。帮助我。

这是我的Controller类。

String

这是我的考试班。

package kr.ac.jbnu.sql.soremore.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.IRDMLConverter;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.IRDMLRDFMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RDMLRDFException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import kr.ac.jbnu.sql.soremore.service.rdf.RDFConverter;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;

// reference
// http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
@Controller
public class SoremoreController {

    private static final int buffer_size = 1024;
    static Logger logger = Logger.getLogger(SoremoreController.class.getName());
    private static String fileName = "";

    @Autowired
    private ApplicationContext appContext  = null;

    @Autowired
    private IRDMLConverter rdmlConverter  = null;

    @Autowired
    private IRDMLRDFMgmt rdmlRDFMgmt  = null;

    @Autowired
    private IRDMLDBMgmt rdmlDBMgmt = null;

    @Autowired
    private RDFConverter rdfConverter  = null;

    private List<String> remainedBaseWorkProductItemIds;
    private List<String> remainedInputedWorkProductItemIds;
    private List<String> sameIds;

//  @RequestMapping(value = "/storeArtifacts", method = { RequestMethod.GET })
//  @ResponseBody
//  String storeArtifacts(HttpServletRequest request,
//          HttpServletResponse response) {
//
//      String rootPath = System.getProperty("catalina.home");
//      File dir = new File(rootPath + File.separator + "tmpFiles");
//      boolean issuccesful = false;
//      String hwpmlPath = dir.getAbsolutePath() + File.separator + fileName
//              + ".xml";
//
//      return storeRDML(hwpmlPath);
//  }

    public String storeRDML(RDML rdml) {
//  public String storeRDML(String hwpmlPath) {
        boolean issuccesful;
//      System.out.println(hwpmlPath);
//      RDML rdml = null;
        // 1. request to convert XML to RD-ML
//      try {
//          rdml = rdmlConverter.convertHWPMLToRDML(hwpmlPath);
//      } catch (RDMLConversionException e) {
//          e.printStackTrace();
//          return "you failed to convert hwpml to rdml";
//      }

        // 2. request to store RD-ML to Apache Jena
        try {
            issuccesful = storeRDML0(rdml);
        } catch (RDMLRDFException e) {
            e.printStackTrace();
            return "you failed to store rdml";
        } catch (RDMLDBException e) {
            e.printStackTrace();
            return "you failed to store rdml";
        } catch (RevisionControlException e) {
            e.printStackTrace();
            return "you failed to store rdml";
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "you failed to store rdml";
        }

        return "you successfully store rdml";
    }

    // forward request to file converter
    @RequestMapping("/convertHWP")
    public ModelAndView convertHWP() {
        return new ModelAndView("convertHWP");
    }

    @RequestMapping(value = "/queryArtifacts", method = { RequestMethod.GET })
    @ResponseBody
    String queryArtifacts(
            @RequestParam(value = "keyword", required = false) String keyword,
            HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException, Exception {
        logger.info("Query Artifacts:" + keyword);

        StringBuilder sb = new StringBuilder();

        try {
            RDML[] results = rdmlRDFMgmt.query(keyword);
            for (RDML rdml : results) {
                sb.append(rdml.getIdFromDocument(rdml.getRdmlAsDocument()))
                        .append(",");
                // retrive rdml documents from Jackrabbit
                // RDML rdmlFromJackRabbit =
                // rdmlDBMgmt.getRDML(rdml.getRdmlID());
                // sb.append(rdmlFromJackRabbit.getRdmlAsString(rdml.getRdmlAsDocument()));
            }
        } catch (RDMLRDFException e1) {
            e1.printStackTrace();
        }

        System.out.println("keyword :" + keyword);

        return "result for " + keyword + ":"
                + sb.toString().substring(0, sb.toString().length() - 1);
    }

    // private String convertArtifactIntoXML(HttpServletRequest request,
    // HttpServletResponse response, String path) {
    // String fileExtension = path.substring(path.lastIndexOf(".")+1);
    //
    // logger.info("convertArtifactIntoXML:"+ path);
    //
    // if( fileExtension.equals(ArtifactTypes.hwp))
    // {
    // // TODO forward request to hwp to xml converter
    // }
    // else
    // {
    // // TODO for processing docx, pptx, xlsx
    // }
    // return "";
    // }

    /**
     * Upload single file using Spring Controller
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public @ResponseBody String uploadFileHandler(
            @RequestParam("name") String name,
            @RequestParam("file") MultipartFile file) {
        File serverFile = null;
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                serverFile = new File(dir.getAbsolutePath() + File.separator
                        + name + ".hwp");
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());
                fileName = name;
                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }

    /**
     * Upload multiple file using Spring Controller
     */
    @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
    public @ResponseBody String uploadMultipleFileHandler(
            @RequestParam("name") String[] names,
            @RequestParam("file") MultipartFile[] files) {

        if (files.length != names.length)
            return "Mandatory information missing";

        String message = "";
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String name = names[i];
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());
                message = message + "You successfully uploaded file=" + name
                        + "<br />";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        }
        return message;
    }

    @RequestMapping("/upload")
    public ModelAndView upload() {
        return new ModelAndView("upload");
    }

    @RequestMapping("/uploadMultifiles")
    public ModelAndView uploadMultipleFile() {
        return new ModelAndView("uploadMultiple");
    }

    @RequestMapping("/queryAndResult")
    public ModelAndView queryAndResult() {
        return new ModelAndView("queryAndResult");
    }

    @RequestMapping("/query")
    public ModelAndView query() {
        return new ModelAndView("query");
    }

    // ////////////////////////////////////
    // String ������ �޽����� ����
    @RequestMapping("/welcome")
    public ModelAndView helloWorld() {
        String message = "<br><div align='center'>"
                + "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is comming from CrunchifyHelloWorld.java **********<br><br>";
        return new ModelAndView("welcome", "message", message);
    }

    public void storeRDMLWithTraceability(RDML rdml, String previousRDMLId,
            TraceabilityTypes satisfy) throws IOException {
        String rdURI = rdfConverter.rdURI;
        String rdmlID = rdml.getRdmlAsDocument().getRootElement()
                .getAttribute("id").getValue();

        Model rdfModel = rdfConverter.createRDFmodelfromRD(rdml
                .getRdmlAsDocument());
        Property traceType = rdfModel.createProperty(rdURI + rdmlID,
                satisfy.satisfy.toString());
        Resource rdfWorkProduct = rdfModel.getResource(rdURI + rdmlID);
        rdfWorkProduct.addProperty(traceType, previousRDMLId);

    }

    public String deleteRDMLTraceability(String previousRDMLId1,
            String previousRDMLId2) {

        return null;
    }

    public String updateRDMLTraceability(String previousRDMLId1,
            String previousRDMLId2, TraceabilityTypes satisfy) {
        return null;
    }

    public ArrayList<RDML> searchRDML(String rdmlKeyWord) {
        return null;
    }

    public RDML getRDML(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    public ArrayList<String> getParentIDs(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    public ArrayList<String> getChildIDs(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    public ArrayList<Traceability> getDirectLinkedTraceability(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    private boolean storeRDML0(RDML rdml) throws RevisionControlException,
            Exception {
        Node baseWP = null;
        Node inputedWP = null;
        remainedBaseWorkProductItemIds = new LinkedList<String>();
        remainedInputedWorkProductItemIds = new LinkedList<String>();
        sameIds = new LinkedList<String>();
        Document rdmlAsDocument = rdml.getRdmlAsDocument();
        String rdmlId = rdml.getIdFromDocument(rdmlAsDocument);

        RDML curRdml = rdmlDBMgmt.retrieveRecentRDML(rdmlId);
        if (curRdml != null && curRdml.getRdmlAsNode() != null)
            baseWP = curRdml.getRdmlAsNode();
        else
            baseWP = null;
        // version 정보 갱신
        inputedWP = rdmlDBMgmt.convertDocToNode(rdmlAsDocument, rdmlId);
        if (baseWP == null) {
            rdmlDBMgmt.initialVersioning(inputedWP);
            // rdf 정보 추가삽입 요망
        } else {
            remainedBaseWorkProductItemIds = rdmlDBMgmt
                    .setAllBaseWorkProductItemId(baseWP);
            remainedInputedWorkProductItemIds = rdmlDBMgmt
                    .setAllInputWorkProductItemId(inputedWP);
            getSameIds();
            Iterator<String> changeNodes = sameIds.iterator();
            while (changeNodes.hasNext()) {
                String chageNodeId = changeNodes.next();
                rdmlDBMgmt.versionUpNode(
                        rdmlDBMgmt.getNode(baseWP, chageNodeId),
                        rdmlDBMgmt.getNode(inputedWP, chageNodeId));
            }
            rdmlDBMgmt.addNodes(baseWP, inputedWP,
                    remainedInputedWorkProductItemIds, "WorkProductItem");
            rdmlDBMgmt.deleteNodes(baseWP, remainedBaseWorkProductItemIds,
                    "WorkProductItem");
        }
        return true;
    }

    private void getSameIds() {
        Iterator<String> baseIter = remainedBaseWorkProductItemIds.iterator();
        while (baseIter.hasNext()) {
            String baseId = baseIter.next();
            Iterator<String> inputedIter = remainedInputedWorkProductItemIds
                    .iterator();
            for (; inputedIter.hasNext();) {
                String inputedId = inputedIter.next();
                if (baseId.equals(inputedId)) {
                    sameIds.add(baseId);
                    remainedBaseWorkProductItemIds.remove(baseId);
                    remainedInputedWorkProductItemIds.remove(inputedId);
                }
            }
        }
    }
}

这是我的spring config xml文件。

package kr.ac.jbnu.sql.soremore.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = { "classpath:/soremore-servlet.xml" })
//@ContextConfiguration(locations = { "/soremore-servlet.xml" })
public class SoremoreControllerTest {

    @Autowired
    SoremoreController soremoreController = null;

    @Test
    public void storeRDML() {
//      String[] hwpmlPaths = { "resource/sample_rdml/예제 1.xml",
//              "resource/sample_rdml/예제 2.xml",
//              "resource/sample_rdml/예제 3.xml",
//              "resource/sample_rdml/예제 4.xml",
//              "resource/sample_rdml/예제 5.xml",
//              "resource/sample_rdml/예제 6.xml",
//              "resource/sample_rdml/예제 7.xml",
//              "resource/sample_rdml/예제 8.xml",
//              "resource/sample_rdml/예제 9.xml",
//              "resource/sample_rdml/예제 10.xml" };
//
//      for (String hwpmlPath : hwpmlPaths) {
//          soremoreController.storeRDML(hwpmlPath);
//      }

        ArrayList<RDML> rdmls = loadTestRDML();
        boolean isSuccessful = false;
        for (RDML rdml : rdmls) {
            try {
                soremoreController.storeRDML(rdml);
                System.out.println();
                isSuccessful = true;
            } catch (Exception e) {
                e.printStackTrace();
                isSuccessful = false;
            }
        }
        Assert.assertTrue(isSuccessful);
    }

    @Test
    public void storeRDMLWithTraceability() throws IOException {
        List<RDML>rdmls = null ;
        String previousRDMLId = "xxx";

        for (RDML rdml : rdmls) {
            soremoreController.storeRDMLWithTraceability(rdml,
                    previousRDMLId, TraceabilityTypes.satisfy);
        }
    }

    @Test
    public void updateRDMLWithTraceability() {
        String previousRDMLId1 = "xxx";
        String previousRDMLId2 = "xxx";

        String updatedTraceability = soremoreController.updateRDMLTraceability(
                previousRDMLId1, previousRDMLId2, TraceabilityTypes.satisfy);
    }

    @Test
    public void deleteRDMLWithTraceability() {
        String previousRDMLId1 = "xxx";
        String previousRDMLId2 = "xxx";

        String removedTraceability = soremoreController.deleteRDMLTraceability(
                previousRDMLId1, previousRDMLId2);
    }

    @Test
    public void searchRDML() {
        String rdmlKeyWord = "abc";

        ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
        for (RDML rdml : rdmls) {
            System.out.println(rdml);
        }
    }

    @Test
    public void searchRDML0() {
        String rdmlKeyWord = "def";

        ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
        for (RDML rdml : rdmls) {
            System.out.println(rdml);
        }
    }

    @Test
    public void searchRDML1() {
        String rdmlKeyWord = "2차년도계획서";

        ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
        for (RDML rdml : rdmls) {
            System.out.println(rdml);
        }
    }

    @Test
    public void getRDML() {
        String rdmlID = "abc";
        RDML rdml = soremoreController.getRDML(rdmlID);
    }

    @Test
    public void getParentIDs() {
        String rdmlID = "abcd";

        ArrayList<String> parentIDs = soremoreController.getParentIDs(rdmlID);

        for (String string : parentIDs) {

        }
    }

    @Test
    public void getChildIDs() {
        String rdmlID = "abcd";

        ArrayList<String> childIDs = soremoreController.getChildIDs(rdmlID);

        for (String string : childIDs) {

        }
    }

    public void getDirectLinkedTraceability() {
        String rdmlID = "abcd";
        ArrayList<Traceability> linkedTraceabilities = soremoreController
                .getDirectLinkedTraceability(rdmlID);

        for (Traceability traceability : linkedTraceabilities) {

        }

    }

    public ArrayList<RDML> loadTestRDML() {
        ArrayList<RDML> rdmls = new ArrayList<RDML>();
        String xmlSource = "resource/sample_rdml";

        File sourceDir = new File(xmlSource);
        File[] sourceFiles = sourceDir.listFiles();
        for (File file : sourceFiles) {
            RDML rdml = new RDML();
            rdml.setRdmlAsDocument(createDocument(file));
            rdmls.add(rdml);
        }

        return rdmls;
    }

    private Document createDocument(File rdmlPathAsFile) {
        SAXBuilder jdomBuilder = new SAXBuilder();
        Document jdomDocument = null;
        try {
            jdomDocument = jdomBuilder.build(rdmlPathAsFile);
        } catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jdomDocument;
    }
}

1 个答案:

答案 0 :(得分:0)

测试中的Autowired变量将为null,除非Spring在运行测试时自动将其变为自动装配。您的注释行@RunWithSpringJUnit4ClassRunner.class)和@ContextConfiguration行可以实现此目的。