DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

如何做Groovy单元测试


Groovy的单元测试可以通过两种方法进行,一是用JUnit框架, 二是用Groovy自己的TestSuite测试。JUnit测试代码是Java代码, GroovyTestSuite的测试代码是groovy代码,且只能一次运行测试类中所有的TestCase, 灵活性较JUnit方法稍差。下面是一个实例:

被测试类Song.groovy:

package  org.leechau.ut; 

class  Song { 
  def name
  def artist
  def genre
  String toString(){ 
    "${ name }, ${ artist }, ${ genre }" 
  } 
  def getGenre(){ 
    genre?.toUpperCase() 
  } 
} 

class Song2 { 
  def name2
  def ex(){
    println  name2
  } 
} 

JUnit测试文件SongTest.java:

package org.leechau.ut; 
import org.junit.Assert; 
import org.junit.Test; 

public class SongTest { 
  @Test
    public void testToString() {
    Song sng = new Song();
    sng.setArtist("Lee");
    Assert.assertEquals("Lee", sng.getArtist());
  }
}

Groovy测试文件TestSong2.groovy:

package org.leechau.ut2;

import groovy.util.GroovyTestCase
import org.leechau.ut.Song
import org.leechau.ut.Song2

class SongTest2 extends GroovyTestCase{
  void  testGetGenre() {
    def  sng =  new  Song()
    sng.setGenre  "Pop"
    assertEquals (sng.getGenre(),  "POP" )
  }
  void  testSong2(){
    def  sng2 =  new  Song2()
    sng2.setName2  "Song2"
    assertEquals (sng2.getName2(),  "Song2" )
  }
} 

且需要进行运行设置:

  1. 在Java Application中新建一个run configuration;

  2. Main标签下的Main Class写:groovy.util.GroovyTestSuite,且勾选“Include System Libraries when searching for a main class”;

  3. Arguments标签下program arguments下写上测试脚本的相对路径,如:src\org\leechau\ut2\SongTest2.groovy;

  4. 运行该配置;

结果如下:



Published

May 31, 2011

Last Updated

May 31, 2011

Category

Tech

Tags

  • groovy 13
  • unittest 4

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor