JUnit-execute test
Test cases are executed using the JUnitCore class. JUnitCore is the appearance class for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, or a mixture of them. To run the test from the command line, you can run java org.junit.runner.JUnitCore. For only one test run, you can use the static method runClasses (Class []).
Create a tested Java class MessageUtil.java
package 执行测试;
public class MessageUtil {
String message;
MessageUtil(String message){
this.message = message;
}
public String printMessage(){
System.out.println("MessageUtil类中printMessage()方法中的输出信息:"+message);
return message;
}
}
Create test case class
- Create a java test class called TestJunit.java.
- Add a test method testPrintMessage () to the class.
- Add the annotation @Test to the method testPrintMessage ().
- Implement test conditions and check the test conditions using Junit's assertEquals API.
package 执行测试;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "测试信息";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
assertEquals(message, messageUtil.printMessage());
}
}
Create a java class TestRunner.java to execute the test case, export the JUnitCore class and use the runClasses () method, taking the test class name as a parameter.
package 执行测试;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for(Failure failure:result.getFailures()){
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Test Results