本文整理了Java中junit.framework.TestCase
类的一些代码示例,展示了TestCase
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。TestCase
类的具体详情如下:
包路径:junit.framework.TestCase
类名称:TestCase
[英]A test case defines the fixture to run multiple tests. To define a test case
TestCase
public class MathTest extends TestCase {
protected double fValue1;
protected double fValue2;
protected void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}
}
For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling junit.framework.Assert#assertTrue(String,boolean) with a boolean.
public void testAdd() {
double result= fValue1 + fValue2;
assertTrue(result == 5.0);
}
Once the methods are defined you can run them. The framework supports both a static type safe and more dynamic way to run a test. In the static way you override the runTest method and define the method to be invoked. A convenient way to do so is with an anonymous inner class.
TestCase test= new MathTest("add") {
public void runTest() {
testAdd();
}
};
test.run();
The dynamic way uses reflection to implement #runTest(). It dynamically finds and invokes a method. In this case the name of the test case has to correspond to the test method to be run.
TestCase test= new MathTest("testAdd");
test.run();
The tests to be run can be collected into a TestSuite. JUnit provides different test runners which can run a test suite and collect the results. A test runner either expects a static method suite
as the entry point to get a test to run or it will extract the suite automatically.
public static Test suite() {
suite.addTest(new MathTest("testAdd"));
suite.addTest(new MathTest("testDivideByZero"));
return suite;
}
[中]测试用例定义了运行多个测试的夹具。定义测试用例
1.实现TestCase
的子类
1.定义存储设备状态的实例变量
1.通过覆盖#setUp()初始化设备状态
1.在测试后通过覆盖#拆卸()进行清理。
每个测试都在自己的夹具中运行,因此测试运行之间不会产生任何副作用。下面是一个例子:
public class MathTest extends TestCase {
protected double fValue1;
protected double fValue2;
protected void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}
}
对于每个测试,实现一个与夹具交互的方法。使用调用junit指定的断言验证预期结果。框架Assert#assertTrue(字符串,布尔值)带有布尔值
public void testAdd() {
double result= fValue1 + fValue2;
assertTrue(result == 5.0);
}
一旦定义了这些方法,就可以运行它们。该框架支持静态类型安全和更动态的测试运行方式。以静态方式重写runTest方法并定义要调用的方法。一种方便的方法是使用匿名内部类
TestCase test= new MathTest("add") {
public void runTest() {
testAdd();
}
};
test.run();
动态方式使用反射来实现#runTest()。它动态地查找并调用一个方法。在这种情况下,测试用例的名称必须与要运行的测试方法相对应
TestCase test= new MathTest("testAdd");
test.run();
要运行的测试可以收集到一个测试套件中。JUnit提供了不同的测试运行程序,可以运行测试套件并收集结果。测试运行者要么期望一个静态方法suite
作为让测试运行的入口点,要么将自动提取套件
public static Test suite() {
suite.addTest(new MathTest("testAdd"));
suite.addTest(new MathTest("testDivideByZero"));
return suite;
}
代码示例来源:origin: google/guava
@Override
public void run() {
assertTrue("Listener called before it was expected", expectCall);
assertFalse("Listener called more than once", wasCalled());
calledCountDown.countDown();
}
代码示例来源:origin: google/guava
@Override
protected void setUp() throws Exception {
super.setUp();
testWasRun = false;
}
代码示例来源:origin: google/guava
@Override
protected void shutDown() {
assertTrue(startUpCalled);
assertTrue(runCalled);
assertFalse(shutDownCalled);
shutDownCalled = true;
assertEquals(expectedShutdownState, state());
}
代码示例来源:origin: google/guava
@Override
public synchronized void onSuccess(String result) {
assertFalse(wasCalled);
wasCalled = true;
assertEquals(value, result);
}
代码示例来源:origin: google/guava
@Override
protected void process(ByteBuffer bb) {
processCalled++;
assertEquals(ByteOrder.LITTLE_ENDIAN, bb.order());
assertTrue(bb.remaining() >= chunkSize);
for (int i = 0; i < chunkSize; i++) {
out.write(bb.get());
}
}
代码示例来源:origin: org.geoserver/gs-wcs2_0
@Test
public void testScaleAxesByFactorXML() throws Exception {
final File xml = new File("./src/test/resources/requestGetCoverageScaleAxesByFactor.xml");
final String request = FileUtils.readFileToString(xml);
MockHttpServletResponse response = postAsServletResponse("wcs", request);
assertEquals("image/tiff", response.getContentType());
byte[] tiffContents = getBinary(response);
File file = File.createTempFile("bm_gtiff", "bm_gtiff.tiff", new File("./target"));
FileUtils.writeByteArrayToFile(file, tiffContents);
// check the tiff structure is the one requested
final GeoTiffReader reader = new GeoTiffReader(file);
assertTrue(
CRS.equalsIgnoreMetadata(
reader.getCoordinateReferenceSystem(), CRS.decode("EPSG:4326", true)));
assertEquals(1260, reader.getOriginalGridRange().getSpan(0));
assertEquals(1260, reader.getOriginalGridRange().getSpan(1));
final GridCoverage2D coverage = reader.read(null);
assertNotNull(coverage);
assertEnvelopeEquals(sourceCoverage, coverage);
reader.dispose();
scheduleForCleaning(coverage);
}
代码示例来源:origin: org.geoserver/gs-wcs2_0
@Test
public void testCoverageTrimmingDuplicatedNativeCRSXML() throws Exception {
final File xml =
new File(
"./src/test/resources/trimming/requestGetCoverageTrimmingDuplicatedNativeCRSXML.xml");
final String request = FileUtils.readFileToString(xml);
MockHttpServletResponse response = postAsServletResponse("wcs", request);
assertEquals("application/xml", response.getContentType());
// checkOws20Exception(response, 404, "InvalidAxisLabel", "coverageId");
}
代码示例来源:origin: org.geoserver/gs-wcs2_0
@Test
public void testInterpolationMixedTimeXML() throws Exception {
final File xml =
new File("./src/test/resources/requestGetCoverageInterpolationMixedTime.xml");
final String request = FileUtils.readFileToString(xml);
MockHttpServletResponse response = postAsServletResponse("wcs", request);
assertEquals("application/xml", response.getContentType());
Document dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()));
print(dom);
}
代码示例来源:origin: spring-projects/spring-framework
@Test // SPR-17410
public void writePublisherError() {
// Turn off writing so next item will be cached
this.processor.setWritePossible(false);
DataBuffer buffer = mock(DataBuffer.class);
this.processor.onNext(buffer);
// Send error while item cached
this.processor.onError(new IllegalStateException());
assertNotNull("Error should flow to result publisher", this.resultSubscriber.getError());
assertEquals(1, this.processor.getDiscardedBuffers().size());
assertSame(buffer, this.processor.getDiscardedBuffers().get(0));
}
代码示例来源:origin: google/guava
void check() {
runTester();
@SuppressWarnings("unchecked") // We are checking it anyway
Converter<String, Integer> defaultConverter =
(Converter<String, Integer>) getDefaultParameterValue(0);
assertEquals(Integer.valueOf(0), defaultConverter.convert("anything"));
assertEquals("", defaultConverter.reverse().convert(123));
assertNull(defaultConverter.convert(null));
assertNull(defaultConverter.reverse().convert(null));
}
}
代码示例来源:origin: google/guava
@Override
public void tearDown() throws Exception {
super.tearDown();
LocalCache.logger.removeHandler(logHandler);
}
代码示例来源:origin: google/guava
@Override
public Entry<K, V> ceilingEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceilingEntry(key);
}
代码示例来源:origin: google/guava
@Override
public void run() {
assertTrue("Listener called before it was expected", expectCall);
assertFalse("Listener called more than once", wasCalled());
called.set(true);
}
代码示例来源:origin: google/guava
public static void assertMapEntryIsUnmodifiable(Entry<?, ?> entry) {
try {
entry.setValue(null);
fail("setValue on unmodifiable Map.Entry succeeded");
} catch (UnsupportedOperationException expected) {
}
}
代码示例来源:origin: apache/hive
/**
* Testing getPartitionWithAuthInfo(String,String,List(String),String,List(String)) ->
* get_partition_with_auth(String,String,List(String),String,List(String)).
*/
@Test
public void testGetPartitionWithAuthInfoNoPrivilagesSet() throws Exception {
createTable3PartCols1Part(client);
Partition partition = client.getPartitionWithAuthInfo(DB_NAME, TABLE_NAME, Lists.newArrayList(
"1997", "05", "16"), "", Lists.newArrayList());
assertNotNull(partition);
assertNull(partition.getPrivileges());
}
代码示例来源:origin: org.geoserver/gs-wcs2_0
private void assertOriginPixelColor(MockHttpServletResponse response, int[] expected)
throws DataSourceException, IOException {
assertEquals("image/tiff", response.getContentType());
byte[] bytes = response.getContentAsByteArray();
GeoTiffReader reader = new GeoTiffReader(new ByteArrayInputStream(bytes));
GridCoverage2D coverage = reader.read(null);
Raster raster = coverage.getRenderedImage().getData();
int[] pixel = new int[3];
raster.getPixel(0, 0, pixel);
assertThat(pixel, equalTo(expected));
}
}
代码示例来源:origin: google/guava
@Override
protected void verify(List<Integer> elements) {
assertEquals(newHashSet(elements), multimap.get("foo"));
}
}.test();
代码示例来源:origin: google/guava
void check() {
runTester();
NullRejectingFromTo<?, ?> defaultFunction =
(NullRejectingFromTo<?, ?>) getDefaultParameterValue(0);
assertNotNull(defaultFunction);
try {
defaultFunction.apply(null);
fail("Proxy Should have rejected null");
} catch (NullPointerException expected) {
}
}
}
代码示例来源:origin: cloudfoundry/uaa
@Test
public void invalid_principal_throws() {
Authentication a = mock(Authentication.class);
when(a.getPrincipal()).thenReturn(new Object());
try {
successHandler.setSavedAccountOptionCookie(new MockHttpServletRequest(), new MockHttpServletResponse(), a);
}catch (IllegalArgumentException x) {
assertEquals("Unrecognized authentication principle.", x.getMessage());
}
}
代码示例来源:origin: geoserver/geoserver
protected void setUp() throws Exception {
super.setUp();
HelloWorld helloWorld = new HelloWorld();
Service service =
new Service(
"hello",
helloWorld,
new Version("1.0.0"),
Collections.singletonList("hello"));
request =
new MockHttpServletRequest() {
public int getServerPort() {
return 8080;
}
};
request.setScheme("http");
request.setServerName("localhost");
request.setContextPath("geoserver");
response = new MockHttpServletResponse();
handler = new DefaultServiceExceptionHandler();
requestInfo = new Request();
requestInfo.setHttpRequest(request);
requestInfo.setHttpResponse(response);
requestInfo.setService("hello");
requestInfo.setVersion("1.0.0");
}
内容来源于网络,如有侵权,请联系作者删除!