下面列出了org.springframework.boot.test.system.CapturedOutput#org.assertj.core.api.BDDAssertions 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void customerByIdShouldReturnACustomer() {
WireMock.stubFor(WireMock.get(WireMock.urlMatching("/customers/1"))
.willReturn(
WireMock.aResponse()
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
.withStatus(HttpStatus.OK.value())
.withBody(asJson(customerById))
));
Customer customer = client.getCustomerById(1L);
BDDAssertions.then(customer.getFirstName()).isEqualToIgnoringCase("first");
BDDAssertions.then(customer.getLastName()).isEqualToIgnoringCase("last");
BDDAssertions.then(customer.getEmail()).isEqualToIgnoringCase("email");
BDDAssertions.then(customer.getId()).isEqualTo(1L);
}
@Test
public void saveShouldMapCorrectly() throws Exception {
Customer customer = new Customer(null, "first", "last", "[email protected]");
Customer saved = this.testEntityManager.persistFlushFind(customer);
BDDAssertions.then(saved.getId()).isNotNull();
BDDAssertions.then(saved.getFirstName()).isEqualToIgnoringCase("first");
BDDAssertions.then(saved.getFirstName()).isNotBlank();
BDDAssertions.then(saved.getLastName()).isEqualToIgnoringCase("last");
BDDAssertions.then(saved.getLastName()).isNotBlank();
BDDAssertions.then(saved.getEmail()).isEqualToIgnoringCase("[email protected]");
BDDAssertions.then(saved.getLastName()).isNotBlank();
}
@Test
public void repositorySaveShouldMapCorrectly() {
Customer customer = new Customer(null, "first", "last", "[email protected]");
Customer saved = this.repository.save(customer);
BDDAssertions.then(saved.getId()).isNotNull();
BDDAssertions.then(saved.getFirstName()).isEqualToIgnoringCase("first");
BDDAssertions.then(saved.getFirstName()).isNotBlank();
BDDAssertions.then(saved.getLastName()).isEqualToIgnoringCase("last");
BDDAssertions.then(saved.getLastName()).isNotBlank();
BDDAssertions.then(saved.getEmail()).isEqualToIgnoringCase("[email protected]");
BDDAssertions.then(saved.getLastName()).isNotBlank();
}
@Test
public void should_push_changes_to_current_branch() throws Exception {
File stubs = new File(
GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
this.updater.updateContractProject("hello-world", stubs.toPath());
// project, not origin, cause we're making one more clone of the local copy
try (Git git = openGitProject(this.project)) {
RevCommit revCommit = git.log().call().iterator().next();
then(revCommit.getShortMessage())
.isEqualTo("Updating project [hello-world] with stubs");
// I have no idea but the file gets deleted after pushing
git.reset().setMode(ResetCommand.ResetType.HARD).call();
}
BDDAssertions.then(new File(this.project,
"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
.exists();
BDDAssertions.then(this.gitRepo.gitFactory.provider).isNull();
BDDAssertions.then(this.outputCapture.toString())
.contains("No custom credentials provider will be set");
}
@Test
public void should_fail_to_perform_a_release_of_consul_when_sc_release_contains_snapshots()
throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release-with-snapshot/",
"vCamden.SR5.BROKEN");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
File project = cloneToTemporaryDirectory(tmpFile("spring-cloud-consul"));
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(this.runner,
properties("debug=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release-with-snapshot/")
.bomBranch("vCamden.SR5.BROKEN").expectedVersion("1.1.2.RELEASE")
.build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
BDDAssertions.thenThrownBy(releaser::release).hasMessageContaining(
"there is at least one SNAPSHOT library version in the Spring Cloud Release project");
});
}
@Test
void releaseGroup() {
ReleaserProperties properties = new ReleaserProperties();
properties.getMetaRelease().setReleaseGroups(Arrays.asList("c,d", "e,f,g"));
ProjectsToRun projectsToRun = projectsToRun();
List<ReleaseGroup> groups = new ProjectsToReleaseGroups(properties)
.toReleaseGroup(projectsToRun);
BDDAssertions.then(groups).hasSize(5);
BDDAssertions.then(projectNames(0, groups)).containsExactly("a");
BDDAssertions.then(projectNames(1, groups)).containsExactly("b");
BDDAssertions.then(projectNames(2, groups)).containsExactly("d", "c");
BDDAssertions.then(projectNames(3, groups)).containsExactly("e", "f", "g");
BDDAssertions.then(projectNames(4, groups)).containsExactly("h");
}
@Test
public void should_pick_stubs_from_a_given_location_for_a_find_producer_with_gav() {
String path = url.getPath();
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withStubRepositoryRoot("stubs://file://" + path)
.withProperties(propsWithFindProducer()).build();
StubsStubDownloader downloader = new StubsStubDownloader(options);
Map.Entry<StubConfiguration, File> entry = downloader
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring:cloud:bye"));
BDDAssertions.then(entry).isNotNull();
File stub = new File(entry.getValue().getPath(),
"lv/spring/cloud/bye/lv_bye.json");
BDDAssertions.then(stub).exists();
}
@Test
public void should_not_update_the_contents_of_wiki_repo_when_release_train_smaller()
throws GitAPIException, IOException {
this.properties.getMetaRelease().setEnabled(true);
this.properties.getGit().setUpdateReleaseTrainWiki(true);
this.properties.getGit()
.setReleaseTrainWikiUrl(this.wikiRepo.getAbsolutePath() + "/");
File file = this.updater.updateReleaseTrainWiki(oldReleaseTrain());
BDDAssertions.then(file).isNotNull();
BDDAssertions.then(edgwareWikiEntryContent(file)).doesNotContain("# Edgware.SR7")
.doesNotContain(
"Spring Cloud Consul `2.0.1.RELEASE` ([issues](http://www.foo.com/))");
BDDAssertions
.then(GitTestUtils.openGitProject(file).log().call().iterator().next()
.getShortMessage())
.doesNotContain("Updating project page to release train");
}
@Test
public void testHappyPathSaveConfigurationWithScheduler() {
// Set Up happy Path
final JobSchedulerConfiguration jobSchedulerConfiguration =
DomainTestHelper.createJobSchedulerConfiguration(null, 10L, 10L,
JobSchedulerType.PERIOD);
final JobConfiguration jobConfiguration = DomainTestHelper.createJobConfiguration(jobSchedulerConfiguration);
jobConfiguration.setJobName(JOB_NAME);
this.adminService.saveJobConfiguration(jobConfiguration);
Collection<JobConfiguration> jobConfigurationsByJobName = this.adminService.getJobConfigurationsByJobName(JOB_NAME);
BDDAssertions.assertThat(jobConfigurationsByJobName).hasSize(1);
Optional<JobConfiguration> optional = jobConfigurationsByJobName.stream().findFirst();
BDDAssertions.assertThat(optional).isPresent();
JobConfiguration jobConfigurationActual = optional.get();
BDDAssertions.assertThat(jobConfigurationActual.getJobConfigurationId()).isNotNull().isPositive();
JobSchedulerConfiguration jobSchedulerActual = jobConfigurationActual.getJobSchedulerConfiguration();
BDDAssertions.assertThat(jobSchedulerActual).isNotNull();
BDDAssertions.assertThat(jobSchedulerActual.getBeanName())
.as("Tests if Bean Name got generated Successfully. Ignore the UUID at the end.")
.isNotNull().startsWith(jobConfiguration.getJobName() + "-" + jobSchedulerConfiguration.getJobSchedulerType() + "-");
}
@Test
public void should_submit_trace_runnable() throws Exception {
AtomicBoolean executed = new AtomicBoolean();
Span span = this.tracer.nextSpan().name("foo");
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
this.traceAsyncListenableTaskExecutor
.submit(aRunnable(this.tracing, executed)).get();
}
finally {
span.finish();
}
Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
BDDAssertions.then(executed.get()).isTrue();
});
}
@Test
void should_add_filter_only_once_to_web_client_via_builder() {
TraceWebClientBeanPostProcessor processor = new TraceWebClientBeanPostProcessor(
this.springContext);
WebClient.Builder builder = WebClient.builder();
builder = (WebClient.Builder) processor.postProcessAfterInitialization(builder,
"foo");
builder = (WebClient.Builder) processor.postProcessAfterInitialization(builder,
"foo");
builder.build().mutate().filters(filters -> {
BDDAssertions.then(filters).hasSize(1);
BDDAssertions.then(filters.get(0))
.isInstanceOf(TraceExchangeFilterFunction.class);
});
}
@Test
void should_return_false_when_current_version_is_not_present_in_the_bom()
throws URISyntaxException {
ProjectVersion projectVersion = new ProjectVersion("spring-cloud-non-existant",
"1.0.0.RELEASE");
URI initilizrUri = VersionsFromBomFetcherTests.class
.getResource("/raw/initializr.yml").toURI();
ReleaserProperties properties = new ReleaserProperties();
properties.getGit().setUpdateSpringGuides(true);
properties.getVersions().setAllVersionsFileUrl(initilizrUri.toString());
properties.getGit().setReleaseTrainBomUrl(
file("/projects/spring-cloud-release/").toURI().toString());
ProjectPomUpdater updater = new ProjectPomUpdater(properties, new ArrayList<>());
VersionsFetcher versionsFetcher = new VersionsFetcher(properties, updater);
boolean latestGa = versionsFetcher.isLatestGa(projectVersion);
BDDAssertions.then(latestGa).isFalse();
}
private Callable<Boolean> applicationHasStartedOnANewPort(
final ConfigurableApplicationContext clientContext,
final Integer serverPortBeforeDying) {
return new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
BDDAssertions.then(callServiceAtPortEndpoint(clientContext))
.isNotEqualTo(serverPortBeforeDying);
}
catch (Exception e) {
log.error("Exception occurred while trying to call the server", e);
return false;
}
return true;
}
};
}
@Test
public void should_reuse_headers_only_from_input_since_exchange_may_contain_already_ignored_headers() {
HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("X-Hello", "World");
MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
.headers(httpHeaders).build();
MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();
HttpHeaders filteredHeaders = filter.filter(requestHeaders(), exchange);
BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
BDDAssertions.then(filteredHeaders.get("X-Hello")).isNullOrEmpty();
BDDAssertions
.then((Object) exchange
.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
.isNotNull();
}
@Ignore("flakey on circle")
@Test
public void should_update_project_and_run_tests_and_release_train_docs_generation_is_called() {
this.properties.getMetaRelease().setEnabled(true);
this.properties.getGit().setReleaseTrainDocsUrl(
tmpFile("spring-cloud-core-tests/").getAbsolutePath() + "/");
this.properties.getMaven().setGenerateReleaseTrainDocsCommand("./test.sh");
PostReleaseActions actions = new PostReleaseActions(this.projectGitHandler,
this.updater, this.gradleUpdater, this.commandExecutor, this.properties,
versionsFetcher, releaserPropertiesUpdater);
actions.generateReleaseTrainDocumentation(currentGa());
Model rootPom = PomReader.readPom(new File(this.cloned, "pom.xml"));
BDDAssertions.then(rootPom.getVersion()).isEqualTo("Finchley.SR1");
BDDAssertions.then(rootPom.getParent().getVersion()).isEqualTo("2.0.4.RELEASE");
BDDAssertions.then(sleuthParentPomVersion()).isEqualTo("2.0.4.RELEASE");
BDDAssertions.then(new File(this.cloned, "generate.log")).exists();
thenGradleUpdaterWasCalled();
}
@Test
public void should_delegate_work_to_other_stub_downloaders() {
EmptyStubDownloaderBuilder emptyStubDownloaderBuilder = new EmptyStubDownloaderBuilder();
ImpossibleToBuildStubDownloaderBuilder impossible = new ImpossibleToBuildStubDownloaderBuilder();
List<StubDownloaderBuilder> builders = Arrays.asList(emptyStubDownloaderBuilder,
impossible, new SomeStubDownloaderBuilder());
CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(
builders);
StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().build());
Map.Entry<StubConfiguration, File> entry = downloader
.downloadAndUnpackStubJar(new StubConfiguration("a:b:v"));
BDDAssertions.then(entry).isNotNull();
BDDAssertions.then(emptyStubDownloaderBuilder.downloaderCalled()).isTrue();
BDDAssertions.then(impossible.called).isTrue();
}
@Test
public void should_log_error_when_exception_thrown() throws IOException {
RuntimeException error = new RuntimeException("exception has occurred");
Span span = this.tracer.nextSpan().name("foo");
BDDMockito.given(this.client.execute(BDDMockito.any(), BDDMockito.any()))
.willThrow(error);
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
this.traceFeignClient.execute(this.request, this.options);
BDDAssertions.fail("Exception should have been thrown");
}
catch (Exception e) {
}
finally {
span.finish();
}
then(this.spans.get(0).kind()).isEqualTo(Span.Kind.CLIENT);
then(this.spans.get(0).error()).isSameAs(error);
}
@Test
public void testFindAll() {
final int count = 10;
for (int i = 0; i < count; i++) {
final JobExecutionEventInfo jobExecutionEventInfo =
ServerDomainHelper.createJobExecutionEventInfo();
getJobExecutionEventRepository().save(jobExecutionEventInfo);
}
final int totalCount = this.getJobExecutionEventRepository().getTotalCount();
final int fetchCount = 5;
final List<JobExecutionEventInfo> all0to5 = this.getJobExecutionEventRepository().findAll(0, fetchCount);
final List<JobExecutionEventInfo> all5to10 = this.getJobExecutionEventRepository().findAll(fetchCount, fetchCount);
BDDAssertions.then(totalCount).isEqualTo(count);
BDDAssertions.then(all0to5).hasSize(fetchCount);
BDDAssertions.then(all5to10).hasSize(fetchCount);
BDDAssertions.then(all5to10).doesNotContain(all0to5.toArray(new JobExecutionEventInfo[5]));
}
@Test
public void should_first_fail_then_succeed_to_process_tax_factor_for_person() throws ConnectException {
// given
willThrow(new ConnectException()).willNothing().given(taxFactorService).updateMeanTaxFactor(any(Person.class), anyDouble());
// when
when(systemUnderTest).processTaxDataFor(new Person());
// then
then(caughtException()).hasCauseInstanceOf(ConnectException.class);
// when
boolean success = systemUnderTest.processTaxDataFor(new Person());
// then
BDDAssertions.then(success).isTrue();
}
@Test
public void testdeleteById() throws SchedulerExecutionNotFoundException {
final SchedulerConfiguration schedulerConfiguration = this.createSchedulerConfiguration("deleteByIdApp");
final SchedulerExecution schedulerExecution = this.createSchedulerExecution(schedulerConfiguration.getId());
final SchedulerExecution result = this.getSchedulerExecutionRepository().findById(schedulerExecution.getId());
BDDAssertions.then(result).isEqualTo(schedulerExecution);
this.getSchedulerExecutionRepository().delete(result.getId());
try {
this.getSchedulerExecutionRepository().findById(result.getId());
fail("Exception not thrown!");
} catch (final SchedulerExecutionNotFoundException e) {
log.debug("Exception caught, every is fine", e);
}
}
@Test
public void should_not_finalize_the_delegate_since_its_a_shared_instance() {
AtomicBoolean wasCalled = new AtomicBoolean();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10) {
@Override
protected void finalize() {
super.finalize();
wasCalled.set(true);
}
};
BeanFactory beanFactory = BDDMockito.mock(BeanFactory.class);
new LazyTraceScheduledThreadPoolExecutor(10, beanFactory, executor).finalize();
BDDAssertions.then(wasCalled).isFalse();
BDDAssertions.then(executor.isShutdown()).isFalse();
}
@Test
public void allowsCustomization() {
this.contextRunner
.withPropertyValues("spring.sleuth.baggage.remote-fields=country-code")
.run((context) -> {
BDDAssertions.then(context.getBean(Propagation.Factory.class))
.extracting("delegate")
.isEqualTo(TraceBaggageConfiguration.B3_FACTORY);
});
}
@Test
public void newInstanceWithValidValuesShouldReturnARecord() {
Customer customer = new Customer(1L, "first", "last", "[email protected]");
BDDAssertions.then(customer.getFirstName()).isEqualToIgnoringCase("first");
BDDAssertions.then(customer.getLastName()).isEqualToIgnoringCase("last");
BDDAssertions.then(customer.getEmail()).isEqualToIgnoringCase("[email protected]");
BDDAssertions.then(customer.getId()).isNotNull();
}
@Test
public void should_give_me_a_beer_when_im_old_enough() throws Exception {
//remove::start[]
Beer.Response response = this.restTemplate.postForObject(
"http://localhost:" + this.port + "/check",
Beer.PersonToCheck.newBuilder().setAge(23).build(), Beer.Response.class);
BDDAssertions.then(response.getStatus()).isEqualTo(Beer.Response.BeerCheckStatus.OK);
// remove::end[]
}
@Test
public void should_override_span_tracing_headers() {
HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("X-Hello", "World");
httpHeaders.set("X-B3-TraceId", "52f112af7472aff0");
httpHeaders.set("X-B3-SpanId", "53e6ab6fc5dfee58");
MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
.headers(httpHeaders).build();
MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();
HttpHeaders filteredHeaders = filter.filter(requestHeaders(httpHeaders),
exchange);
// we want to continue the trace
BDDAssertions.then(filteredHeaders.get("X-B3-TraceId"))
.isEqualTo(httpHeaders.get("X-B3-TraceId"));
// but we want to have a new span id
BDDAssertions.then(filteredHeaders.get("X-B3-SpanId"))
.isNotEqualTo(httpHeaders.get("X-B3-SpanId"));
BDDAssertions.then(filteredHeaders.get("X-Hello"))
.isEqualTo(Collections.singletonList("World"));
BDDAssertions.then(filteredHeaders.get("X-Hello-Request"))
.isEqualTo(Collections.singletonList("Request World"));
BDDAssertions.then(filteredHeaders.get("X-Auth-User")).hasSize(1);
BDDAssertions
.then((Object) exchange
.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
.isNotNull();
}
@Test
public void testGetJobConfigurationModel() {
final LightminClientApplication lightminClientApplication = ServiceTestHelper.createLightminClientApplication();
when(this.registrationBean.findById(APPLICATION_INSTANCE_ID)).thenReturn(lightminClientApplication);
final JobConfiguration jobConfiguration = ApiTestHelper.createJobConfiguration(
ApiTestHelper.createJobListenerConfiguration("/", "*.txt", JobListenerType.LOCAL_FOLDER_LISTENER));
when(this.adminServerService.getJobConfiguration(JC_ID, lightminClientApplication)).thenReturn(jobConfiguration);
final ListenerJobConfigurationModel result =
this.jobListenerFeService.getJobConfigurationModel(JC_ID, APPLICATION_INSTANCE_ID);
BDDAssertions.then(result).isNotNull();
}
@Test
public void APPLICATION_JSON_UTF8() {
BDDAssertions.then(MediaTypes.APPLICATION_JSON_UTF8)
.isEqualTo("application/json;charset=UTF-8");
BDDAssertions.then(new MediaTypes().applicationJsonUtf8())
.isEqualTo(MediaTypes.APPLICATION_JSON_UTF8);
}
@Test
public void testSaveUpdateSchedulerConfigurationWithOutRetry() {
final SchedulerConfiguration schedulerConfiguration = this.createSchedulerConfiguration("saveApp", Boolean.FALSE);
schedulerConfiguration.setCronExpression("changed");
final SchedulerConfiguration updated = this.getSchedulerConfigurationRepository().save(schedulerConfiguration);
BDDAssertions.then(updated.getId()).isEqualTo(schedulerConfiguration.getId());
BDDAssertions.then(updated.getCronExpression()).isEqualTo("changed");
}
@Test
void should_not_fail_the_release_when_project_post_release_task_fails(
@Autowired SpringBatchFlowRunner runner) {
Options options = new OptionsBuilder().interactive(false).options();
ProjectsToRun projectsToRun = projectsToRun(options, releaserProperties);
TasksToRun tasks = new TasksToRun(new MyProjectPostReleaseTask());
ExecutionResult executionResult = runner.runReleaseTasks(options,
releaserProperties, projectsToRun, tasks);
BDDAssertions.then(executionResult.isUnstable()).isTrue();
}
@Test
public void testSave() {
final JobExecutionEventInfo jobExecutionEventInfo =
ServerDomainHelper.createJobExecutionEventInfo();
final JobExecutionEventInfo saved = getJobExecutionEventRepository().save(jobExecutionEventInfo);
final int totalCount = this.getJobExecutionEventRepository().getTotalCount();
final List<JobExecutionEventInfo> all = this.getJobExecutionEventRepository().findAll(0, totalCount);
BDDAssertions.then(totalCount).isEqualTo(1);
BDDAssertions.then(all).hasSize(1);
BDDAssertions.then(all).contains(saved);
}