java----JUnit

在pom.xml中添加JUnit依赖

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13-beta-2</version>
            <scope>compile</scope>   <!--scope中的compile官网是test,如果改为test会报错(网上说scope标签,这个标签是只能在test package下才能引用此jar包),直接将 <scope>compile</scope> 去掉也是可以的-->
</dependency>

使用

@Before
public void before(){
        System.out.println("before");
}
@After
public void after(){
        System.out.println("after");
}
@Test
public void test() {
        System.out.println("test");
}

  

高级用法

在pom中添加

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13-beta-2</version>
</dependency>
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.1.7.RELEASE</version>
</dependency>

  

使用

@RunWith(SpringJUnit4ClassRunner.class) //junit和spring整合
@ContextConfiguration(locations = "classpath:spring-context.xml")//定位到src目录下(target的名字叫classes,打包的时候resources目录下的文件,会放到classes目录下)
public class DemoTest {
    @Autowired
    private  UserAcountService userAcountService;

    @Test
    public void demo1(){
        userAcountService.transfer("渣渣辉","古天乐",10);
    }
}

替代了下面 (这样不用每一个方法都要写 new ClassPathXmlApplicationContext())

public class DemoTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        UserAcountService userAcountServiceImpl = (UserAcountService) classPathXmlApplicationContext.getBean("userAcountServiceImpl");
        userAcountServiceImpl.transfer("渣渣辉","古天乐",10);
    }
}

  

  

原文地址:https://www.cnblogs.com/yanxiaoge/p/10809761.html