formatting work
This commit is contained in:
parent
1cba1b043c
commit
b00a9e61bc
|
@ -16,7 +16,8 @@ import java.util.UUID;
|
|||
|
||||
public class JWTCsrfTokenRepository implements CsrfTokenRepository {
|
||||
|
||||
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN");
|
||||
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName()
|
||||
.concat(".CSRF_TOKEN");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
|
||||
private byte[] secret;
|
||||
|
@ -27,10 +28,12 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
|
|||
|
||||
@Override
|
||||
public CsrfToken generateToken(HttpServletRequest request) {
|
||||
String id = UUID.randomUUID().toString().replace("-", "");
|
||||
String id = UUID.randomUUID()
|
||||
.toString()
|
||||
.replace("-", "");
|
||||
|
||||
Date now = new Date();
|
||||
Date exp = new Date(System.currentTimeMillis() + (1000*30)); // 30 seconds
|
||||
Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds
|
||||
|
||||
String token = Jwts.builder()
|
||||
.setId(id)
|
||||
|
@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
|
|||
if (session != null) {
|
||||
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
HttpSession session = request.getSession();
|
||||
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
|
||||
}
|
||||
|
|
|
@ -30,23 +30,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
SecretService secretService;
|
||||
|
||||
// ordered so we can use binary search below
|
||||
private String[] ignoreCsrfAntMatchers = {
|
||||
"/dynamic-builder-compress",
|
||||
"/dynamic-builder-general",
|
||||
"/dynamic-builder-specific",
|
||||
"/set-secrets"
|
||||
};
|
||||
private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" };
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
|
||||
http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
|
||||
.csrf()
|
||||
.csrfTokenRepository(jwtCsrfTokenRepository)
|
||||
.ignoringAntMatchers(ignoreCsrfAntMatchers)
|
||||
.and().authorizeRequests()
|
||||
.antMatchers("/**")
|
||||
.permitAll();
|
||||
.csrfTokenRepository(jwtCsrfTokenRepository)
|
||||
.ignoringAntMatchers(ignoreCsrfAntMatchers)
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/**")
|
||||
.permitAll();
|
||||
}
|
||||
|
||||
private class JwtCsrfValidatorFilter extends OncePerRequestFilter {
|
||||
|
@ -58,13 +53,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
|
||||
|
||||
if (
|
||||
// only care if it's a POST
|
||||
"POST".equals(request.getMethod()) &&
|
||||
// ignore if the request path is in our list
|
||||
// only care if it's a POST
|
||||
"POST".equals(request.getMethod()) &&
|
||||
// ignore if the request path is in our list
|
||||
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
|
||||
// make sure we have a token
|
||||
token != null
|
||||
) {
|
||||
token != null) {
|
||||
// CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
|
||||
try {
|
||||
Jwts.parser()
|
||||
|
|
|
@ -11,12 +11,13 @@ import org.springframework.web.bind.annotation.ResponseStatus;
|
|||
public class BaseController {
|
||||
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler({SignatureException.class, MalformedJwtException.class, JwtException.class})
|
||||
@ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class })
|
||||
public JwtResponse exception(Exception e) {
|
||||
JwtResponse response = new JwtResponse();
|
||||
response.setStatus(JwtResponse.Status.ERROR);
|
||||
response.setMessage(e.getMessage());
|
||||
response.setExceptionType(e.getClass().getName());
|
||||
response.setExceptionType(e.getClass()
|
||||
.getName());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
|
|
@ -27,25 +27,19 @@ public class DynamicJWTController extends BaseController {
|
|||
|
||||
@RequestMapping(value = "/dynamic-builder-general", method = POST)
|
||||
public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
|
||||
String jws = Jwts.builder()
|
||||
String jws = Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.signWith(
|
||||
SignatureAlgorithm.HS256,
|
||||
secretService.getHS256SecretBytes()
|
||||
)
|
||||
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
|
||||
.compact();
|
||||
return new JwtResponse(jws);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/dynamic-builder-compress", method = POST)
|
||||
public JwtResponse dynamicBuildercompress(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
|
||||
String jws = Jwts.builder()
|
||||
String jws = Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.compressWith(CompressionCodecs.DEFLATE)
|
||||
.signWith(
|
||||
SignatureAlgorithm.HS256,
|
||||
secretService.getHS256SecretBytes()
|
||||
)
|
||||
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
|
||||
.compact();
|
||||
return new JwtResponse(jws);
|
||||
}
|
||||
|
@ -56,36 +50,36 @@ public class DynamicJWTController extends BaseController {
|
|||
|
||||
claims.forEach((key, value) -> {
|
||||
switch (key) {
|
||||
case "iss":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setIssuer((String) value);
|
||||
break;
|
||||
case "sub":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setSubject((String) value);
|
||||
break;
|
||||
case "aud":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setAudience((String) value);
|
||||
break;
|
||||
case "exp":
|
||||
ensureType(key, value, Long.class);
|
||||
builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
|
||||
break;
|
||||
case "nbf":
|
||||
ensureType(key, value, Long.class);
|
||||
builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
|
||||
break;
|
||||
case "iat":
|
||||
ensureType(key, value, Long.class);
|
||||
builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
|
||||
break;
|
||||
case "jti":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setId((String) value);
|
||||
break;
|
||||
default:
|
||||
builder.claim(key, value);
|
||||
case "iss":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setIssuer((String) value);
|
||||
break;
|
||||
case "sub":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setSubject((String) value);
|
||||
break;
|
||||
case "aud":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setAudience((String) value);
|
||||
break;
|
||||
case "exp":
|
||||
ensureType(key, value, Long.class);
|
||||
builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
|
||||
break;
|
||||
case "nbf":
|
||||
ensureType(key, value, Long.class);
|
||||
builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
|
||||
break;
|
||||
case "iat":
|
||||
ensureType(key, value, Long.class);
|
||||
builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
|
||||
break;
|
||||
case "jti":
|
||||
ensureType(key, value, String.class);
|
||||
builder.setId((String) value);
|
||||
break;
|
||||
default:
|
||||
builder.claim(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController {
|
|||
}
|
||||
|
||||
private void ensureType(String registeredClaim, Object value, Class expectedType) {
|
||||
boolean isCorrectType =
|
||||
expectedType.isInstance(value) ||
|
||||
expectedType == Long.class && value instanceof Integer;
|
||||
boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer;
|
||||
|
||||
if (!isCorrectType) {
|
||||
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" +
|
||||
registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName();
|
||||
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass()
|
||||
.getCanonicalName();
|
||||
throw new JwtException(msg);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,22 +11,16 @@ public class HomeController {
|
|||
@RequestMapping("/")
|
||||
public String home(HttpServletRequest req) {
|
||||
String requestUrl = getUrl(req);
|
||||
return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" +
|
||||
" http " + requestUrl + "/\n\tThis usage message\n\n" +
|
||||
" http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" +
|
||||
" http POST " + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" +
|
||||
" http POST " + requestUrl + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" +
|
||||
" http POST " + requestUrl + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" +
|
||||
" http " + requestUrl + "/parser?jwt=<jwt>\n\tParse passed in JWT\n\n" +
|
||||
" http " + requestUrl + "/parser-enforce?jwt=<jwt>\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" +
|
||||
" http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" +
|
||||
" http " + requestUrl + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" +
|
||||
" http POST " + requestUrl + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application.";
|
||||
return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + " http " + requestUrl + "/\n\tThis usage message\n\n" + " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + " http POST "
|
||||
+ requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + " http POST " + requestUrl
|
||||
+ "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + " http POST " + requestUrl
|
||||
+ "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + " http " + requestUrl + "/parser?jwt=<jwt>\n\tParse passed in JWT\n\n" + " http " + requestUrl
|
||||
+ "/parser-enforce?jwt=<jwt>\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + " http " + requestUrl
|
||||
+ "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl
|
||||
+ "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application.";
|
||||
}
|
||||
|
||||
private String getUrl(HttpServletRequest req) {
|
||||
return req.getScheme() + "://" +
|
||||
req.getServerName() +
|
||||
((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
|
||||
return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,12 +30,9 @@ public class StaticJWTController extends BaseController {
|
|||
.setSubject("msilverman")
|
||||
.claim("name", "Micah Silverman")
|
||||
.claim("scope", "admins")
|
||||
.setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT)
|
||||
.setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT)
|
||||
.setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT)
|
||||
.signWith(
|
||||
SignatureAlgorithm.HS256,
|
||||
secretService.getHS256SecretBytes()
|
||||
)
|
||||
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
|
||||
.compact();
|
||||
|
||||
return new JwtResponse(jws);
|
||||
|
|
|
@ -16,7 +16,8 @@ public class JwtResponse {
|
|||
SUCCESS, ERROR
|
||||
}
|
||||
|
||||
public JwtResponse() {}
|
||||
public JwtResponse() {
|
||||
}
|
||||
|
||||
public JwtResponse(String jwt) {
|
||||
this.jwt = jwt;
|
||||
|
|
|
@ -61,7 +61,6 @@ public class SecretService {
|
|||
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue()));
|
||||
}
|
||||
|
||||
|
||||
public Map<String, String> refreshSecrets() {
|
||||
SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256);
|
||||
secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded()));
|
||||
|
|
|
@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest {
|
|||
public void findCarsByYearNamedProcedure() {
|
||||
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
|
||||
final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015);
|
||||
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
storedProcedure.getResultList()
|
||||
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findCarsByYearNoNamed() {
|
||||
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015);
|
||||
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
|
||||
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
|
||||
.setParameter(1, 2015);
|
||||
storedProcedure.getResultList()
|
||||
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
|
|
|
@ -27,18 +27,22 @@ public class ELSampleBean {
|
|||
@PostConstruct
|
||||
public void init() {
|
||||
pageCounter = randomIntGen.nextInt();
|
||||
FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() {
|
||||
@Override
|
||||
public void contextCreated(ELContextEvent evt) {
|
||||
evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean");
|
||||
}
|
||||
});
|
||||
FacesContext.getCurrentInstance()
|
||||
.getApplication()
|
||||
.addELContextListener(new ELContextListener() {
|
||||
@Override
|
||||
public void contextCreated(ELContextEvent evt) {
|
||||
evt.getELContext()
|
||||
.getImportHandler()
|
||||
.importClass("com.baeldung.springintegration.controllers.ELSampleBean");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void save() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static String constantField() {
|
||||
return constantField;
|
||||
}
|
||||
|
@ -48,7 +52,8 @@ public class ELSampleBean {
|
|||
}
|
||||
|
||||
public Long multiplyValue(LambdaExpression expr) {
|
||||
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter);
|
||||
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance()
|
||||
.getELContext(), pageCounter);
|
||||
return theResult;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.springintegration.dao;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO {
|
|||
public UserManagementDAOImpl() {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -18,8 +18,11 @@ import static org.junit.Assert.assertEquals;
|
|||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class OperationIntegrationTest {
|
||||
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json");
|
||||
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
private InputStream jsonInputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("intro_api.json");
|
||||
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
|
||||
.next();
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
|
||||
|
@ -38,21 +41,27 @@ public class OperationIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() {
|
||||
Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00));
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter);
|
||||
Filter expensiveFilter = Filter.filter(Criteria.where("price")
|
||||
.gt(20.00));
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
|
||||
.read("$['book'][?]", expensiveFilter);
|
||||
predicateUsageAssertionHelper(expensive);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() {
|
||||
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00;
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate);
|
||||
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class)
|
||||
.get("price")
|
||||
.toString()) > 20.00;
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
|
||||
.read("$['book'][?]", expensivePredicate);
|
||||
predicateUsageAssertionHelper(expensive);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() {
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]");
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
|
||||
.read("$['book'][?(@['price'] > $['price range']['medium'])]");
|
||||
predicateUsageAssertionHelper(expensive);
|
||||
}
|
||||
|
||||
|
|
|
@ -18,12 +18,16 @@ import static org.junit.Assert.assertEquals;
|
|||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class ServiceTest {
|
||||
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json");
|
||||
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
private InputStream jsonInputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("intro_service.json");
|
||||
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
|
||||
.next();
|
||||
|
||||
@Test
|
||||
public void givenId_whenRequestingRecordData_thenSucceed() {
|
||||
Object dataObject = JsonPath.parse(jsonString).read("$[?(@.id == 2)]");
|
||||
Object dataObject = JsonPath.parse(jsonString)
|
||||
.read("$[?(@.id == 2)]");
|
||||
String dataString = dataObject.toString();
|
||||
|
||||
assertThat(dataString, containsString("2"));
|
||||
|
@ -33,8 +37,10 @@ public class ServiceTest {
|
|||
|
||||
@Test
|
||||
public void givenStarring_whenRequestingMovieTitle_thenSucceed() {
|
||||
List<Map<String, Object>> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]");
|
||||
String title = (String) dataList.get(0).get("title");
|
||||
List<Map<String, Object>> dataList = JsonPath.parse(jsonString)
|
||||
.read("$[?('Eva Green' in @['starring'])]");
|
||||
String title = (String) dataList.get(0)
|
||||
.get("title");
|
||||
|
||||
assertEquals("Casino Royale", title);
|
||||
}
|
||||
|
@ -59,8 +65,12 @@ public class ServiceTest {
|
|||
Arrays.sort(revenueArray);
|
||||
|
||||
int highestRevenue = revenueArray[revenueArray.length - 1];
|
||||
Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build();
|
||||
List<String> pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]");
|
||||
Configuration pathConfiguration = Configuration.builder()
|
||||
.options(Option.AS_PATH_LIST)
|
||||
.build();
|
||||
List<String> pathList = JsonPath.using(pathConfiguration)
|
||||
.parse(jsonString)
|
||||
.read("$[?(@['box office'] == " + highestRevenue + ")]");
|
||||
|
||||
Map<String, String> dataRecord = context.read(pathList.get(0));
|
||||
String title = dataRecord.get("title");
|
||||
|
@ -83,7 +93,8 @@ public class ServiceTest {
|
|||
|
||||
long latestTime = dateArray[dateArray.length - 1];
|
||||
List<Map<String, Object>> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]");
|
||||
String title = (String) finalDataList.get(0).get("title");
|
||||
String title = (String) finalDataList.get(0)
|
||||
.get("title");
|
||||
|
||||
assertEquals("Spectre", title);
|
||||
}
|
||||
|
|
|
@ -32,11 +32,7 @@ public class FastJsonUnitTest {
|
|||
@Test
|
||||
public void whenJavaList_thanConvertToJsonCorrect() {
|
||||
String personJsonFormat = JSON.toJSONString(listOfPersons);
|
||||
assertEquals(
|
||||
personJsonFormat,
|
||||
"[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":"
|
||||
+ "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":"
|
||||
+ "\"24/07/2016\"}]");
|
||||
assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -44,8 +40,10 @@ public class FastJsonUnitTest {
|
|||
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
|
||||
Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
|
||||
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
|
||||
assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName());
|
||||
assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName());
|
||||
assertEquals(newPerson.getFirstName(), listOfPersons.get(0)
|
||||
.getFirstName());
|
||||
assertEquals(newPerson.getLastName(), listOfPersons.get(0)
|
||||
.getLastName());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -58,18 +56,13 @@ public class FastJsonUnitTest {
|
|||
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
|
||||
jsonArray.add(jsonObject);
|
||||
}
|
||||
assertEquals(
|
||||
jsonArray.toString(),
|
||||
"[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":"
|
||||
+ "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\","
|
||||
+ "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
|
||||
assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
|
||||
ContextValueFilter valueFilter = new ContextValueFilter() {
|
||||
public Object process(BeanContext context, Object object,
|
||||
String name, Object value) {
|
||||
public Object process(BeanContext context, Object object, String name, Object value) {
|
||||
if (name.equals("DATE OF BIRTH")) {
|
||||
return "NOT TO DISCLOSE";
|
||||
}
|
||||
|
@ -87,18 +80,16 @@ public class FastJsonUnitTest {
|
|||
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
|
||||
NameFilter formatName = new NameFilter() {
|
||||
public String process(Object object, String name, Object value) {
|
||||
return name.toLowerCase().replace(" ", "_");
|
||||
return name.toLowerCase()
|
||||
.replace(" ", "_");
|
||||
}
|
||||
};
|
||||
SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName);
|
||||
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons,
|
||||
"yyyy-MM-dd");
|
||||
assertEquals(
|
||||
jsonOutput,
|
||||
"[{\"first_name\":\"Doe\",\"last_name\":\"John\","
|
||||
+ "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":"
|
||||
+ "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
|
||||
SerializeConfig.getGlobalInstance()
|
||||
.addFilter(Person.class, formatName);
|
||||
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
|
||||
assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
|
||||
// resetting custom serializer
|
||||
SerializeConfig.getGlobalInstance().put(Person.class, null);
|
||||
SerializeConfig.getGlobalInstance()
|
||||
.put(Person.class, null);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -32,10 +32,9 @@ public class Person {
|
|||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [age=" + age + ", lastName=" + lastName + ", firstName="
|
||||
+ firstName + ", dateOfBirth=" + dateOfBirth + "]";
|
||||
return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]";
|
||||
}
|
||||
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
|
|
@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest {
|
|||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
doc = Jsoup.connect("https://spring.io/blog").get();
|
||||
doc = Jsoup.connect("https://spring.io/blog")
|
||||
.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadDocument404() throws IOException {
|
||||
try {
|
||||
doc = Jsoup.connect("https://spring.io/will-not-be-found").get();
|
||||
doc = Jsoup.connect("https://spring.io/will-not-be-found")
|
||||
.get();
|
||||
} catch (HttpStatusException ex) {
|
||||
assertEquals(404, ex.getStatusCode());
|
||||
}
|
||||
|
@ -35,13 +37,13 @@ public class JsoupParserIntegrationTest {
|
|||
@Test
|
||||
public void loadDocumentCustomized() throws IOException {
|
||||
doc = Jsoup.connect("https://spring.io/blog")
|
||||
.userAgent("Mozilla")
|
||||
.timeout(5000)
|
||||
.cookie("cookiename", "val234")
|
||||
.cookie("anothercookie", "ilovejsoup")
|
||||
.referrer("http://google.com")
|
||||
.header("headersecurity", "xyz123")
|
||||
.get();
|
||||
.userAgent("Mozilla")
|
||||
.timeout(5000)
|
||||
.cookie("cookiename", "val234")
|
||||
.cookie("anothercookie", "ilovejsoup")
|
||||
.referrer("http://google.com")
|
||||
.header("headersecurity", "xyz123")
|
||||
.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void examplesExtracting() {
|
||||
Element firstArticle = doc.select("article").first();
|
||||
Element timeElement = firstArticle.select("time").first();
|
||||
Element firstArticle = doc.select("article")
|
||||
.first();
|
||||
Element timeElement = firstArticle.select("time")
|
||||
.first();
|
||||
String dateTimeOfFirstArticle = timeElement.attr("datetime");
|
||||
Element sectionDiv = firstArticle.select("section div").first();
|
||||
Element sectionDiv = firstArticle.select("section div")
|
||||
.first();
|
||||
String sectionDivText = sectionDiv.text();
|
||||
String articleHtml = firstArticle.html();
|
||||
String outerHtml = firstArticle.outerHtml();
|
||||
|
@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void examplesModifying() {
|
||||
Element firstArticle = doc.select("article").first();
|
||||
Element timeElement = firstArticle.select("time").first();
|
||||
Element sectionDiv = firstArticle.select("section div").first();
|
||||
Element firstArticle = doc.select("article")
|
||||
.first();
|
||||
Element timeElement = firstArticle.select("time")
|
||||
.first();
|
||||
Element sectionDiv = firstArticle.select("section div")
|
||||
.first();
|
||||
|
||||
String dateTimeOfFirstArticle = timeElement.attr("datetime");
|
||||
timeElement.attr("datetime", "2016-12-16 15:19:54.3");
|
||||
sectionDiv.text("foo bar");
|
||||
firstArticle.select("h2").html("<div><span></span></div>");
|
||||
firstArticle.select("h2")
|
||||
.html("<div><span></span></div>");
|
||||
|
||||
Element link = new Element(Tag.valueOf("a"), "")
|
||||
.text("Checkout this amazing website!")
|
||||
.attr("href", "http://baeldung.com")
|
||||
.attr("target", "_blank");
|
||||
Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!")
|
||||
.attr("href", "http://baeldung.com")
|
||||
.attr("target", "_blank");
|
||||
firstArticle.appendChild(link);
|
||||
|
||||
doc.select("li.navbar-link").remove();
|
||||
firstArticle.select("img").remove();
|
||||
doc.select("li.navbar-link")
|
||||
.remove();
|
||||
firstArticle.select("img")
|
||||
.remove();
|
||||
|
||||
assertTrue(doc.html().contains("http://baeldung.com"));
|
||||
assertTrue(doc.html()
|
||||
.contains("http://baeldung.com"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,23 +6,23 @@ import org.junit.jupiter.api.Test;
|
|||
|
||||
public class AssertionUnitTest {
|
||||
|
||||
@Test
|
||||
public void testConvertToDoubleThrowException() {
|
||||
String age = "eighteen";
|
||||
assertThrows(NumberFormatException.class, () -> {
|
||||
convertToInt(age);
|
||||
});
|
||||
@Test
|
||||
public void testConvertToDoubleThrowException() {
|
||||
String age = "eighteen";
|
||||
assertThrows(NumberFormatException.class, () -> {
|
||||
convertToInt(age);
|
||||
});
|
||||
|
||||
assertThrows(NumberFormatException.class, () -> {
|
||||
convertToInt(age);
|
||||
});
|
||||
}
|
||||
|
||||
private static Integer convertToInt(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return Integer.valueOf(str);
|
||||
}
|
||||
assertThrows(NumberFormatException.class, () -> {
|
||||
convertToInt(age);
|
||||
});
|
||||
}
|
||||
|
||||
private static Integer convertToInt(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return Integer.valueOf(str);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,9 +24,6 @@ public class AssumptionUnitTest {
|
|||
@Test
|
||||
void assumptionThat() {
|
||||
String someString = "Just a string";
|
||||
assumingThat(
|
||||
someString.equals("Just a string"),
|
||||
() -> assertEquals(2 + 2, 4)
|
||||
);
|
||||
assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,40 +24,33 @@ public class DynamicTestsExample {
|
|||
|
||||
@TestFactory
|
||||
Collection<DynamicTest> dynamicTestsWithCollection() {
|
||||
return Arrays.asList(
|
||||
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
|
||||
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
}
|
||||
|
||||
|
||||
@TestFactory
|
||||
Iterable<DynamicTest> dynamicTestsWithIterable() {
|
||||
return Arrays.asList(
|
||||
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
|
||||
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
}
|
||||
|
||||
|
||||
@TestFactory
|
||||
Iterator<DynamicTest> dynamicTestsWithIterator() {
|
||||
return Arrays.asList(
|
||||
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
|
||||
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
|
||||
.iterator();
|
||||
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
|
||||
.iterator();
|
||||
}
|
||||
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsFromIntStream() {
|
||||
return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj(
|
||||
n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
|
||||
return IntStream.iterate(0, n -> n + 2)
|
||||
.limit(10)
|
||||
.mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
|
||||
}
|
||||
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsFromStream() {
|
||||
|
||||
// sample input and output
|
||||
List<String> inputList =
|
||||
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
|
||||
List<String> outputList =
|
||||
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
|
||||
List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
|
||||
List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
|
||||
|
||||
// input generator that generates inputs using inputList
|
||||
Iterator<String> inputGenerator = inputList.iterator();
|
||||
|
@ -75,57 +68,56 @@ public class DynamicTestsExample {
|
|||
// combine everything and return a Stream of DynamicTest
|
||||
return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
|
||||
}
|
||||
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsFromStreamInJava8() {
|
||||
|
||||
|
||||
DomainNameResolver resolver = new DomainNameResolver();
|
||||
|
||||
List<String> inputList =
|
||||
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
|
||||
List<String> outputList =
|
||||
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
|
||||
|
||||
return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
|
||||
int id = inputList.indexOf(dom);
|
||||
assertEquals(outputList.get(id), resolver.resolveDomain(dom));
|
||||
}));
|
||||
|
||||
|
||||
List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
|
||||
List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
|
||||
|
||||
return inputList.stream()
|
||||
.map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
|
||||
int id = inputList.indexOf(dom);
|
||||
assertEquals(outputList.get(id), resolver.resolveDomain(dom));
|
||||
}));
|
||||
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() {
|
||||
List<Employee> inputList =
|
||||
Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
|
||||
|
||||
List<Employee> inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
|
||||
|
||||
EmployeeDao dao = new EmployeeDao();
|
||||
Stream<DynamicTest> saveEmployeeStream = inputList.stream().map(emp ->
|
||||
DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
|
||||
Employee returned = dao.save(emp.getId());
|
||||
assertEquals(returned.getId(), emp.getId());
|
||||
}));
|
||||
|
||||
Stream<DynamicTest> saveEmployeeWithFirstNameStream
|
||||
= inputList.stream().filter(emp -> !emp.getFirstName().isEmpty())
|
||||
Stream<DynamicTest> saveEmployeeStream = inputList.stream()
|
||||
.map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
|
||||
Employee returned = dao.save(emp.getId());
|
||||
assertEquals(returned.getId(), emp.getId());
|
||||
}));
|
||||
|
||||
Stream<DynamicTest> saveEmployeeWithFirstNameStream = inputList.stream()
|
||||
.filter(emp -> !emp.getFirstName()
|
||||
.isEmpty())
|
||||
.map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> {
|
||||
Employee returned = dao.save(emp.getId(), emp.getFirstName());
|
||||
assertEquals(returned.getId(), emp.getId());
|
||||
assertEquals(returned.getFirstName(), emp.getFirstName());
|
||||
}));
|
||||
|
||||
Employee returned = dao.save(emp.getId(), emp.getFirstName());
|
||||
assertEquals(returned.getId(), emp.getId());
|
||||
assertEquals(returned.getFirstName(), emp.getFirstName());
|
||||
}));
|
||||
|
||||
return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream);
|
||||
}
|
||||
|
||||
|
||||
class DomainNameResolver {
|
||||
|
||||
|
||||
private Map<String, String> ipByDomainName = new HashMap<>();
|
||||
|
||||
|
||||
DomainNameResolver() {
|
||||
this.ipByDomainName.put("www.somedomain.com", "154.174.10.56");
|
||||
this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132");
|
||||
this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156");
|
||||
}
|
||||
|
||||
|
||||
public String resolveDomain(String domainName) {
|
||||
return ipByDomainName.get(domainName);
|
||||
}
|
||||
|
|
|
@ -33,12 +33,14 @@ public class EmployeesTest {
|
|||
public void whenAddEmployee_thenGetEmployee() throws SQLException {
|
||||
Employee emp = new Employee(1, "john");
|
||||
employeeDao.add(emp);
|
||||
assertEquals(1, employeeDao.findAll().size());
|
||||
assertEquals(1, employeeDao.findAll()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetEmployees_thenEmptyList() throws SQLException {
|
||||
assertEquals(0, employeeDao.findAll().size());
|
||||
assertEquals(0, employeeDao.findAll()
|
||||
.size());
|
||||
}
|
||||
|
||||
public void setLogger(Logger logger) {
|
||||
|
|
|
@ -7,19 +7,19 @@ import org.junit.jupiter.api.Test;
|
|||
|
||||
public class ExceptionUnitTest {
|
||||
|
||||
@Test
|
||||
void shouldThrowException() {
|
||||
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
|
||||
throw new UnsupportedOperationException("Not supported");
|
||||
});
|
||||
assertEquals(exception.getMessage(), "Not supported");
|
||||
}
|
||||
@Test
|
||||
void shouldThrowException() {
|
||||
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
|
||||
throw new UnsupportedOperationException("Not supported");
|
||||
});
|
||||
assertEquals(exception.getMessage(), "Not supported");
|
||||
}
|
||||
|
||||
@Test
|
||||
void assertThrowsException() {
|
||||
String str = null;
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
Integer.valueOf(str);
|
||||
});
|
||||
}
|
||||
@Test
|
||||
void assertThrowsException() {
|
||||
String str = null;
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
Integer.valueOf(str);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,21 +13,16 @@ class FirstUnitTest {
|
|||
@Test
|
||||
void lambdaExpressions() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3);
|
||||
assertTrue(numbers
|
||||
.stream()
|
||||
.mapToInt(i -> i)
|
||||
.sum() > 5, "Sum should be greater than 5");
|
||||
assertTrue(numbers.stream()
|
||||
.mapToInt(i -> i)
|
||||
.sum() > 5, "Sum should be greater than 5");
|
||||
}
|
||||
|
||||
@Disabled("test to show MultipleFailuresError")
|
||||
@Test
|
||||
void groupAssertions() {
|
||||
int[] numbers = {0, 1, 2, 3, 4};
|
||||
assertAll("numbers",
|
||||
() -> assertEquals(numbers[0], 1),
|
||||
() -> assertEquals(numbers[3], 3),
|
||||
() -> assertEquals(numbers[4], 1)
|
||||
);
|
||||
int[] numbers = { 0, 1, 2, 3, 4 };
|
||||
assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -13,38 +13,38 @@ import org.junit.jupiter.api.Test;
|
|||
//@RunWith(JUnitPlatform.class)
|
||||
public class JUnit5NewFeaturesUnitTest {
|
||||
|
||||
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName());
|
||||
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName());
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
log.info("@BeforeAll - executes once before all test methods in this class");
|
||||
}
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
log.info("@BeforeAll - executes once before all test methods in this class");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
log.info("@BeforeEach - executes before each test method in this class");
|
||||
}
|
||||
@BeforeEach
|
||||
void init() {
|
||||
log.info("@BeforeEach - executes before each test method in this class");
|
||||
}
|
||||
|
||||
@DisplayName("Single test successful")
|
||||
@Test
|
||||
void testSingleSuccessTest() {
|
||||
log.info("Success");
|
||||
@DisplayName("Single test successful")
|
||||
@Test
|
||||
void testSingleSuccessTest() {
|
||||
log.info("Success");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled("Not implemented yet.")
|
||||
void testShowSomething() {
|
||||
}
|
||||
@Test
|
||||
@Disabled("Not implemented yet.")
|
||||
void testShowSomething() {
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
log.info("@AfterEach - executed after each test method.");
|
||||
}
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
log.info("@AfterEach - executed after each test method.");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void done() {
|
||||
log.info("@AfterAll - executed after all test methods.");
|
||||
}
|
||||
@AfterAll
|
||||
static void done() {
|
||||
log.info("@AfterAll - executed after all test methods.");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -12,27 +12,28 @@ import org.junit.jupiter.api.TestFactory;
|
|||
|
||||
public class LiveTest {
|
||||
|
||||
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
|
||||
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
|
||||
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
|
||||
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
|
||||
|
||||
@TestFactory
|
||||
public Stream<DynamicTest> translateDynamicTestsFromStream() {
|
||||
@TestFactory
|
||||
public Stream<DynamicTest> translateDynamicTestsFromStream() {
|
||||
|
||||
return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
|
||||
int id = in.indexOf(word);
|
||||
assertEquals(out.get(id), translate(word));
|
||||
}));
|
||||
}
|
||||
return in.stream()
|
||||
.map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
|
||||
int id = in.indexOf(word);
|
||||
assertEquals(out.get(id), translate(word));
|
||||
}));
|
||||
}
|
||||
|
||||
private String translate(String word) {
|
||||
if ("Hello".equalsIgnoreCase(word)) {
|
||||
return "Cześć";
|
||||
} else if ("Yes".equalsIgnoreCase(word)) {
|
||||
return "Tak";
|
||||
} else if ("No".equalsIgnoreCase(word)) {
|
||||
return "Nie";
|
||||
}
|
||||
return "Error";
|
||||
}
|
||||
private String translate(String word) {
|
||||
if ("Hello".equalsIgnoreCase(word)) {
|
||||
return "Cześć";
|
||||
} else if ("Yes".equalsIgnoreCase(word)) {
|
||||
return "Tak";
|
||||
} else if ("No".equalsIgnoreCase(word)) {
|
||||
return "Nie";
|
||||
}
|
||||
return "Error";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -14,36 +14,36 @@ public class RepeatedTestExample {
|
|||
void beforeEachTest() {
|
||||
System.out.println("Before Each Test");
|
||||
}
|
||||
|
||||
|
||||
@AfterEach
|
||||
void afterEachTest() {
|
||||
System.out.println("After Each Test");
|
||||
System.out.println("=====================");
|
||||
}
|
||||
|
||||
|
||||
@RepeatedTest(3)
|
||||
void repeatedTest(TestInfo testInfo) {
|
||||
System.out.println("Executing repeated test");
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
|
||||
@RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)
|
||||
void repeatedTestWithLongName() {
|
||||
System.out.println("Executing repeated test with long name");
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
|
||||
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
|
||||
void repeatedTestWithShortName() {
|
||||
System.out.println("Executing repeated test with long name");
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
|
||||
@RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}")
|
||||
void repeatedTestWithCustomDisplayName() {
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
|
||||
@RepeatedTest(3)
|
||||
void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
|
||||
System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition());
|
||||
|
|
|
@ -2,10 +2,10 @@ package com.baeldung;
|
|||
|
||||
public final class StringUtils {
|
||||
|
||||
public static Double convertToDouble(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return Double.valueOf(str);
|
||||
}
|
||||
public static Double convertToDouble(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return Double.valueOf(str);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,13 +25,15 @@ public class TestLauncher {
|
|||
|
||||
//@formatter:on
|
||||
|
||||
TestPlan plan = LauncherFactory.create().discover(request);
|
||||
TestPlan plan = LauncherFactory.create()
|
||||
.discover(request);
|
||||
Launcher launcher = LauncherFactory.create();
|
||||
SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
|
||||
launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
|
||||
launcher.execute(request);
|
||||
|
||||
summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out));
|
||||
summaryGeneratingListener.getSummary()
|
||||
.printTo(new PrintWriter(System.out));
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver {
|
|||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class);
|
||||
return parameterContext.getParameter()
|
||||
.getType()
|
||||
.equals(EmployeeJdbcDao.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -10,7 +10,9 @@ public class LoggingExtension implements TestInstancePostProcessor {
|
|||
@Override
|
||||
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
|
||||
Logger logger = LogManager.getLogger(testInstance.getClass());
|
||||
testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger);
|
||||
testInstance.getClass()
|
||||
.getMethod("setLogger", Logger.class)
|
||||
.invoke(testInstance, logger);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -30,9 +30,10 @@ public class AssertionsExampleTest {
|
|||
List<Integer> list = Arrays.asList(1, 2, 3);
|
||||
|
||||
Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0)
|
||||
.intValue(), 1),
|
||||
() -> Assertions.assertEquals(list.get(1)
|
||||
.intValue(), 2),
|
||||
.intValue(), 1), () -> Assertions.assertEquals(
|
||||
list.get(1)
|
||||
.intValue(),
|
||||
2),
|
||||
() -> Assertions.assertEquals(list.get(2)
|
||||
.intValue(), 3));
|
||||
}
|
||||
|
|
|
@ -9,42 +9,51 @@ import org.junit.jupiter.api.extension.ParameterResolver;
|
|||
|
||||
public class InvalidPersonParameterResolver implements ParameterResolver {
|
||||
|
||||
/**
|
||||
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] INVALID_PERSONS = {
|
||||
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"),
|
||||
new Person().setId(2L).setLastName(",Baker").setFirstName(""),
|
||||
new Person().setId(3L).setLastName(null).setFirstName(null),
|
||||
new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"),
|
||||
new Person().setId(5L).setLastName("").setFirstName("English, Jane"),
|
||||
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
/**
|
||||
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] INVALID_PERSONS = { new Person().setId(1L)
|
||||
.setLastName("Ad_ams")
|
||||
.setFirstName("Jill,"),
|
||||
new Person().setId(2L)
|
||||
.setLastName(",Baker")
|
||||
.setFirstName(""),
|
||||
new Person().setId(3L)
|
||||
.setLastName(null)
|
||||
.setFirstName(null),
|
||||
new Person().setId(4L)
|
||||
.setLastName("Daniel&")
|
||||
.setFirstName("{Joseph}"),
|
||||
new Person().setId(5L)
|
||||
.setLastName("")
|
||||
.setFirstName("English, Jane"),
|
||||
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// to be resolved. Otherwise return null.
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// to be resolved. Otherwise return null.
|
||||
if (parameterContext.getParameter()
|
||||
.getType() == Person.class) {
|
||||
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = true;
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
|
||||
if (parameterContext.getParameter()
|
||||
.getType() == Person.class) {
|
||||
ret = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -9,35 +9,35 @@ package com.baeldung.param;
|
|||
*/
|
||||
public class Person {
|
||||
|
||||
private Long id;
|
||||
private String lastName;
|
||||
private String firstName;
|
||||
private Long id;
|
||||
private String lastName;
|
||||
private String firstName;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Person setId(Long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
public Person setId(Long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Person setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
return this;
|
||||
}
|
||||
public Person setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public Person setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
return this;
|
||||
}
|
||||
public Person setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -11,132 +11,122 @@ import java.util.Arrays;
|
|||
*/
|
||||
public class PersonValidator {
|
||||
|
||||
/**
|
||||
* Contrived checked exception to illustrate one possible
|
||||
* way to handle validation errors (via a checked exception).
|
||||
*
|
||||
* @author J Steven Perry
|
||||
*
|
||||
*/
|
||||
public static class ValidationException extends Exception {
|
||||
/**
|
||||
* Contrived checked exception to illustrate one possible
|
||||
* way to handle validation errors (via a checked exception).
|
||||
*
|
||||
* @author J Steven Perry
|
||||
*
|
||||
*/
|
||||
public static class ValidationException extends Exception {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -134518049431883102L;
|
||||
|
||||
// Probably should implement some more constructors, but don't want
|
||||
/// to tarnish the lesson...
|
||||
|
||||
/**
|
||||
* The one and only way to create this checked exception.
|
||||
*
|
||||
* @param message
|
||||
* The message accompanying the exception. Should be meaningful.
|
||||
*/
|
||||
public ValidationException(String message) {
|
||||
super(message);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final String[] ILLEGAL_NAME_CHARACTERS = { ",", "_", "{", "}", "!" };
|
||||
|
||||
/**
|
||||
* Validate the first name of the specified Person object.
|
||||
*
|
||||
* @param person
|
||||
* The Person object to validate.
|
||||
*
|
||||
* @return - returns true if the specified Person is valid
|
||||
*
|
||||
* @throws ValidationException
|
||||
* - this Exception is thrown if any kind of validation error occurs.
|
||||
*/
|
||||
private static final long serialVersionUID = -134518049431883102L;
|
||||
|
||||
// Probably should implement some more constructors, but don't want
|
||||
/// to tarnish the lesson...
|
||||
public static boolean validateFirstName(Person person) throws ValidationException {
|
||||
boolean ret = true;
|
||||
// The validation rules go here.
|
||||
// Naive: use simple ifs
|
||||
if (person == null) {
|
||||
throw new ValidationException("Person is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName() == null) {
|
||||
throw new ValidationException("Person FirstName is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName()
|
||||
.isEmpty()) {
|
||||
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException("Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one and only way to create this checked exception.
|
||||
* Validate the last name of the specified Person object. Looks the same as first
|
||||
* name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge.
|
||||
*
|
||||
* @param message
|
||||
* The message accompanying the exception. Should be meaningful.
|
||||
* @param person
|
||||
* The Person object to validate.
|
||||
*
|
||||
* @return - returns true if the specified Person is valid
|
||||
*
|
||||
* @throws ValidationException
|
||||
* - this Exception is thrown if any kind of validation error occurs.
|
||||
*/
|
||||
public ValidationException(String message) {
|
||||
super(message);
|
||||
|
||||
public static boolean validateLastName(Person person) throws ValidationException {
|
||||
boolean ret = true;
|
||||
// The validation rules go here.
|
||||
// Naive: use simple ifs
|
||||
if (person == null) {
|
||||
throw new ValidationException("Person is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName() == null) {
|
||||
throw new ValidationException("Person FirstName is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName()
|
||||
.isEmpty()) {
|
||||
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException("Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final String[] ILLEGAL_NAME_CHARACTERS = {
|
||||
",",
|
||||
"_",
|
||||
"{",
|
||||
"}",
|
||||
"!"
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the first name of the specified Person object.
|
||||
*
|
||||
* @param person
|
||||
* The Person object to validate.
|
||||
*
|
||||
* @return - returns true if the specified Person is valid
|
||||
*
|
||||
* @throws ValidationException
|
||||
* - this Exception is thrown if any kind of validation error occurs.
|
||||
*/
|
||||
public static boolean validateFirstName(Person person) throws ValidationException {
|
||||
boolean ret = true;
|
||||
// The validation rules go here.
|
||||
// Naive: use simple ifs
|
||||
if (person == null) {
|
||||
throw new ValidationException("Person is null (not allowed)!");
|
||||
/**
|
||||
* Validates the specified name. If it contains any of the illegalCharacters,
|
||||
* this method returns false (indicating the name is illegal). Otherwise it returns true.
|
||||
*
|
||||
* @param candidate
|
||||
* The candidate String to validate
|
||||
*
|
||||
* @param illegalCharacters
|
||||
* The characters the String is not allowed to have
|
||||
*
|
||||
* @return - boolean - true if the name is valid, false otherwise.
|
||||
*/
|
||||
private static boolean isStringValid(String candidate, String[] illegalCharacters) {
|
||||
boolean ret = true;
|
||||
for (String illegalChar : illegalCharacters) {
|
||||
if (candidate.contains(illegalChar)) {
|
||||
ret = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
if (person.getFirstName() == null) {
|
||||
throw new ValidationException("Person FirstName is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName().isEmpty()) {
|
||||
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException(
|
||||
"Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: "
|
||||
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
|
||||
+ "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the last name of the specified Person object. Looks the same as first
|
||||
* name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge.
|
||||
*
|
||||
* @param person
|
||||
* The Person object to validate.
|
||||
*
|
||||
* @return - returns true if the specified Person is valid
|
||||
*
|
||||
* @throws ValidationException
|
||||
* - this Exception is thrown if any kind of validation error occurs.
|
||||
*/
|
||||
public static boolean validateLastName(Person person) throws ValidationException {
|
||||
boolean ret = true;
|
||||
// The validation rules go here.
|
||||
// Naive: use simple ifs
|
||||
if (person == null) {
|
||||
throw new ValidationException("Person is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName() == null) {
|
||||
throw new ValidationException("Person FirstName is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName().isEmpty()) {
|
||||
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException(
|
||||
"Person LastName (" + person.getLastName() + ") may not contain any of the following characters: "
|
||||
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
|
||||
+ "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the specified name. If it contains any of the illegalCharacters,
|
||||
* this method returns false (indicating the name is illegal). Otherwise it returns true.
|
||||
*
|
||||
* @param candidate
|
||||
* The candidate String to validate
|
||||
*
|
||||
* @param illegalCharacters
|
||||
* The characters the String is not allowed to have
|
||||
*
|
||||
* @return - boolean - true if the name is valid, false otherwise.
|
||||
*/
|
||||
private static boolean isStringValid(String candidate, String[] illegalCharacters) {
|
||||
boolean ret = true;
|
||||
for (String illegalChar : illegalCharacters) {
|
||||
if (candidate.contains(illegalChar)) {
|
||||
ret = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -15,88 +15,88 @@ import org.junit.runner.RunWith;
|
|||
@DisplayName("Testing PersonValidator")
|
||||
public class PersonValidatorTest {
|
||||
|
||||
/**
|
||||
* Nested class, uses ExtendWith
|
||||
* {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
|
||||
* to feed Test methods with "good" data.
|
||||
*/
|
||||
@Nested
|
||||
@DisplayName("When using Valid data")
|
||||
@ExtendWith(ValidPersonParameterResolver.class)
|
||||
public class ValidData {
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* A valid Person object to validate.
|
||||
* Nested class, uses ExtendWith
|
||||
* {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
|
||||
* to feed Test methods with "good" data.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are valid")
|
||||
public void validateFirstName(Person person) {
|
||||
try {
|
||||
assertTrue(PersonValidator.validateFirstName(person));
|
||||
} catch (PersonValidator.ValidationException e) {
|
||||
fail("Exception not expected: " + e.getLocalizedMessage());
|
||||
}
|
||||
@Nested
|
||||
@DisplayName("When using Valid data")
|
||||
@ExtendWith(ValidPersonParameterResolver.class)
|
||||
public class ValidData {
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* A valid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are valid")
|
||||
public void validateFirstName(Person person) {
|
||||
try {
|
||||
assertTrue(PersonValidator.validateFirstName(person));
|
||||
} catch (PersonValidator.ValidationException e) {
|
||||
fail("Exception not expected: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* A valid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All last names are valid")
|
||||
public void validateLastName(Person person) {
|
||||
try {
|
||||
assertTrue(PersonValidator.validateLastName(person));
|
||||
} catch (PersonValidator.ValidationException e) {
|
||||
fail("Exception not expected: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* A valid Person object to validate.
|
||||
* Nested class, uses ExtendWith
|
||||
* {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
|
||||
* to feed Test methods with "bad" data.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All last names are valid")
|
||||
public void validateLastName(Person person) {
|
||||
try {
|
||||
assertTrue(PersonValidator.validateLastName(person));
|
||||
} catch (PersonValidator.ValidationException e) {
|
||||
fail("Exception not expected: " + e.getLocalizedMessage());
|
||||
}
|
||||
@Nested
|
||||
@DisplayName("When using Invalid data")
|
||||
@ExtendWith(InvalidPersonParameterResolver.class)
|
||||
public class InvalidData {
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* An invalid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are invalid")
|
||||
public void validateFirstName(Person person) {
|
||||
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person));
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* An invalid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are invalid")
|
||||
public void validateLastName(Person person) {
|
||||
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Nested class, uses ExtendWith
|
||||
* {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
|
||||
* to feed Test methods with "bad" data.
|
||||
*/
|
||||
@Nested
|
||||
@DisplayName("When using Invalid data")
|
||||
@ExtendWith(InvalidPersonParameterResolver.class)
|
||||
public class InvalidData {
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* An invalid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are invalid")
|
||||
public void validateFirstName(Person person) {
|
||||
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person));
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* An invalid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are invalid")
|
||||
public void validateLastName(Person person) {
|
||||
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -9,42 +9,53 @@ import org.junit.jupiter.api.extension.ParameterResolver;
|
|||
|
||||
public class ValidPersonParameterResolver implements ParameterResolver {
|
||||
|
||||
/**
|
||||
* The "good" (valid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] VALID_PERSONS = {
|
||||
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"),
|
||||
new Person().setId(2L).setLastName("Baker").setFirstName("James"),
|
||||
new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"),
|
||||
new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"),
|
||||
new Person().setId(5L).setLastName("English").setFirstName("Jane"),
|
||||
new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"),
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
/**
|
||||
* The "good" (valid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] VALID_PERSONS = { new Person().setId(1L)
|
||||
.setLastName("Adams")
|
||||
.setFirstName("Jill"),
|
||||
new Person().setId(2L)
|
||||
.setLastName("Baker")
|
||||
.setFirstName("James"),
|
||||
new Person().setId(3L)
|
||||
.setLastName("Carter")
|
||||
.setFirstName("Samanta"),
|
||||
new Person().setId(4L)
|
||||
.setLastName("Daniels")
|
||||
.setFirstName("Joseph"),
|
||||
new Person().setId(5L)
|
||||
.setLastName("English")
|
||||
.setFirstName("Jane"),
|
||||
new Person().setId(6L)
|
||||
.setLastName("Fontana")
|
||||
.setFirstName("Enrique"),
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// to be resolved. Otherwise return null.
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// to be resolved. Otherwise return null.
|
||||
if (parameterContext.getParameter()
|
||||
.getType() == Person.class) {
|
||||
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = true;
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
|
||||
if (parameterContext.getParameter()
|
||||
.getType() == Person.class) {
|
||||
ret = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@ import org.junit.runner.RunWith;
|
|||
|
||||
@RunWith(JUnitPlatform.class)
|
||||
@SelectPackages("com.baeldung")
|
||||
//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
|
||||
// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
|
||||
public class AllTests {
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue