junit unit test, annotation (timeout, exception)

code under test


public class java3 {
public String data(String phone,String ip) {
	if (phone.matches("^[1][0-9]{10}")&&ip.matches("^[a-z][a-z0-9]{0,9}")){
		System.out.println("OK");
		return "OK";
	}else if (phone.matches("^[1][0-9]{10}")) {
		System.out.println("地址不符合要求");
		return "地址不符合要求";
	}else if (ip.matches("^[a-z][a-z0-9]{0,9}")){
		System.out.println("手机号不符合要求");
		return "手机号不符合要求";
	}else {
		System.out.println("手机号和地址不符合要求");
		return "手机号地址不符合要求";
	}
}
}

 test class

import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
import jdk.nashorn.internal.runtime.logging.*;


public class java3Test {
java3 aa=new java3();
	
//	@Test
	public void test() {
		String ss=aa.data("12345678901", "asdf123");
		assertThat(ss, equalTo("OK"));
	}
//  异常测试(expected=AssertionError.class)AssertionError为报错信息
	@Test(expected=AssertionError.class)
	public void test1() {
		String ss=aa.data("12345678901123", "asdf123");
		assertThat(ss, equalTo("手机号不符合要"));
	}
	//超时(timeout=时间)
	@Test(timeout=1)
	public void test2() {
		String ss=aa.data("12345678901", "asdf1231231123");
		assertThat(ss, equalTo("地址不符合要求"));
	}

}

result

OK
手机号不符合要求
地址不符合要求

Guess you like

Origin blog.csdn.net/weixin_62854251/article/details/130017580