Spring Boot MVC(Maven)的Junit测试用例

时间:2017-09-14 14:27:18

标签: maven spring-mvc spring-boot

所以请帮我写一下这个代码的junit测试用例,因为我是spring boot maven项目的新手,我没有得到如何为这段代码编写测试用例。 粘贴在下面的源代码,    我有一个示例Spring Boot应用程序,其中包含以下内容

1。控制器

   package com.learn.spring;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    import com.learn.spring.model.Chipset;
    import com.learn.spring.model.Stbm;
    import com.learn.spring.service.ChipsetService;
    import com.learn.spring.service.StbmService;

    @Controller
    public class ChipsetController {

        private ChipsetService chipsetService;

        private StbmService stbmService;

        @Autowired(required=true)
        @Qualifier(value="stbmService")
        public void setStbmService(StbmService ss){
            this.stbmService = ss;
        }

        @Autowired(required=true)
        @Qualifier(value="chipsetService")
        public void setChipsetService(ChipsetService cs){
            this.chipsetService = cs;
        }

        @RequestMapping(value = "/chipset", method = RequestMethod.GET)
        public String listChipset(Model model) {
            model.addAttribute("chipset", new Chipset());
            model.addAttribute("listChipset", this.chipsetService.listChipset());
            List<String> stbNameList=new ArrayList<String>();
            /*stbNameList.add("a");
            stbNameList.add("b");
            stbNameList.add("c");
            model.addAttribute("stbNameList",stbNameList);*/

            List<Stbm> stbmList= this.stbmService.listStbm();
                Iterator<Stbm> itr=stbmList.iterator();
                while (itr.hasNext()) 
                {
                Stbm st =  itr.next();
                stbNameList.add(st.toString());
                }

            model.addAttribute("stbNameList", this.stbmService.listStbm());
            model.addAttribute("stbNameList", stbNameList);

            return "chipset";
        }

        //For add  
        @RequestMapping(value= "/chipset/add", method = RequestMethod.POST)
        public String addChipSet(@ModelAttribute("chipset") Chipset c){
            this.chipsetService.addChipset(c);
            return "redirect:/chipset";

        }
        @RequestMapping(value = "/stbm", method = RequestMethod.GET)
        public String listStbm(Model model) {
            model.addAttribute("stbm", new Stbm());


            model.addAttribute("stbmList", this.stbmService.listStbm());

            return "stbm";
        }

        //For add  
        @RequestMapping(value= "/stbm/add", method = RequestMethod.POST)
        public String addStbm(@ModelAttribute("stbm") Stbm s){
            this.stbmService.addStbm(s);
            return "redirect:/stbm";

        }


    }

2.型号

package com.learn.spring.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="CHIPSET")
public class Chipset {

    @Id
    @Column(name="c_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int chipSetModelId;

    @Column(name="c_Name")
    private String chipSetName;

    @Column(name="STBM_name")
    private String name_STBM;

    @Column(name="c_Ext")
    private String chipsetExtension;

    public int getChipSetModelId() {
        return chipSetModelId;
    }
    public void setChipSetModelId(int chipSetModelId) {
        this.chipSetModelId = chipSetModelId;
    }
    public String getChipSetName() {
        return chipSetName;
    }
    public void setChipSetName(String chipSetName) {
        this.chipSetName = chipSetName;
    }
    public String getName_STBM() {
        return name_STBM;
    }
    public void setName_STBM(String name_STBM) {
        this.name_STBM = name_STBM;
    }
    public String getChipsetExtension() {
        return chipsetExtension;
    }
    public void setChipsetExtension(String chipsetExtension) {
        this.chipsetExtension = chipsetExtension;
    }
    @Override
    public String toString() {
        return "chipSetModelId=" + chipSetModelId + ", chipSetName=" + chipSetName + ", name_STBM=" + name_STBM
                + ", chipsetExtension=" + chipsetExtension ;
    }




}

3.Services

3.1界面

package com.learn.spring.service;

import java.util.List;

import com.learn.spring.model.Chipset;
import com.learn.spring.model.Stbm;


public interface ChipsetService {

    public void addChipset(Chipset c);
    public List<Chipset> listChipset();
    public Chipset getChipsetByModelId(int chipSetModelId);


}

3.2已实施的课程

package com.learn.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.learn.spring.dao.ChipsetDAO;
import com.learn.spring.model.Chipset;
import com.learn.spring.model.Stbm;

@Service
public class ChipsetServiceImpl implements ChipsetService {

    @Autowired
    private ChipsetDAO chipsetDAO;

    public void setChipsetDAO(ChipsetDAO chipsetDAO) {
        this.chipsetDAO = chipsetDAO;
    }

    @Override
    @Transactional
    public void addChipset(Chipset c) {
        this.chipsetDAO.addChipset(c);
    }

    @Override
    @Transactional
    public List<Chipset> listChipset() {

        List<Chipset> chipsetList= this.chipsetDAO.listChipset();
        return chipsetList;
    }

    @Override
    @Transactional
    public Chipset getChipsetByModelId(int chipSetModelId) {
        Chipset chipset =this.chipsetDAO.getChipsetByModelId(chipSetModelId);
        return chipset;
    }


}

4.DAO

4.1界面

package com.learn.spring.dao;

import java.util.List;

import com.learn.spring.model.Chipset;
import com.learn.spring.model.Stbm;

public interface ChipsetDAO {

    public void addChipset(Chipset c);

    public List<Chipset> listChipset();
    public Chipset getChipsetByModelId(int chipSetModelId);



}

4.2已实施的课程

package com.learn.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.learn.spring.model.Chipset;
import com.learn.spring.model.Stbm;

@Repository
public class ChipsetDAOImpl implements ChipsetDAO {

    private static final Logger logger = LoggerFactory.getLogger(ChipsetDAOImpl.class);

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    @Override
    public void addChipset(Chipset c) {
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(c);
        logger.info("Chipset saved successfully, Chipset Details="+c);
    }



    @SuppressWarnings("unchecked")
    @Override
    public List<Chipset> listChipset() {
        Session session = this.sessionFactory.getCurrentSession();
        List<Chipset> chipsetList = session.createQuery("from Chipset").list();
        for(Chipset c : chipsetList){
            logger.info("Chipset List::"+c);
        }
        return chipsetList;
    }

    @Override
    public Chipset getChipsetByModelId(int chipSetModelId) {
        Session session = this.sessionFactory.getCurrentSession();      
        Chipset c = (Chipset) session.load(Chipset.class, new Integer(chipSetModelId));
        logger.info("Chipset loaded successfully, Chipset details="+c);
        return c;
    }




}

1 个答案:

答案 0 :(得分:0)

这个答案对你有帮助我想我只给你一个简单的例子,如果你需要在这个例子中进一步说明,我可以回复你,

package com.package;


import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)//U can choose any Other Runner classes like junit4Runner etc here
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)//For Every it will give you a random port number
@FixMethodOrder(MethodSorters.NAME_ASCENDING)//It will take your test methods in assending order
public class LoginControllerTest {
private MockMvc mockMvc;//This will mock your restemplates

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

    }


    @Test
    public void verifyAuthentication() throws Exception {
        mockMvc.perform(get("/chipset")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andDo(print());
    }

}