1、什么是junit?
2、思路:
a.写一个Person类(如下)
b.写配置文件(如下)
c.新建一个类,类中写一个用来测试的方法,将测试的代码放入这个测试方法内,然后右键—— go to —— test——勾选这个测试方法,然后就会在这个方法上生成@Test,然后在这个类上注上@RunWith,@ContextConfiguration,然后运行就行了。(如下)
3、上代码
Person类
public class Person {
private String name;
private Integer age;
private String adress;
private String phoneNum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", adress='" + adress + '\'' +
", phoneNum='" + phoneNum + '\'' +
'}';
}
public Person(String name, Integer age, String adress, String phoneNum) {
this.name = name;
this.age = age;
this.adress = adress;
this.phoneNum = phoneNum;
}
public Person() {
}
}
TestTest类
package klj.spipng_demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-config.xml"})
public class TestTest {
@Test
public void test1() {
//加载sping的配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
//获取到Person类
Person person = (Person) applicationContext.getBean("Person");
// 输出对象
System.out.println(person);
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="Person" class="klj.spipng_demo.Person" >
<constructor-arg name="adress" value="山东临沂"></constructor-arg>
<constructor-arg name="age" value="17"></constructor-arg>
<constructor-arg name="phoneNum" value="13969902329"></constructor-arg>
<constructor-arg name="name" value="konglingjin"></constructor-arg>
</bean>
</beans>