Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

Commit

Permalink
Use lambda expressions where possible (test)
Browse files Browse the repository at this point in the history
  • Loading branch information
cbeams committed Apr 10, 2014
1 parent 65b20aa commit 3718f64
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 103 deletions.
Expand Up @@ -55,13 +55,10 @@ public class BlogService_ValidPostTests {
public void setup() {
given(dateFactory.now()).willReturn(now);

given(postRepository.save((Post) anyObject())).will(new Answer<Post>() {
@Override
public Post answer(InvocationOnMock invocation) throws Throwable {
Post post = (Post) invocation.getArguments()[0];
ReflectionTestUtils.setField(post, "id", 123L);
return post;
}
given(postRepository.save((Post) anyObject())).will(invocation -> {
Post post = (Post) invocation.getArguments()[0];
ReflectionTestUtils.setField(post, "id", 123L);
return post;
});

post = PostBuilder.post().publishAt(publishAt).build();
Expand Down
Expand Up @@ -17,19 +17,12 @@ public class GuideSearchEntryMapperTests {

private Guide guide = new GettingStartedGuide(
new DefaultGuideMetadata("my-org", "xyz", "gs-xyz", "Guide XYZ Title::Guide XYZ Subtitle"),
new ContentProvider<GettingStartedGuide>() {
@Override
public void populate(GettingStartedGuide guide) {
guide.setContent("Some Guide Content");
guide.setSidebar("Some Sidebar Content");
}
(ContentProvider<GettingStartedGuide>) (gsg) -> {
gsg.setContent("Some Guide Content");
gsg.setSidebar("Some Sidebar Content");
},
new ImageProvider() {
@Override
public byte[] loadImage(Guide guide, String imageName) {
return new byte[0];
}
});
(gsg, imageName) -> new byte[0]
);

private GuideSearchEntryMapper guideMapper = new GuideSearchEntryMapper();
private SearchEntry searchEntry;
Expand Down
Expand Up @@ -19,12 +19,9 @@
public class UnderstandingDocMapperTests {

private final UnderstandingDocMapper mapper = new UnderstandingDocMapper();
private final UnderstandingDoc doc = new UnderstandingDoc("foo", new ContentProvider<UnderstandingDoc>() {
@Override
public void populate(UnderstandingDoc doc) {
doc.setContent("<h1>Understanding: foo</h1><p>content</p>");
doc.setSidebar("<p>sidebar</p>");
}
private final UnderstandingDoc doc = new UnderstandingDoc("foo", udoc -> {
udoc.setContent("<h1>Understanding: foo</h1><p>content</p>");
udoc.setSidebar("<p>sidebar</p>");
});
private final SearchEntry entry = mapper.map(doc);

Expand Down
Expand Up @@ -45,10 +45,7 @@ public void blogServiceIsAdvisedForCaching() {
}
}
assertTrue("BlogService is advised, but does not have caching advisor", hasCachingAdvisor);
// @formatter:off
ReflectionUtils.doWithMethods(BlogService.class, new ReflectionUtils.MethodCallback() { // TODO: lambda
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.doWithMethods(BlogService.class, (method) -> {
Cacheable cacheable = AnnotationUtils.findAnnotation(method, Cacheable.class);
String methodName = method.getName();
if (methodName.matches("^get.*Published.*$")) {
Expand All @@ -58,9 +55,7 @@ public void doWith(Method method) throws IllegalArgumentException, IllegalAccess
} else {
assertNull("Method " + methodName + " was not expected to have Cacheable annotation.", cacheable);
}
}
});
// @formatter:on
});
}

}
18 changes: 5 additions & 13 deletions sagan-site/src/it/java/sagan/blog/support/CreateBlogPostTests.java
Expand Up @@ -51,12 +51,7 @@ public void setup() {

final Long profileId = profile.getId();

principal = new Principal() {
@Override
public String getName() {
return profileId.toString();
}
};
principal = profileId::toString;
mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.addFilters(springSecurityFilterChain)
.defaultRequest(get("/").with(csrf()).with(user(profileId).roles("USER"))).build();
Expand Down Expand Up @@ -87,13 +82,10 @@ public void redirectToPublishedPostAfterCreation() throws Exception {

mockMvc.perform(createPostRequest)
.andExpect(status().isFound())
.andExpect(new ResultMatcher() {
@Override
public void match(MvcResult result) {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertTrue("Expected redirect to /blog/2013/07/01/post-title, got: " + redirectedUrl,
redirectedUrl.matches("^/blog/2013/07/01/post-title"));
}
.andExpect(result -> {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertTrue("Expected redirect to /blog/2013/07/01/post-title, got: " + redirectedUrl,
redirectedUrl.matches("^/blog/2013/07/01/post-title"));
});
}

Expand Down
Expand Up @@ -52,12 +52,9 @@ public void redirectToIndexAfterDelete() throws Exception {

mockMvc.perform(editPostRequest)
.andExpect(status().isFound())
.andExpect(new ResultMatcher() {
@Override
public void match(MvcResult result) {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertThat(redirectedUrl, startsWith("/admin/blog"));
}
.andExpect(result -> {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertThat(redirectedUrl, startsWith("/admin/blog"));
});
}

Expand Down
Expand Up @@ -65,12 +65,9 @@ public void redirectToPublishedPostAfterUpdate() throws Exception {

mockMvc.perform(editPostRequest)
.andExpect(status().isFound())
.andExpect(new ResultMatcher() {
@Override
public void match(MvcResult result) {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertThat(redirectedUrl, startsWith("/blog/" + post.getPublicSlug()));
}
.andExpect(result -> {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertThat(redirectedUrl, startsWith("/blog/" + post.getPublicSlug()));
});
}

Expand Down
16 changes: 4 additions & 12 deletions sagan-site/src/it/java/sagan/team/support/EditTeamMemberTests.java
Expand Up @@ -50,12 +50,7 @@ public void setup() {

final MemberProfile memberProfile = teamRepository.save(existingProfile);

principal = new Principal() {
@Override
public String getName() {
return memberProfile.getId().toString();
}
};
principal = () -> memberProfile.getId().toString();
mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.addFilters(springSecurityFilterChain)
.defaultRequest(get("/").with(csrf()).with(user(memberProfile.getId()).roles("USER"))).build();
Expand Down Expand Up @@ -132,12 +127,9 @@ private void saveProfile(String editTeamUri) throws Exception {
private void performRequestAndExpectRedirect(MockHttpServletRequestBuilder requestBuilder,
final String expectedRedirectUrl) throws Exception {
mockMvc.perform(requestBuilder)
.andExpect(new ResultMatcher() {
@Override
public void match(MvcResult result) {
String redirectedUrl = result.getResponse().getRedirectedUrl();
MatcherAssert.assertThat(redirectedUrl, startsWith(expectedRedirectUrl));
}
.andExpect(result -> {
String redirectedUrl = result.getResponse().getRedirectedUrl();
MatcherAssert.assertThat(redirectedUrl, startsWith(expectedRedirectUrl));
});
}

Expand Down
Expand Up @@ -3,8 +3,6 @@
import sagan.DatabaseConfig;
import saganx.AbstractIntegrationTests;

import java.lang.reflect.Method;

import org.junit.Test;

import org.springframework.aop.Advisor;
Expand Down Expand Up @@ -45,22 +43,17 @@ public void teamServiceIsAdvisedForCaching() {
}
}
assertTrue("TeamService is advised, but does not have caching advisor", hasCachingAdvisor);
// @formatter:off
ReflectionUtils.doWithMethods(TeamService.class, new ReflectionUtils.MethodCallback() { // TODO: lambda
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Cacheable cacheable = AnnotationUtils.findAnnotation(method, Cacheable.class);
String methodName = method.getName();
if (methodName.equals("fetchMemberProfileUsername") || methodName.equals("fetchActiveMembers")) {
assertNotNull("Method " + methodName + " was expected to have Cacheable annotation.", cacheable);
String[] cacheName = cacheable.value();
assertThat(cacheName[0], equalTo(DatabaseConfig.CACHE_NAME));
} else {
assertNull("Method " + methodName + " was not expected to have Cacheable annotation.", cacheable);
}
ReflectionUtils.doWithMethods(TeamService.class, method -> {
Cacheable cacheable = AnnotationUtils.findAnnotation(method, Cacheable.class);
String methodName = method.getName();
if (methodName.equals("fetchMemberProfileUsername") || methodName.equals("fetchActiveMembers")) {
assertNotNull("Method " + methodName + " was expected to have Cacheable annotation.", cacheable);
String[] cacheName = cacheable.value();
assertThat(cacheName[0], equalTo(DatabaseConfig.CACHE_NAME));
} else {
assertNull("Method " + methodName + " was not expected to have Cacheable annotation.", cacheable);
}
});
// @formatter:on
}

}
9 changes: 3 additions & 6 deletions sagan-site/src/it/java/saganx/AuthenticationTests.java
Expand Up @@ -104,12 +104,9 @@ public void signoutRedirectsToTheHomePage() throws Exception {

mockMvc.perform(get("/signout"))
.andExpect(status().isFound())
.andExpect(new ResultMatcher() {
@Override
public void match(MvcResult result) {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertThat(redirectedUrl, equalTo("/"));
}
.andExpect(result -> {
String redirectedUrl = result.getResponse().getRedirectedUrl();
assertThat(redirectedUrl, equalTo("/"));
});
}
}
8 changes: 2 additions & 6 deletions sagan-site/src/it/java/saganx/BasicAcceptanceTests.java
Expand Up @@ -43,12 +43,8 @@ public static void start() throws Exception {
serverAddress = "http://localhost:" + port;

Future<ConfigurableApplicationContext> future =
Executors.newSingleThreadExecutor().submit(new Callable<ConfigurableApplicationContext>() {
@Override
public ConfigurableApplicationContext call() throws Exception {
return SpringApplication.run(IntegrationTestsConfig.class, "--server.port=" + port);
}
});
Executors.newSingleThreadExecutor().submit(() ->
SpringApplication.run(IntegrationTestsConfig.class, "--server.port=" + port));
context = future.get(30, TimeUnit.SECONDS);
}

Expand Down
Expand Up @@ -59,12 +59,7 @@ public class BlogAdminControllerTests {
public void setup() {
bindingResult = new MapBindingResult(new HashMap<>(), "postForm");
postViewFactory = new PostViewFactory(new DateFactory());
principal = new Principal() {
@Override
public String getName() {
return "12345";
}
};
principal = () -> "12345";

controller = new BlogAdminController(blogService, postViewFactory, teamRepository);
}
Expand Down

0 comments on commit 3718f64

Please sign in to comment.