Spring Roo 测试
一、stub unit test
“test stub”命令创建JUnit测试
1、假定已经创建service层代码
package org.rooina.coursemanager.service; import java.math.BigDecimal; import org.springframework.beans.factory.annotation.Autowired; public class DefaultTaxCalcService implements TaxCalcService { private BigDecimal taxRate; @Autowired public DefaultTaxCalcService(BigDecimal taxRate) { this.taxRate = taxRate; } @Override public BigDecimal calculateTax(BigDecimal price) { return price.multiply(taxRate); } }
2、创建测试脚本
roo> test stub --class ~.service.DefaultTaxService
3、产生测试代码
package org.rooina.coursemanager.service; import org.junit.Test; public class DefaultTaxCalcServiceTest { private DefaultTaxCalcService defaultTaxCalcService = ➥ new DefaultTaxCalcService(); @Test public void calculateTax() { org.junit.Assert.assertTrue(true); } }
4、更新测试代码
package org.rooina.coursemanager.service; import java.math.BigDecimal; import junit.framework.Assert; import org.junit.Test; public class DefaultTaxCalcServiceTest { private DefaultTaxCalcService defaultTaxCalcService = new DefaultTaxCalcService(new BigDecimal("0.02")); @Test public void calculateTax() { BigDecimal price = new BigDecimal("50"); BigDecimal taxAmount = defaultTaxCalcService.calculateTax(price); Assert.assertEquals("Tax rate invalid", new BigDecimal("1.00"), taxAmount); } }
二、任意测试
测试任意类时
1、脚本代码
roo> class --class ~.web.BillingServiceSystemTest ➥ --path SRC_TEST_JAVA
2、测试代码
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext*.xml") public class TaskServiceSystemTest { @Autowired private TaskService service; long studentId; @Test @Transactional public void testTask() { TaskDataOnDemand taskDod = new TaskDataOnDemand(); Task task = taskDod.getRandomTask(); Long taskId = task.getId(); Task task1 = service.findTask(taskId); Assert.assertNotNull(task1); } }