formatting work

This commit is contained in:
Eugen Paraschiv 2018-03-04 17:53:14 +02:00
parent 5fd8e4293e
commit 8d633d6402
48 changed files with 101 additions and 248 deletions

View File

@ -9,8 +9,7 @@ public class AttrListener implements ServletContextListener {
@Override @Override
public void contextInitialized(ServletContextEvent servletContextEvent) { public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext() servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test");
.setAttribute("servlet-context-attr", "test");
System.out.println("context init"); System.out.println("context init");
} }

View File

@ -16,8 +16,7 @@ public class EchoServlet extends HttpServlet {
@Override @Override
public void doPost(HttpServletRequest request, HttpServletResponse response) { public void doPost(HttpServletRequest request, HttpServletResponse response) {
try { try {
Path path = File.createTempFile("echo", "tmp") Path path = File.createTempFile("echo", "tmp").toPath();
.toPath();
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
Files.copy(path, response.getOutputStream()); Files.copy(path, response.getOutputStream());
Files.delete(path); Files.delete(path);

View File

@ -18,8 +18,7 @@ public class HelloFilter implements Filter {
@Override @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.getOutputStream() servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg"));
.print(filterConfig.getInitParameter("msg"));
filterChain.doFilter(servletRequest, servletResponse); filterChain.doFilter(servletRequest, servletResponse);
} }

View File

@ -21,9 +21,7 @@ public class HelloServlet extends HttpServlet {
@Override @Override
public void doGet(HttpServletRequest request, HttpServletResponse response) { public void doGet(HttpServletRequest request, HttpServletResponse response) {
try { try {
response.getOutputStream() response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes());
.write(servletConfig.getInitParameter("msg")
.getBytes());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -98,13 +98,8 @@ public class MySQLAutoconfiguration {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
return Arrays.stream(CLASS_NAMES) return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
.filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
.map(className -> ConditionOutcome.match(message.found("class")
.items(Style.NORMAL, className)))
.findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes")
.items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
} }
} }

View File

@ -28,9 +28,7 @@ public class ContactInfoValidator implements ConstraintValidator<ContactInfo, St
if (StringUtils.isEmptyOrWhitespace(expressionType)) { if (StringUtils.isEmptyOrWhitespace(expressionType)) {
LOG.error("Contact info type missing!"); LOG.error("Contact info type missing!");
} else { } else {
pattern = expressionRepository.findOne(expressionType) pattern = expressionRepository.findOne(expressionType).map(ContactInfoExpression::getPattern).orElse("");
.map(ContactInfoExpression::getPattern)
.orElse("");
} }
} }

View File

@ -18,10 +18,7 @@ public class PersistenceConfig {
@Bean @Bean
public DataSource dataSource() { public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2) EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build();
.addScript("schema-expressions.sql")
.addScript("data-expressions.sql")
.build();
return db; return db;
} }
} }

View File

@ -12,15 +12,11 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnaly
} }
private String getDescription(BeanNotOfRequiredTypeException ex) { private String getDescription(BeanNotOfRequiredTypeException ex) {
return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType() return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType().getName(), ex.getActualType().getName());
.getName(),
ex.getActualType()
.getName());
} }
private String getAction(BeanNotOfRequiredTypeException ex) { private String getAction(BeanNotOfRequiredTypeException ex) {
return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType() return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType().getName());
.getName());
} }
} }

View File

@ -11,8 +11,6 @@ public class AuthorDao {
} }
public Optional<Author> getAuthor(String id) { public Optional<Author> getAuthor(String id) {
return authors.stream() return authors.stream().filter(author -> id.equals(author.getId())).findFirst();
.filter(author -> id.equals(author.getId()))
.findFirst();
} }
} }

View File

@ -13,8 +13,7 @@ public class Mutation implements GraphQLMutationResolver {
public Post writePost(String title, String text, String category, String author) { public Post writePost(String title, String text, String category, String author) {
Post post = new Post(); Post post = new Post();
post.setId(UUID.randomUUID() post.setId(UUID.randomUUID().toString());
.toString());
post.setTitle(title); post.setTitle(title);
post.setText(text); post.setText(text);
post.setCategory(category); post.setCategory(category);

View File

@ -11,16 +11,11 @@ public class PostDao {
} }
public List<Post> getRecentPosts(int count, int offset) { public List<Post> getRecentPosts(int count, int offset) {
return posts.stream() return posts.stream().skip(offset).limit(count).collect(Collectors.toList());
.skip(offset)
.limit(count)
.collect(Collectors.toList());
} }
public List<Post> getAuthorPosts(String author) { public List<Post> getAuthorPosts(String author) {
return posts.stream() return posts.stream().filter(post -> author.equals(post.getAuthorId())).collect(Collectors.toList());
.filter(post -> author.equals(post.getAuthorId()))
.collect(Collectors.toList());
} }
public void savePost(Post post) { public void savePost(Post post) {

View File

@ -24,9 +24,8 @@ public class QueryController {
REQUEST_COUNTER++; REQUEST_COUNTER++;
if ("BTC".equalsIgnoreCase(code)) if ("BTC".equalsIgnoreCase(code))
return "10000"; return "10000";
else return "N/A"; else
return "N/A";
} }
} }

View File

@ -28,11 +28,7 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**") registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
.addResourceLocations("/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
} }
@Bean @Bean

View File

@ -13,7 +13,6 @@ public class AnnotationServlet extends HttpServlet {
@Override @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/annotationservlet.jsp") request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response);
.forward(request, response);
} }
} }

View File

@ -14,12 +14,10 @@ public class FeaturesAspect {
@Around(value = "@within(featureAssociation) || @annotation(featureAssociation)") @Around(value = "@within(featureAssociation) || @annotation(featureAssociation)")
public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable { public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable {
if (featureAssociation.value() if (featureAssociation.value().isActive()) {
.isActive()) {
return joinPoint.proceed(); return joinPoint.proceed();
} else { } else {
LOG.info("Feature " + featureAssociation.value() LOG.info("Feature " + featureAssociation.value().name() + " is not enabled!");
.name() + " is not enabled!");
return null; return null;
} }
} }

View File

@ -17,8 +17,7 @@ public enum MyFeatures implements Feature {
EMPLOYEE_MANAGEMENT_FEATURE; EMPLOYEE_MANAGEMENT_FEATURE;
public boolean isActive() { public boolean isActive() {
return FeatureContext.getFeatureManager() return FeatureContext.getFeatureManager().isActive(this);
.isActive(this);
} }
} }

View File

@ -39,31 +39,21 @@ public class GenericEntityController {
@RequestMapping("/entity/findby/{id}") @RequestMapping("/entity/findby/{id}")
public GenericEntity findById(@PathVariable Long id) { public GenericEntity findById(@PathVariable Long id) {
return entityList.stream() return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
.filter(entity -> entity.getId()
.equals(id))
.findFirst()
.get();
} }
@GetMapping("/entity/findbydate/{date}") @GetMapping("/entity/findbydate/{date}")
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
return entityList.stream() return entityList.stream().findFirst().get();
.findFirst()
.get();
} }
@GetMapping("/entity/findbymode/{mode}") @GetMapping("/entity/findbymode/{mode}")
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
return entityList.stream() return entityList.stream().findFirst().get();
.findFirst()
.get();
} }
@GetMapping("/entity/findbyversion") @GetMapping("/entity/findbyversion")
public ResponseEntity findByVersion(@Version String version) { public ResponseEntity findByVersion(@Version String version) {
return version != null ? new ResponseEntity(entityList.stream() return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
.findFirst()
.get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
} }
} }

View File

@ -11,16 +11,13 @@ public class GenericBigDecimalConverter implements GenericConverter {
@Override @Override
public Set<ConvertiblePair> getConvertibleTypes() { public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair[] pairs = new ConvertiblePair[] { ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) };
new ConvertiblePair(Number.class, BigDecimal.class),
new ConvertiblePair(String.class, BigDecimal.class)};
return ImmutableSet.copyOf(pairs); return ImmutableSet.copyOf(pairs);
} }
@Override @Override
public Object convert (Object source, TypeDescriptor sourceType, public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
TypeDescriptor targetType) {
if (sourceType.getType() == BigDecimal.class) { if (sourceType.getType() == BigDecimal.class) {
return source; return source;
} }

View File

@ -1,6 +1,5 @@
package org.baeldung.boot.converter; package org.baeldung.boot.converter;
import com.baeldung.toggle.Employee; import com.baeldung.toggle.Employee;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;

View File

@ -36,8 +36,7 @@ public class UserCombinedSerializer {
public static class UserJsonDeserializer extends JsonDeserializer<User> { public static class UserJsonDeserializer extends JsonDeserializer<User> {
@Override @Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
TreeNode treeNode = jsonParser.getCodec() TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
.readTree(jsonParser);
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
return new User(Color.web(favoriteColor.asText())); return new User(Color.web(favoriteColor.asText()));
} }

View File

@ -15,8 +15,7 @@ import java.io.IOException;
public class UserJsonDeserializer extends JsonDeserializer<User> { public class UserJsonDeserializer extends JsonDeserializer<User> {
@Override @Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
TreeNode treeNode = jsonParser.getCodec() TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
.readTree(jsonParser);
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
return new User(Color.web(favoriteColor.asText())); return new User(Color.web(favoriteColor.asText()));
} }

View File

@ -14,8 +14,7 @@ public class MonitoringConfig {
@Bean @Bean
public JmxReporter jmxReporter() { public JmxReporter jmxReporter() {
JmxReporter reporter = JmxReporter.forRegistry(registry) JmxReporter reporter = JmxReporter.forRegistry(registry).build();
.build();
reporter.start(); reporter.start();
return reporter; return reporter;
} }

View File

@ -10,13 +10,9 @@ public class MyHealthCheck implements HealthIndicator {
public Health health() { public Health health() {
int errorCode = check(); // perform some specific health check int errorCode = check(); // perform some specific health check
if (errorCode != 0) { if (errorCode != 0) {
return Health.down() return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build();
.withDetail("Error Code", errorCode)
.withDetail("Description", "You custom MyHealthCheck endpoint is down")
.build();
} }
return Health.up() return Health.up().build();
.build();
} }
public int check() { public int check() {

View File

@ -16,8 +16,7 @@ public class LoginServiceImpl implements LoginService {
public boolean login(String userName, char[] password) { public boolean login(String userName, char[] password) {
boolean success; boolean success;
if (userName.equals("admin") && "secret".toCharArray() if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
.equals(password)) {
counterService.increment("counter.login.success"); counterService.increment("counter.login.success");
success = true; success = true;
} else { } else {

View File

@ -14,14 +14,12 @@ public class FooRepositoryImpl implements FooRepository {
@Override @Override
public void save(Foo foo) { public void save(Foo foo) {
sessionFactory.getCurrentSession() sessionFactory.getCurrentSession().saveOrUpdate(foo);
.saveOrUpdate(foo);
} }
@Override @Override
public Foo get(Integer id) { public Foo get(Integer id) {
return sessionFactory.getCurrentSession() return sessionFactory.getCurrentSession().get(Foo.class, id);
.get(Foo.class, id);
} }
} }

View File

@ -40,8 +40,7 @@ public class SpringBootWithServletComponentIntegrationTest {
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration); assertNotNull(filterRegistration);
assertTrue(filterRegistration.getServletNameMappings() assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet"));
.contains("echo servlet"));
} }
@Autowired @Autowired

View File

@ -60,11 +60,8 @@ public class DisplayBeanIntegrationTest {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class);
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody() List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans");
.get(0)).get("beans"); List<String> beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList());
List<String> beanNamesList = allBeans.stream()
.map(x -> (String) x.get("bean"))
.collect(Collectors.toList());
assertThat(beanNamesList, hasItem("fooController")); assertThat(beanNamesList, hasItem("fooController"));
assertThat(beanNamesList, hasItem("fooService")); assertThat(beanNamesList, hasItem("fooService"));

View File

@ -26,18 +26,12 @@ public class AppLiveTest {
@Test @Test
public void getIndex() throws Exception { public void getIndex() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/") mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page")));
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Index Page")));
} }
@Test @Test
public void getLocal() throws Exception { public void getLocal() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/local") mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local")));
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("/local")));
} }
} }

View File

@ -39,7 +39,8 @@ public class KongAdminAPILiveTest {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
} }
@Autowired TestRestTemplate restTemplate; @Autowired
TestRestTemplate restTemplate;
@Test @Test
public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() { public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() {

View File

@ -30,7 +30,8 @@ public class KongLoadBalanceLiveTest {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
} }
@Autowired TestRestTemplate restTemplate; @Autowired
TestRestTemplate restTemplate;
@Test @Test
public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {

View File

@ -35,8 +35,7 @@ public class ToggleIntegrationTest {
@Before @Before
public void setup() { public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
.build();
} }
@Test @Test
@ -46,8 +45,7 @@ public class ToggleIntegrationTest {
System.setProperty("employee.feature", "false"); System.setProperty("employee.feature", "false");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
.andExpect(status().is(200));
emp = employeeRepository.findOne(1L); emp = employeeRepository.findOne(1L);
assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
@ -60,8 +58,7 @@ public class ToggleIntegrationTest {
System.setProperty("employee.feature", "true"); System.setProperty("employee.feature", "true");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
.andExpect(status().is(200));
emp = employeeRepository.findOne(1L); emp = employeeRepository.findOne(1L);
assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);

View File

@ -21,17 +21,14 @@ public class UtilsControllerIntegrationTest {
@Before @Before
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build();
.build();
} }
@Test @Test
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
String param = "testparam"; String param = "testparam";
this.mockMvc.perform(post("/setParam").param("param", param) this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk());
.sessionAttr("parameter", param))
.andExpect(status().isOk());
} }
} }

View File

@ -14,9 +14,7 @@ public class MyStompSessionHandlerIntegrationTest {
StompHeaders mockHeader = Mockito.mock(StompHeaders.class); StompHeaders mockHeader = Mockito.mock(StompHeaders.class);
MyStompSessionHandler sessionHandler = new MyStompSessionHandler(); MyStompSessionHandler sessionHandler = new MyStompSessionHandler();
sessionHandler.afterConnected(mockSession, mockHeader); sessionHandler.afterConnected(mockSession, mockHeader);
Mockito.verify(mockSession) Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler);
.subscribe("/topic/messages", sessionHandler); Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject());
Mockito.verify(mockSession)
.send(Mockito.anyString(), Mockito.anyObject());
} }
} }

View File

@ -34,31 +34,21 @@ public class SpringBootApplicationIntegrationTest {
@Before @Before
public void setupMockMvc() { public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
.build();
} }
@Test @Test
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")) mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$", hasSize(4)));
} }
@Test @Test
public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")) mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1))); .andExpect(jsonPath("$.id", equalTo(1)));
} }
@ -66,24 +56,14 @@ public class SpringBootApplicationIntegrationTest {
public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())) mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1)));
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
} }
@Test @Test
public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion") mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.header("Version", "1.0.0"))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1))); .andExpect(jsonPath("$.id", equalTo(1)));
} }
} }

View File

@ -61,15 +61,11 @@ public class SpringBootMailIntegrationTest {
} }
private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException {
return wiserMessage.getMimeMessage() return wiserMessage.getMimeMessage().getContent().toString().trim();
.getContent()
.toString()
.trim();
} }
private String getSubject(WiserMessage wiserMessage) throws MessagingException { private String getSubject(WiserMessage wiserMessage) throws MessagingException {
return wiserMessage.getMimeMessage() return wiserMessage.getMimeMessage().getSubject();
.getSubject();
} }
private SimpleMailMessage composeEmailMessage() { private SimpleMailMessage composeEmailMessage() {

View File

@ -33,8 +33,7 @@ public class DetailsServiceClientIntegrationTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
this.server.expect(requestTo("/john/details")) this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
.andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
} }
@Test @Test

View File

@ -33,8 +33,7 @@ public class CustomConverterIntegrationTest {
public void whenConvertStringToEmployee_thenSuccess() { public void whenConvertStringToEmployee_thenSuccess() {
Employee employee = conversionService.convert("1,50000.00", Employee.class); Employee employee = conversionService.convert("1,50000.00", Employee.class);
Employee actualEmployee = new Employee(1, 50000.00); Employee actualEmployee = new Employee(1, 50000.00);
assertThat(conversionService.convert("1,50000.00", Employee.class)) assertThat(conversionService.convert("1,50000.00", Employee.class)).isEqualToComparingFieldByField(actualEmployee);
.isEqualToComparingFieldByField(actualEmployee);
} }
@Test @Test
@ -44,11 +43,8 @@ public class CustomConverterIntegrationTest {
@Test @Test
public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() { public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() {
assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)) assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN));
.isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN)); assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)) assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32));
.isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
assertThat(conversionService.convert("2.32", BigDecimal.class))
.isEqualTo(BigDecimal.valueOf(2.32));
} }
} }

View File

@ -26,10 +26,6 @@ public class StringToEmployeeConverterControllerIntegrationTest {
@Test @Test
public void getStringToEmployeeTest() throws Exception { public void getStringToEmployeeTest() throws Exception {
mockMvc.perform(get("/string-to-employee?employee=1,2000")) mockMvc.perform(get("/string-to-employee?employee=1,2000")).andDo(print()).andExpect(jsonPath("$.id", is(1))).andExpect(jsonPath("$.salary", is(2000.0))).andExpect(status().isOk());
.andDo(print())
.andExpect(jsonPath("$.id", is(1)))
.andExpect(jsonPath("$.salary", is(2000.0)))
.andExpect(status().isOk());
} }
} }

View File

@ -47,10 +47,7 @@ public class EmployeeControllerIntegrationTest {
Employee alex = new Employee("alex"); Employee alex = new Employee("alex");
given(service.save(Mockito.anyObject())).willReturn(alex); given(service.save(Mockito.anyObject())).willReturn(alex);
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex")));
.content(JsonUtil.toJson(alex)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name", is("alex")));
verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject());
reset(service); reset(service);
} }
@ -65,11 +62,7 @@ public class EmployeeControllerIntegrationTest {
given(service.getAllEmployees()).willReturn(allEmployees); given(service.getAllEmployees()).willReturn(allEmployees);
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is(alex.getName()))).andExpect(jsonPath("$[1].name", is(john.getName())))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[0].name", is(alex.getName())))
.andExpect(jsonPath("$[1].name", is(john.getName())))
.andExpect(jsonPath("$[2].name", is(bob.getName()))); .andExpect(jsonPath("$[2].name", is(bob.getName())));
verify(service, VerificationModeFactory.times(1)).getAllEmployees(); verify(service, VerificationModeFactory.times(1)).getAllEmployees();
reset(service); reset(service);

View File

@ -66,8 +66,6 @@ public class EmployeeRepositoryIntegrationTest {
List<Employee> allEmployees = employeeRepository.findAll(); List<Employee> allEmployees = employeeRepository.findAll();
assertThat(allEmployees).hasSize(3) assertThat(allEmployees).hasSize(3).extracting(Employee::getName).containsOnly(alex.getName(), ron.getName(), bob.getName());
.extracting(Employee::getName)
.containsOnly(alex.getName(), ron.getName(), bob.getName());
} }
} }

View File

@ -50,12 +50,10 @@ public class EmployeeRestControllerIntegrationTest {
@Test @Test
public void whenValidInput_thenCreateEmployee() throws IOException, Exception { public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
Employee bob = new Employee("bob"); Employee bob = new Employee("bob");
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(bob)));
.content(JsonUtil.toJson(bob)));
List<Employee> found = repository.findAll(); List<Employee> found = repository.findAll();
assertThat(found).extracting(Employee::getName) assertThat(found).extracting(Employee::getName).containsOnly("bob");
.containsOnly("bob");
} }
@Test @Test
@ -64,13 +62,8 @@ public class EmployeeRestControllerIntegrationTest {
createTestEmployee("bob"); createTestEmployee("bob");
createTestEmployee("alex"); createTestEmployee("alex");
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
.andDo(print()) .andExpect(jsonPath("$[0].name", is("bob"))).andExpect(jsonPath("$[1].name", is("alex")));
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
.andExpect(jsonPath("$[0].name", is("bob")))
.andExpect(jsonPath("$[1].name", is("alex")));
} }
private void createTestEmployee(String name) { private void createTestEmployee(String name) {

View File

@ -47,18 +47,12 @@ public class EmployeeServiceImplIntegrationTest {
List<Employee> allEmployees = Arrays.asList(john, bob, alex); List<Employee> allEmployees = Arrays.asList(john, bob, alex);
Mockito.when(employeeRepository.findByName(john.getName())) Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
.thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
Mockito.when(employeeRepository.findByName(alex.getName())) Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
.thenReturn(alex); Mockito.when(employeeRepository.findById(john.getId())).thenReturn(john);
Mockito.when(employeeRepository.findByName("wrong_name")) Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
.thenReturn(null); Mockito.when(employeeRepository.findById(-99L)).thenReturn(null);
Mockito.when(employeeRepository.findById(john.getId()))
.thenReturn(john);
Mockito.when(employeeRepository.findAll())
.thenReturn(allEmployees);
Mockito.when(employeeRepository.findById(-99L))
.thenReturn(null);
} }
@Test @Test
@ -116,26 +110,21 @@ public class EmployeeServiceImplIntegrationTest {
List<Employee> allEmployees = employeeService.getAllEmployees(); List<Employee> allEmployees = employeeService.getAllEmployees();
verifyFindAllEmployeesIsCalledOnce(); verifyFindAllEmployeesIsCalledOnce();
assertThat(allEmployees).hasSize(3) assertThat(allEmployees).hasSize(3).extracting(Employee::getName).contains(alex.getName(), john.getName(), bob.getName());
.extracting(Employee::getName)
.contains(alex.getName(), john.getName(), bob.getName());
} }
private void verifyFindByNameIsCalledOnce(String name) { private void verifyFindByNameIsCalledOnce(String name) {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findByName(name);
.findByName(name);
Mockito.reset(employeeRepository); Mockito.reset(employeeRepository);
} }
private void verifyFindByIdIsCalledOnce() { private void verifyFindByIdIsCalledOnce() {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findById(Mockito.anyLong());
.findById(Mockito.anyLong());
Mockito.reset(employeeRepository); Mockito.reset(employeeRepository);
} }
private void verifyFindAllEmployeesIsCalledOnce() { private void verifyFindAllEmployeesIsCalledOnce() {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findAll();
.findAll();
Mockito.reset(employeeRepository); Mockito.reset(employeeRepository);
} }
} }

View File

@ -23,30 +23,21 @@ public class ConfigPropertiesIntegrationTest {
@Test @Test
public void whenListPropertyQueriedthenReturnsProperty() throws Exception { public void whenListPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients() Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2);
.size() == 2); Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients()
.size() == 2);
} }
@Test @Test
public void whenMapPropertyQueriedthenReturnsProperty() throws Exception { public void whenMapPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null); Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders() Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3);
.size() == 3);
} }
@Test @Test
public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception { public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null); Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null);
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials() Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1"));
.getAuthMethod() Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john"));
.equals("SHA1")); Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials()
.getUsername()
.equals("john"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials()
.getPassword()
.equals("password"));
} }
} }

View File

@ -47,8 +47,7 @@ public class UserRepositoryIntegrationTest {
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM); Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent(), equalTo(true)); assertThat(foundUser.isPresent(), equalTo(true));
assertThat(foundUser.get() assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM));
.getName(), equalTo(USER_NAME_ADAM));
} }
@Test @Test
@ -84,8 +83,7 @@ public class UserRepositoryIntegrationTest {
CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS);
assertThat(userByStatus.get() assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM));
.getName(), equalTo(USER_NAME_ADAM));
} }