我是Spring框架中的新手,需要测试一些后端软件。后端分为三层 - i)dao,ii)服务和iii)控制器。 ' dao'是最近的数据库层,所有SQL查询都在那里。 '服务' layer用于制作来自' dao'的提取数据的JSON。层。控制器' layer用于将JSON字符串抛出到前端。
架构是[数据库< - > dao< - >服务< - >控制器< - >前端]
三层的示例代码如下 - >
GDao.java
==============
@Repository
public class GarageDao {
private JdbcTemplate m_oJdbcTemplateObj;
@Autowired
public void setDataSource(DataSource dataSource) {
this.m_oJdbcTemplateObj = new JdbcTemplate(dataSource);
}
/**
* Query data base to get all the parking site id, identifier, description, and shape
* @return list of map
*/
public List<Map<String,Object>> getAllLocation() {
List<Map<String, Object>> results;
try{
//
}
catch(Exception e){
//
}
return results;
}
}
GServices.java
===================
@Service("m_oGarageService")
public class GarageServices {
@Autowired
private GarageDao m_oGarageDao;
public String getAllLocation() {
List< Map<String, Object> > results = m_oGarageDao.getAllLocation();
try {
if (null != results) {
JSONObject featureCollection = new JSONObject();
featureCollection .put("type", "FeatureCollection");
JSONArray featureList = new JSONArray();
for (Map<String, Object> m : results) {
// some code to insert data into featureList
}
// return JSON data String
return featureCollection.toString();
}
}
catch (JSONException e) {
// some code
}
return null;
}
}
GControllers.java
======================
@Controller
@RequestMapping("/garage")
public class GarageController {
@Autowired
private GarageServices m_oGarageService;
@RequestMapping("/getall")
public @ResponseBody ResponseEntity<String> getAllLocation(){
HttpHeaders ResultHeader = new HttpHeaders();
ResultHeader.set("Access-Control-Allow-Origin", "*");
ResultHeader.set("Content-Type", "application/json");
String result = m_oGarageService.getAllLocation();
if(null == result){
// some code
}
return new ResponseEntity<String>(result, ResultHeader, HttpStatus.OK);
}
}
如何开始后端的写测试?感谢。
答案 0 :(得分:1)
首先,我使用Spring Data存储库而不是自定义DAO代码。然后编写你的bean以使用构造函数注入,并使用与Mockito或Spock相同的方式使用模拟测试它们。