您的位置:首页 > 编程语言 > Java开发

Spring与Junit结合使用的代码

2017-05-15 19:59 316 查看
1、首先应该导入Junit相应版本的jar包和Spring TestContext Framework的jar包(gradle相应加入'org.springframework:spring-test:4.3.8.RELEASE'即可)

2、在你的Junit类中使用Spring注解来配置和注入,我的Spring配置文件放在WEB-INF目录下所以我引用它的地址是“file:src/main/webapp/WEB-INF/applicationContext.xml",如果你是放在src/main/resources下面的话即为”classpath:applicationContext.xml",



具体代码为:

package test;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
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.SpringJUnit4ClassRunner;
import domain.Guitar;
import domain.GuitarSpec;
import domain.Inventory;
import service.GuitarService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml"})
public class GuitarTest {
@Autowired
private GuitarService guitarService;

@Test
public void test1() {
GuitarSpec guitarSpec = new GuitarSpec("","","","alder","");
Inventory inventroy = new Inventory();
List<Guitar> guitarList = new ArrayList<Guitar>();
guitarList = guitarService.getAll();
inventroy.setGuitars(guitarList);
List<Guitar> guitarList2 = new ArrayList<Guitar>();
try {
guitarList2 = inventroy.search(guitarSpec);
} catch (Exception e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
for(Guitar guitar : guitarList2){
JSONObject jo = new JSONObject();
jo.put("price", guitar.getPrice());
jo.put("serialNumber", guitar.getSerialNumber());
jo.put("backWood", guitar.getGuitarSpec().getBackWood());
jo.put("builder", guitar.getGuitarSpec().getBuilder());
jo.put("model", guitar.getGuitarSpec().getModel());
jo.put("topWood", guitar.getGuitarSpec().getTopWood());
jo.put("type", guitar.getGuitarSpec().getType());
jsonArray.put(jo);
System.out.println(jo.toString());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: