junit单元测试时通过spring注入

springboot:
测试原子服务

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
@SuppressWarnings("deprecation")
public class RcSystemTest {
    @Autowired
    private AddRcSystemService addRcSystemService;
    @Test
    public void AddRcSystemTest() throws  Exception{
        RcSystemPo rcSystemPo=new RcSystemPo();
        rcSystemPo.setSysId((long) 2);
        rcSystemPo.setSysName("托儿所");
        int i = addRcSystemService.addRcSystem(rcSystemPo);
        System.out.println(i);
    }

    /**
     * 测试原子服务 查询RcSystem
     * @throws Exception
     */
    @Test
    public void selectRcSystemTest() throws  Exception{
        RcSystemPO rcSystemPo=new RcSystemPO();
        rcSystemPo.setSysId(362338778643234816L);
        RcSystemPO rcSystemPO = rcSystemAtomService.selectRcSystem(rcSystemPo);
        Assert.assertEquals("托儿所",rcSystemPO.getSysName());
        Assert.assertEquals("幼稚园",rcSystemPO.getSysAlias());
    }
}

测试controller,先把服务起来:

import com.alibaba.fastjson.JSONObject;
import com.ohaotian.plugin.common.util.BeanMapper;
import com.ohaotian.plugin.db.Sequence;
import com.tydic.sz.RcSystem.bo.AddRcSystemReqBO;
import com.tydic.sz.RcSystem.service.AddRcSystemBusiService;
import com.tydic.sz.vo.AddRcSystemVo;
import lombok.extern.ohaotian.HTServiceRef;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
@SuppressWarnings("deprecation")
public class RcSystemControllerTest {
    @HTServiceRef
    private AddRcSystemBusiService addRcSystemBusiService;

    @Test
    public void AddRcSystemTest() throws  Exception{
        AddRcSystemVo addRcSystemVo=new AddRcSystemVo();
        //生成主键
        Sequence sequence=Sequence.getInstance();

        addRcSystemVo.setSysId(sequence.nextId());
        addRcSystemVo.setSysName("土管所");
        addRcSystemVo.setSysLevel("国建");
        addRcSystemVo.setSysOrg("xx部门");
        addRcSystemVo.setSysUseObject("社会公众");
        addRcSystemVo.setNetEnvironment("电子政务外网");
        addRcSystemVo.setSysUrl("http://www.xxx.com");

        //解析扩展字段
        JSONObject jsonObject = (JSONObject) JSONObject.parse(addRcSystemVo.getExtend());
        //vo转bo
        AddRcSystemReqBO addRcSystemReqBO=new AddRcSystemReqBO();
        BeanMapper.copy(addRcSystemVo, addRcSystemReqBO);
        addRcSystemBusiService.addRcSystem(addRcSystemReqBO, jsonObject);

    }
}

ssm:
测试类的名字上添加注解:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:beans.xml" })或者@ContextConfiguration("classpath:beans.xml")

你可能感兴趣的:(junit单元测试时通过spring注入)