Junit入门到掌握-16-JUnit集成-在Java main方法中执行JUnit测试类

前面JUnit基础和JUnit的高级都介绍完了,该考虑和其他工具集成,例如ant和maven,由于最近几年java项目都使用maven和gradle,几乎看不到ant构建工具,所以这个集成,我这里主要介绍JUnit和Maven的集成。其实,如果做过集成自动化自动化测试就应该知道,想要集成,第一个要实现的就是简化成一条命令在控制台或者命令终端执行,如果可以做到,集成就没有任何问题,所以,我们这里先来讨论如何把执行Junit换成控制台执行,下一篇介绍如何在cmd中执行junit测试,就是一条比较长的命令而已。

 

1.前提准备

前面我们一直用这个测试类test.TrackingServiceTests.java,里面大概有5 6个测试用例。

package test;
import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.anthony.protein.InvalidGoalException;
import com.anthony.protein.TrackingService;

public class TrackingServiceTests {
	private TrackingService ts;
	
	@BeforeClass
	public static void before() {
		System.out.println("Before class, Onln Once");
	}
	
	@AfterClass
	public static void after() {
		System.out.println("After class, only once");
	}
	
	@Before
	public void setup() {
		System.out.println("Before Method");
		ts = new TrackingService();
	}
	
	@After
	public void tearDown() {
		System.out.println("After Method");
	}
	
	@Test
	public void newTrackingServiceTotalIsZero() {
		assertEquals("Tracking service total was not zero", 0, ts.getTotal());
	}
	
	@Test
	public void whenAddingProteinTotalIsIncreaseByAmount() {
		ts.addProtein(10);
		assertEquals(10, ts.getTotal());
	}
	
	@Test
	public void whenRemovingProteinTotalRemainsZero() {
		ts.removeProtein(5);
		assertEquals(0, ts.getTotal());
	}
	
	@Test(expected=InvalidGoalException.class)
	public void testExceptionThrow() throws InvalidGoalException {
		ts.setGoal(-5);
	}
	
	@Test(timeout=20)
	public void badTest() throws InvalidGoalException {
		for(int i=0; i < 1000000000; i++) {
			ts.setGoal(1);
		}
	}

}

我们这里新建一个Java类带main方法,代码如下

package test;

import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

public class ConsoleRunner {

	public static void main(String[] args) {
		
		JUnitCore junit = new JUnitCore();
		junit.run(TrackingServiceTests.class);

	}

}

运行下这个Java 主方法,看看效果。

Before class, Onln Once
Before Method
After Method
Before Method
After Method
Before Method
After Method
Before Method
After Method
Before Method
After Method
After class, only once

运行效果是这样,看不出执行了多少条,其实最后一条应该超时了,但是控制台没有显示,为了增加显示,我们需要利用一个监听,添加一行代码。

package test;

import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

public class ConsoleRunner {

	public static void main(String[] args) {
		
		JUnitCore junit = new JUnitCore();
		junit.addListener(new TextListener(System.out));
		junit.run(TrackingServiceTests.class);
	}
}

运行下,控制台输出

Before class, Onln Once
.Before Method
After Method
.Before Method
After Method
E.Before Method
After Method
.Before Method
After Method
.Before Method
After Method
After class, only once

Time: 0.101
There was 1 failure:
1) badTest(test.TrackingServiceTests)
org.junit.runners.model.TestTimedOutException: test timed out after 20 milliseconds
	at test.TrackingServiceTests.badTest(TrackingServiceTests.java:62)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
	at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.lang.Thread.run(Thread.java:748)

FAILURES!!!
Tests run: 5,  Failures: 1

这个就有一个简单的测试报告,执行了多少个,失败了几个,失败详细原因是什么。

 

2.runClass方法

上面演示了执行一个class的过程,如果要执行多个,怎么办?

我们多准备一个测试类HelloJunitTests.java

package test;
 
import static org.junit.Assert.assertEquals;
 
import org.junit.Test;
 
public class HelloJunitTest {
	@Test
	public void test() {
		assertEquals(5, "Hello".length());
		System.out.println("Run Hello Junit");
	}
}

添加这个打印语句是方便在控制台识别是否运行了这个类下的用例。

package test;

import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

public class ConsoleRunner {

	public static void main(String[] args) {
		
		JUnitCore junit = new JUnitCore();
		junit.addListener(new TextListener(System.out));
		//junit.run(TrackingServiceTests.class);
		// 执行多个class
		junit.runClasses(TrackingServiceTests.class, test.HelloJunitTest.class);
	}
}

运行结果,即使添加了监听还是没有详细输出在控制台。

Before class, Onln Once
Before Method
After Method
Before Method
After Method
Before Method
After Method
Before Method
After Method
Before Method
After Method
After class, only once
Run Hello Junit

为什么多个class就监听不到具体输出,这个我也不知道。

 

3.通过加载执行testSuite来执行多个测试类

前面我们学习了TestSuite,这个java main方法其实也可以执行run testSuite。

先创建一个testSuite文件

package test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ 
	HelloJunitTest.class, 
	TheoryTests.class, 
	TrackingServiceTests.class 
})
public class ProteinTrackerSuite {

}

我这边有三个测试类。

package test;

import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

public class ConsoleRunner {

	public static void main(String[] args) {
		
		JUnitCore junit = new JUnitCore();
		junit.addListener(new TextListener(System.out));
		//junit.run(TrackingServiceTests.class);
		// 执行testSuite
		junit.run(ProteinTrackerSuite.class);
		
	}
}

来验证run方法里面是支持TestSuite.class的

.Run Hello Junit
.EBefore class, Onln Once
.Before Method
After Method
.Before Method
After Method
E.Before Method
After Method
.Before Method
After Method
.Before Method
After Method
After class, only once

Time: 0.084
There were 2 failures:
1) testThory(test.TheoryTests)
org.junit.experimental.theories.internal.ParameterizedAssertionError: testThory("-4" <from data[4]>)
	at org.junit.experimental.theories.Theories$TheoryAnchor.reportParameterizedError(Theories.java:288)
	at org.junit.experimental.theories.Theories$TheoryAnchor$1$1.evaluate(Theories.java:237)
	at org.junit.experimental.theories.Theories$TheoryAnchor.runWithCompleteAssignment(Theories.java:218)
	at org.junit.experimental.theories.Theories$TheoryAnchor.runWithAssignment(Theories.java:204)
	at org.junit.experimental.theories.Theories$TheoryAnchor.runWithIncompleteAssignment(Theories.java:212)
	at org.junit.experimental.theories.Theories$TheoryAnchor.runWithAssignment(Theories.java:202)
	at org.junit.experimental.theories.Theories$TheoryAnchor.evaluate(Theories.java:187)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runners.Suite.runChild(Suite.java:128)
	at org.junit.runners.Suite.runChild(Suite.java:27)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runners.Suite.runChild(Suite.java:128)
	at org.junit.runners.Suite.runChild(Suite.java:27)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:105)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:94)
	at test.ConsoleRunner.main(ConsoleRunner.java:14)
Caused by: java.lang.AssertionError
	at org.junit.Assert.fail(Assert.java:86)
	at org.junit.Assert.assertTrue(Assert.java:41)
	at org.junit.Assert.assertTrue(Assert.java:52)
	at test.TheoryTests.testThory(TheoryTests.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.experimental.theories.Theories$TheoryAnchor$2.evaluate(Theories.java:274)
	at org.junit.experimental.theories.Theories$TheoryAnchor$1$1.evaluate(Theories.java:232)
	... 35 more
2) badTest(test.TrackingServiceTests)
org.junit.runners.model.TestTimedOutException: test timed out after 20 milliseconds
	at test.TrackingServiceTests.badTest(TrackingServiceTests.java:62)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
	at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.lang.Thread.run(Thread.java:748)

FAILURES!!!
Tests run: 7,  Failures: 2

这个也是能监听到一个TestSuite类中管理的全部测试用例执行的统计结果。

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
使用 JUnit 测试 Java-Spark 可以按照以下步骤进行: 1. 在 pom.xml 文件添加以下依赖项: ```xml <dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.9.3</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> ``` 2. 创建一个测试,并在上使用 @ExtendWith(JUnit5.class) 注解。 3. 在测试创建一个 Spark 应用程序实例,并在该实例设置路由。 ```java import static spark.Spark.get; public class SparkAppTest { private SparkApp app; @BeforeEach public void setup() { app = new SparkApp(); app.init(); // Define routes get("/hello", (req, res) -> "Hello World"); get("/hello/:name", (req, res) -> "Hello " + req.params("name")); } @AfterEach public void tearDown() { app.stop(); } @Test public void testHelloWorldRoute() { // Use JUnit assertions to test the route given().when().get("/hello").then().statusCode(200).body(is("Hello World")); } @Test public void testHelloNameRoute() { // Use JUnit assertions to test the route given().when().get("/hello/John").then().statusCode(200).body(is("Hello John")); } } ``` 4. 在测试方法使用 RestAssured 发送 HTTP 请求,并使用 JUnit 断言来检查响应。 ```java import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.is; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.restassured.RestAssured; import spark.Spark; @ExtendWith(SparkExtension.class) public class SparkAppTest { private SparkApp app; @BeforeEach public void setup() { app = new SparkApp(); app.init(); // Define routes get("/hello", (req, res) -> "Hello World"); get("/hello/:name", (req, res) -> "Hello " + req.params("name")); } @AfterEach public void tearDown() { app.stop(); } @Test public void testHelloWorldRoute() { // Use JUnit assertions to test the route given().when().get("/hello").then().statusCode(200).body(is("Hello World")); } @Test public void testHelloNameRoute() { // Use JUnit assertions to test the route given().when().get("/hello/John").then().statusCode(200).body(is("Hello John")); } } ``` 以上就是使用 JUnit 测试 Java-Spark 的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值