下面列出了怎么用org.junit.rules.ExpectedException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testMapObjectToDomain() throws MappingException {
exception = ExpectedException.none();
MappingResult result = mapper.mapToDomainField(findDomainField("floatValue"), testProtobuf, testDomain);
testMappingResult(result, Result.MAPPED, testProtobuf.getFloatValue(), testDomain);
result = mapper.mapToDomainField(findDomainField("doubleValue"), testProtobuf, testDomain);
testMappingResult(result, Result.MAPPED, testProtobuf.getDoubleValue(), testDomain);
result = mapper.mapToDomainField(findDomainField("intValue"), testProtobuf, testDomain);
testMappingResult(result, Result.MAPPED, testProtobuf.getIntValue(), testDomain);
result = mapper.mapToDomainField(findDomainField("longValue"), testProtobuf, testDomain);
testMappingResult(result, Result.MAPPED, testProtobuf.getLongValue(), testDomain);
result = mapper.mapToDomainField(findDomainField("stringValue"), testProtobuf, testDomain);
testMappingResult(result, Result.MAPPED, testProtobuf.getStringValue(), testDomain);
}
@Test
public void testMapObjectToProtobuf() throws MappingException {
exception = ExpectedException.none();
MappingProto.MappingTest.Builder protobufBuilder = MappingProto.MappingTest.newBuilder();
MappingResult result = mapper.mapToProtobufField(findDomainField("boolValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, testDomain.getBoolValue(), protobufBuilder);
result = mapper.mapToProtobufField(findDomainField("floatValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, testDomain.getFloatValue(), protobufBuilder);
result = mapper.mapToProtobufField(findDomainField("doubleValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, testDomain.getDoubleValue(), protobufBuilder);
result = mapper.mapToProtobufField(findDomainField("intValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, testDomain.getIntValue(), protobufBuilder);
result = mapper.mapToProtobufField(findDomainField("longValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, testDomain.getLongValue(), protobufBuilder);
result = mapper.mapToProtobufField(findDomainField("stringValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, testDomain.getStringValue(), protobufBuilder);
}
@Test
public void testMapPrimitiveToProtobuf() throws MappingException {
exception = ExpectedException.none();
MappingProto.MappingTest.Builder protobufBuilder = MappingProto.MappingTest.newBuilder();
MappingResult result = mapper
.mapToProtobufField(findPrimitiveField("booleanValue"), primitiveTestDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, primitiveTestDomain.isBooleanValue(), protobufBuilder);
result = mapper.mapToProtobufField(findPrimitiveField("floatValue"), primitiveTestDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, primitiveTestDomain.getFloatValue(), protobufBuilder);
result = mapper.mapToProtobufField(findPrimitiveField("doubleValue"), primitiveTestDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, primitiveTestDomain.getDoubleValue(), protobufBuilder);
result = mapper.mapToProtobufField(findPrimitiveField("intValue"), primitiveTestDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, primitiveTestDomain.getIntValue(), protobufBuilder);
result = mapper.mapToProtobufField(findPrimitiveField("longValue"), primitiveTestDomain, protobufBuilder);
testMappingResult(result, Result.MAPPED, primitiveTestDomain.getLongValue(), protobufBuilder);
}
@Test
public void testExceptionThrownWhenMisConfigured() throws IOException {
Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
conf.set("hbase.thrift.security.qop", "privacy");
conf.setBoolean("hbase.thrift.ssl.enabled", false);
ExpectedException thrown = ExpectedException.none();
ThriftServerRunner tsr = null;
try {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Thrift HTTP Server's QoP is privacy, " +
"but hbase.thrift.ssl.enabled is false");
tsr = TestThriftServerCmdLine.createBoundServer(() -> new ThriftServer(conf));
fail("Thrift HTTP Server starts up even with wrong security configurations.");
} catch (Exception e) {
LOG.info("Expected!", e);
} finally {
if (tsr != null) {
tsr.close();
}
}
}
@Test
public void testMapFieldWithDifferentNameToDomain() throws MappingException {
exception = ExpectedException.none();
MappingResult result = mapper.mapToDomainField(findDomainField("boolValue"), testProtobuf, testDomain);
testMappingResult(result, Result.MAPPED, testProtobuf.getBooleanValue(), testDomain);
result = mapper.mapToDomainField(findDomainField("simpleListValue"), testProtobuf, testDomain);
testMappingResult(result, Result.COLLECTION_MAPPING, testProtobuf.getStringListValueList(), testDomain);
}
@Test
public void testMapCollectionToDomain() throws MappingException {
exception = ExpectedException.none();
MappingResult result = mapper.mapToDomainField(findDomainField("simpleListValue"), testProtobuf, testDomain);
testMappingResult(result, Result.COLLECTION_MAPPING, testProtobuf.getStringListValueList(), testDomain);
result = mapper.mapToDomainField(findDomainField("nestedListValue"), testProtobuf, testDomain);
testMappingResult(result, Result.COLLECTION_MAPPING, testProtobuf.getNestedListValueList(), testDomain);
}
@Test
public void testMapCollectionToProtobuf() throws MappingException {
exception = ExpectedException.none();
MappingProto.MappingTest.Builder protobufBuilder = MappingProto.MappingTest.newBuilder();
MappingResult result = mapper
.mapToProtobufField(findDomainField("simpleListValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.COLLECTION_MAPPING, testDomain.getSimpleListValue(), protobufBuilder);
result = mapper.mapToProtobufField(findDomainField("nestedListValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.COLLECTION_MAPPING, testDomain.getNestedListValue(), protobufBuilder);
}
@Test
public void testMapNestedToProtobuf() throws MappingException {
exception = ExpectedException.none();
MappingProto.MappingTest.Builder protobufBuilder = MappingProto.MappingTest.newBuilder();
MappingResult result = mapper.mapToProtobufField(findDomainField("nestedValue"), testDomain, protobufBuilder);
testMappingResult(result, Result.NESTED_MAPPING, testDomain.getNestedValue(), protobufBuilder);
}
private TypeSpec classTest(ClassName className, List<MethodSpec> methodSpecs) {
String methodName = Introspector
.decapitalize(className.simpleName());
MethodSpec abstractMethodInstanceToTest = methodBuilder(methodName)
.addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED)
.returns(className)
.build();
FieldSpec exception = FieldSpec.builder(ExpectedException.class, "exception")
.addAnnotation(Rule.class)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.initializer("$T.none()", ExpectedException.class)
.build();
return TypeSpec.classBuilder(className.simpleName() + "Test_")
.addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
.addMethod(abstractMethodInstanceToTest)
.addField(exception)
.addAnnotation(AnnotationSpec.builder(Generated.class)
.addMember("value", "$S", MockeryProcessor.class.getCanonicalName())
.addMember("comments", "$S", CMessages.codeGenerateWarning())
.build())
.addAnnotation(AnnotationSpec.builder(RunWith.class)
.addMember("value", "$T.class", OrderedRunner.class)
.build())
.addMethods(methodSpecs)
.build();
}
/** Tests trying to call add after calling sort. Should throw an exception. */
public static void testAddAfterSort(Sorter sorter, ExpectedException thrown) throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage(is("Records can only be added before sort()"));
KV<byte[], byte[]> kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2});
sorter.add(kv);
sorter.sort();
sorter.add(kv);
}
/** Tests trying to calling sort twice. Should throw an exception. */
public static void testSortTwice(Sorter sorter, ExpectedException thrown) throws Exception {
thrown.expect(IllegalStateException.class);
thrown.expectMessage(is("sort() can only be called once."));
KV<byte[], byte[]> kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2});
sorter.add(kv);
sorter.sort();
sorter.sort();
}
/**
* Asserts that a {@link IllegalQueryException} is thrown with the given {@link ErrorCode}.
*
* @param exception the {@link ExpectedException}.
* @param errorCode the {@link ErrorCode}.
*/
public static void assertIllegalQueryEx( ExpectedException exception, ErrorCode errorCode )
{
exception.expect( IllegalQueryException.class );
exception.expect( Matchers.hasProperty( "errorCode", CoreMatchers.is( errorCode ) ) );
exception.reportMissingExceptionWithMessage( String.format(
"Test does not throw an IllegalQueryException with error code: '%s'", errorCode ) );
}
@Test
public void nsdManagementOnboardTest()
throws NotFoundException, BadFormatException, NetworkServiceIntegrityException,
CyclicDependenciesException, EntityInUseException, BadRequestException, IOException,
AlreadyExistingException, PluginException, IncompatibleVNFPackage, VimException,
InterruptedException, EntityUnreachableException {
NetworkServiceDescriptor nsd_exp = createNetworkServiceDescriptor();
when(vnfmManagerEndpointRepository.findAll())
.thenReturn(
new ArrayList<VnfmManagerEndpoint>() {
{
VnfmManagerEndpoint vnfmManagerEndpoint = new VnfmManagerEndpoint();
vnfmManagerEndpoint.setEndpoint("test");
vnfmManagerEndpoint.setType("test");
vnfmManagerEndpoint.setActive(true);
vnfmManagerEndpoint.setEnabled(true);
add(vnfmManagerEndpoint);
}
});
when(nsdRepository.save(nsd_exp)).thenReturn(nsd_exp);
exception = ExpectedException.none();
nsdManagement.onboard(nsd_exp, projectId);
assertEqualsNSD(nsd_exp);
}
@Test
public void timeoutTestNull() throws KeeperException, InterruptedException, IOException {
claimLockingTicket(zookeeperConnection.getActiveConnection(), znode);
thrown = ExpectedException.none();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("TIMER");
try {
deleteLockingTicket(zookeeperConnection.getActiveConnection(), znode);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
}, 2000);
ResourceClaim claim = ExpiringResourceClaim.claimExpiring(
zookeeperConnection,
64,
znode,
Duration.ofSeconds(2),
Duration.ofSeconds(5)
);
int resource = claim.get();
assertThat(claim.state, is(ResourceClaim.State.HAS_CLAIM));
assertThat(resource, is(both(greaterThanOrEqualTo(0)).and(lessThan(64))));
}
@Test
public void shouldConvertDefaultValue() {
// assert
thrown = ExpectedException.none();
// act
optionDefinitionUnderTest.getDefaultValue();
}
@Test
public void testHTTPError() {
ExpectedException exception = ExpectedException.none();
try {
exception.expect(CandybeanException.class);
response = WS.request(WS.OP.POST, uri + "/get", headers, "", ContentType.DEFAULT_TEXT);
Assert.fail();
} catch (CandybeanException e) {
Assert.assertEquals("HTTP request received HTTP code: 405",
e.getMessage().split("\n")[0]);
}
}
@Test
@Ignore("This test should pass, but takes a full minute to do so because it" +
"waits for the response to time out.")
public void testResponseError() {
ExpectedException exception = ExpectedException.none();
try {
exception.expect(CandybeanException.class);
// Send to an IP address that does not exist
response = WS.request(WS.OP.POST, "http://240.0.0.0", headers, "", ContentType.DEFAULT_TEXT);
Assert.fail();
} catch (CandybeanException e) {
Assert.assertEquals("Connect to 240.0.0.0:80 [/240.0.0.0] failed: Operation timed out", e.getMessage());
}
}
/**
* Checks the GET operation fails when the downloaded file (from HA store)
* is corrupt, i.e. its content's hash does not match the {@link BlobKey}'s hash.
*
* @param config
* blob server configuration (including HA settings like {@link HighAvailabilityOptions#HA_STORAGE_PATH}
* and {@link HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt>
* @param blobStore
* shared HA blob store to use
* @param expectedException
* expected exception rule to use
*/
public static void testGetFailsFromCorruptFile(
Configuration config, BlobStore blobStore, ExpectedException expectedException)
throws IOException {
Random rnd = new Random();
JobID jobId = new JobID();
try (BlobServer server = new BlobServer(config, blobStore)) {
server.start();
byte[] data = new byte[2000000];
rnd.nextBytes(data);
// put content addressable (like libraries)
BlobKey key = put(server, jobId, data, PERMANENT_BLOB);
assertNotNull(key);
// delete local file to make sure that the GET requests downloads from HA
File blobFile = server.getStorageLocation(jobId, key);
assertTrue(blobFile.delete());
// change HA store file contents to make sure that GET requests fail
byte[] data2 = Arrays.copyOf(data, data.length);
data2[0] ^= 1;
File tmpFile = Files.createTempFile("blob", ".jar").toFile();
try {
FileUtils.writeByteArrayToFile(tmpFile, data2);
blobStore.put(tmpFile, jobId, key);
} finally {
//noinspection ResultOfMethodCallIgnored
tmpFile.delete();
}
// issue a GET request that fails
expectedException.expect(IOException.class);
expectedException.expectMessage("data corruption");
get(server, jobId, key);
}
}
/**
* Checks the GET operation fails when the downloaded file (from HA store)
* is corrupt, i.e. its content's hash does not match the {@link BlobKey}'s hash.
*
* @param config
* blob server configuration (including HA settings like {@link HighAvailabilityOptions#HA_STORAGE_PATH}
* and {@link HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt>
* @param blobStore
* shared HA blob store to use
* @param expectedException
* expected exception rule to use
*/
public static void testGetFailsFromCorruptFile(
Configuration config, BlobStore blobStore, ExpectedException expectedException)
throws IOException {
Random rnd = new Random();
JobID jobId = new JobID();
try (BlobServer server = new BlobServer(config, blobStore)) {
server.start();
byte[] data = new byte[2000000];
rnd.nextBytes(data);
// put content addressable (like libraries)
BlobKey key = put(server, jobId, data, PERMANENT_BLOB);
assertNotNull(key);
// delete local file to make sure that the GET requests downloads from HA
File blobFile = server.getStorageLocation(jobId, key);
assertTrue(blobFile.delete());
// change HA store file contents to make sure that GET requests fail
byte[] data2 = Arrays.copyOf(data, data.length);
data2[0] ^= 1;
File tmpFile = Files.createTempFile("blob", ".jar").toFile();
try {
FileUtils.writeByteArrayToFile(tmpFile, data2);
blobStore.put(tmpFile, jobId, key);
} finally {
//noinspection ResultOfMethodCallIgnored
tmpFile.delete();
}
// issue a GET request that fails
expectedException.expect(IOException.class);
expectedException.expectMessage("data corruption");
get(server, jobId, key);
}
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}
@Rule
public ExpectedException expectedException() {
return expectedException;
}