今天用ssm写一个测试类。我的项目用的是分布式,用dubbo来接发服务。
运行测试类,老是报错。说是找不到本机ip:21880。cause: Failed to bind to: /0.0.0.0:20880。
原因是,我测试的时候把项目启动了,启动项目需要占用application.xml中的端口。加载测试类,需要再加载一次application.xml,当然第二次的端口就不能被加载了。
在用no.2测试,sring-test的依赖版本=spring-web版本。否则报包的冲突。
ssm测试类两种方法,no1通过ApplicationContext来加载配置的file,no2通过spring-test的注解将文件加载进来。
no.1
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yuan.service.impl.TeacherServiceImpl;
public class TeacherServiceTest {
@Test
public void testTeacher(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
TeacherServiceImpl bean = (TeacherServiceImpl)ctx.getBean("teacherService");
System.out.println(bean.queryAll());
}
}
no.2
package com.medicalcare.test;
import com.medicalcare.user.pojo.UserBaseInfo;
import com.medicalcare.user.service.UserService;
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.*;
import javax.annotation.Resource;
import javax.swing.*;
/**
* @author haoshuai
* @Title: MyTest
* @ProjectName medicalcare-parent
* @Description: TODO
* @date 2018/9/1210:13
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MyTest {
@Resource
private UserService userService;
@Test
public void demo1(){
UserBaseInfo userBaseInfo=userService.getUserBaseInfo(1);
System.out.println("我要输出内容了");
System.out.println(userBaseInfo.getUserName());
System.out.println("haha");
}
}