formatting work

This commit is contained in:
eugenp 2017-08-24 15:30:33 +03:00
parent 1cba1b043c
commit b00a9e61bc
36 changed files with 628 additions and 616 deletions

View File

@ -16,7 +16,8 @@ import java.util.UUID;
public class JWTCsrfTokenRepository implements CsrfTokenRepository { 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 static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
private byte[] secret; private byte[] secret;
@ -27,10 +28,12 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
@Override @Override
public CsrfToken generateToken(HttpServletRequest request) { public CsrfToken generateToken(HttpServletRequest request) {
String id = UUID.randomUUID().toString().replace("-", ""); String id = UUID.randomUUID()
.toString()
.replace("-", "");
Date now = new Date(); 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() String token = Jwts.builder()
.setId(id) .setId(id)
@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
if (session != null) { if (session != null) {
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
} }
} } else {
else {
HttpSession session = request.getSession(); HttpSession session = request.getSession();
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token); session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
} }

View File

@ -30,23 +30,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
SecretService secretService; SecretService secretService;
// ordered so we can use binary search below // ordered so we can use binary search below
private String[] ignoreCsrfAntMatchers = { private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" };
"/dynamic-builder-compress",
"/dynamic-builder-general",
"/dynamic-builder-specific",
"/set-secrets"
};
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
.csrf() .csrf()
.csrfTokenRepository(jwtCsrfTokenRepository) .csrfTokenRepository(jwtCsrfTokenRepository)
.ignoringAntMatchers(ignoreCsrfAntMatchers) .ignoringAntMatchers(ignoreCsrfAntMatchers)
.and().authorizeRequests() .and()
.antMatchers("/**") .authorizeRequests()
.permitAll(); .antMatchers("/**")
.permitAll();
} }
private class JwtCsrfValidatorFilter extends OncePerRequestFilter { private class JwtCsrfValidatorFilter extends OncePerRequestFilter {
@ -58,13 +53,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
if ( if (
// only care if it's a POST // only care if it's a POST
"POST".equals(request.getMethod()) && "POST".equals(request.getMethod()) &&
// ignore if the request path is in our list // ignore if the request path is in our list
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 && Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
// make sure we have a token // 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 // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
try { try {
Jwts.parser() Jwts.parser()

View File

@ -11,12 +11,13 @@ import org.springframework.web.bind.annotation.ResponseStatus;
public class BaseController { public class BaseController {
@ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({SignatureException.class, MalformedJwtException.class, JwtException.class}) @ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class })
public JwtResponse exception(Exception e) { public JwtResponse exception(Exception e) {
JwtResponse response = new JwtResponse(); JwtResponse response = new JwtResponse();
response.setStatus(JwtResponse.Status.ERROR); response.setStatus(JwtResponse.Status.ERROR);
response.setMessage(e.getMessage()); response.setMessage(e.getMessage());
response.setExceptionType(e.getClass().getName()); response.setExceptionType(e.getClass()
.getName());
return response; return response;
} }

View File

@ -27,25 +27,19 @@ public class DynamicJWTController extends BaseController {
@RequestMapping(value = "/dynamic-builder-general", method = POST) @RequestMapping(value = "/dynamic-builder-general", method = POST)
public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException { public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
String jws = Jwts.builder() String jws = Jwts.builder()
.setClaims(claims) .setClaims(claims)
.signWith( .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
SignatureAlgorithm.HS256,
secretService.getHS256SecretBytes()
)
.compact(); .compact();
return new JwtResponse(jws); return new JwtResponse(jws);
} }
@RequestMapping(value = "/dynamic-builder-compress", method = POST) @RequestMapping(value = "/dynamic-builder-compress", method = POST)
public JwtResponse dynamicBuildercompress(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException { public JwtResponse dynamicBuildercompress(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
String jws = Jwts.builder() String jws = Jwts.builder()
.setClaims(claims) .setClaims(claims)
.compressWith(CompressionCodecs.DEFLATE) .compressWith(CompressionCodecs.DEFLATE)
.signWith( .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
SignatureAlgorithm.HS256,
secretService.getHS256SecretBytes()
)
.compact(); .compact();
return new JwtResponse(jws); return new JwtResponse(jws);
} }
@ -56,36 +50,36 @@ public class DynamicJWTController extends BaseController {
claims.forEach((key, value) -> { claims.forEach((key, value) -> {
switch (key) { switch (key) {
case "iss": case "iss":
ensureType(key, value, String.class); ensureType(key, value, String.class);
builder.setIssuer((String) value); builder.setIssuer((String) value);
break; break;
case "sub": case "sub":
ensureType(key, value, String.class); ensureType(key, value, String.class);
builder.setSubject((String) value); builder.setSubject((String) value);
break; break;
case "aud": case "aud":
ensureType(key, value, String.class); ensureType(key, value, String.class);
builder.setAudience((String) value); builder.setAudience((String) value);
break; break;
case "exp": case "exp":
ensureType(key, value, Long.class); ensureType(key, value, Long.class);
builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break; break;
case "nbf": case "nbf":
ensureType(key, value, Long.class); ensureType(key, value, Long.class);
builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break; break;
case "iat": case "iat":
ensureType(key, value, Long.class); ensureType(key, value, Long.class);
builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break; break;
case "jti": case "jti":
ensureType(key, value, String.class); ensureType(key, value, String.class);
builder.setId((String) value); builder.setId((String) value);
break; break;
default: default:
builder.claim(key, value); builder.claim(key, value);
} }
}); });
@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController {
} }
private void ensureType(String registeredClaim, Object value, Class expectedType) { private void ensureType(String registeredClaim, Object value, Class expectedType) {
boolean isCorrectType = boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer;
expectedType.isInstance(value) ||
expectedType == Long.class && value instanceof Integer;
if (!isCorrectType) { if (!isCorrectType) {
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass()
registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName(); .getCanonicalName();
throw new JwtException(msg); throw new JwtException(msg);
} }
} }

View File

@ -11,22 +11,16 @@ public class HomeController {
@RequestMapping("/") @RequestMapping("/")
public String home(HttpServletRequest req) { public String home(HttpServletRequest req) {
String requestUrl = getUrl(req); String requestUrl = getUrl(req);
return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + 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 "
" http " + requestUrl + "/\n\tThis usage message\n\n" + + 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
" http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + + "/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
" 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" + + "/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
" 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" + + "/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
" 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" + + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl
" http " + requestUrl + "/parser?jwt=<jwt>\n\tParse passed in JWT\n\n" + + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application.";
" 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) { private String getUrl(HttpServletRequest req) {
return req.getScheme() + "://" + return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
req.getServerName() +
((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
} }
} }

View File

@ -30,12 +30,9 @@ public class StaticJWTController extends BaseController {
.setSubject("msilverman") .setSubject("msilverman")
.claim("name", "Micah Silverman") .claim("name", "Micah Silverman")
.claim("scope", "admins") .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) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT)
.signWith( .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
SignatureAlgorithm.HS256,
secretService.getHS256SecretBytes()
)
.compact(); .compact();
return new JwtResponse(jws); return new JwtResponse(jws);

View File

@ -16,7 +16,8 @@ public class JwtResponse {
SUCCESS, ERROR SUCCESS, ERROR
} }
public JwtResponse() {} public JwtResponse() {
}
public JwtResponse(String jwt) { public JwtResponse(String jwt) {
this.jwt = jwt; this.jwt = jwt;

View File

@ -61,7 +61,6 @@ public class SecretService {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue())); return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue()));
} }
public Map<String, String> refreshSecrets() { public Map<String, String> refreshSecrets() {
SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256); SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256);
secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded())); secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded()));

View File

@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest {
public void findCarsByYearNamedProcedure() { public void findCarsByYearNamedProcedure() {
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); 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 @Test
public void findCarsByYearNoNamed() { public void findCarsByYearNoNamed() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015); final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
.setParameter(1, 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
} }
@AfterClass @AfterClass

View File

@ -27,18 +27,22 @@ public class ELSampleBean {
@PostConstruct @PostConstruct
public void init() { public void init() {
pageCounter = randomIntGen.nextInt(); pageCounter = randomIntGen.nextInt();
FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { FacesContext.getCurrentInstance()
@Override .getApplication()
public void contextCreated(ELContextEvent evt) { .addELContextListener(new ELContextListener() {
evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); @Override
} public void contextCreated(ELContextEvent evt) {
}); evt.getELContext()
.getImportHandler()
.importClass("com.baeldung.springintegration.controllers.ELSampleBean");
}
});
} }
public void save() { public void save() {
} }
public static String constantField() { public static String constantField() {
return constantField; return constantField;
} }
@ -48,7 +52,8 @@ public class ELSampleBean {
} }
public Long multiplyValue(LambdaExpression expr) { 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; return theResult;
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.springintegration.dao; package com.baeldung.springintegration.dao;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO {
public UserManagementDAOImpl() { public UserManagementDAOImpl() {
} }
} }

View File

@ -18,8 +18,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
public class OperationIntegrationTest { public class OperationIntegrationTest {
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); private InputStream jsonInputStream = this.getClass()
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); .getClassLoader()
.getResourceAsStream("intro_api.json");
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
.next();
@Test @Test
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
@ -38,21 +41,27 @@ public class OperationIntegrationTest {
@Test @Test
public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() { public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() {
Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00)); Filter expensiveFilter = Filter.filter(Criteria.where("price")
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter); .gt(20.00));
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$['book'][?]", expensiveFilter);
predicateUsageAssertionHelper(expensive); predicateUsageAssertionHelper(expensive);
} }
@Test @Test
public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() {
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00; Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class)
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); .get("price")
.toString()) > 20.00;
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$['book'][?]", expensivePredicate);
predicateUsageAssertionHelper(expensive); predicateUsageAssertionHelper(expensive);
} }
@Test @Test
public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() { 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); predicateUsageAssertionHelper(expensive);
} }

View File

@ -18,12 +18,16 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
public class ServiceTest { public class ServiceTest {
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json"); private InputStream jsonInputStream = this.getClass()
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); .getClassLoader()
.getResourceAsStream("intro_service.json");
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
.next();
@Test @Test
public void givenId_whenRequestingRecordData_thenSucceed() { 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(); String dataString = dataObject.toString();
assertThat(dataString, containsString("2")); assertThat(dataString, containsString("2"));
@ -33,8 +37,10 @@ public class ServiceTest {
@Test @Test
public void givenStarring_whenRequestingMovieTitle_thenSucceed() { public void givenStarring_whenRequestingMovieTitle_thenSucceed() {
List<Map<String, Object>> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]"); List<Map<String, Object>> dataList = JsonPath.parse(jsonString)
String title = (String) dataList.get(0).get("title"); .read("$[?('Eva Green' in @['starring'])]");
String title = (String) dataList.get(0)
.get("title");
assertEquals("Casino Royale", title); assertEquals("Casino Royale", title);
} }
@ -59,8 +65,12 @@ public class ServiceTest {
Arrays.sort(revenueArray); Arrays.sort(revenueArray);
int highestRevenue = revenueArray[revenueArray.length - 1]; int highestRevenue = revenueArray[revenueArray.length - 1];
Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build(); Configuration pathConfiguration = Configuration.builder()
List<String> pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]"); .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)); Map<String, String> dataRecord = context.read(pathList.get(0));
String title = dataRecord.get("title"); String title = dataRecord.get("title");
@ -83,7 +93,8 @@ public class ServiceTest {
long latestTime = dateArray[dateArray.length - 1]; long latestTime = dateArray[dateArray.length - 1];
List<Map<String, Object>> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); 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); assertEquals("Spectre", title);
} }

View File

@ -32,11 +32,7 @@ public class FastJsonUnitTest {
@Test @Test
public void whenJavaList_thanConvertToJsonCorrect() { public void whenJavaList_thanConvertToJsonCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons); String personJsonFormat = JSON.toJSONString(listOfPersons);
assertEquals( 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\"}]");
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 @Test
@ -44,8 +40,10 @@ public class FastJsonUnitTest {
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0)); String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
Person newPerson = JSON.parseObject(personJsonFormat, Person.class); Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName()); assertEquals(newPerson.getFirstName(), listOfPersons.get(0)
assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName()); .getFirstName());
assertEquals(newPerson.getLastName(), listOfPersons.get(0)
.getLastName());
} }
@Test @Test
@ -58,18 +56,13 @@ public class FastJsonUnitTest {
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject); jsonArray.add(jsonObject);
} }
assertEquals( 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\"}]");
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 @Test
public void givenContextFilter_whenJavaObject_thanJsonCorrect() { public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
ContextValueFilter valueFilter = new ContextValueFilter() { ContextValueFilter valueFilter = new ContextValueFilter() {
public Object process(BeanContext context, Object object, public Object process(BeanContext context, Object object, String name, Object value) {
String name, Object value) {
if (name.equals("DATE OF BIRTH")) { if (name.equals("DATE OF BIRTH")) {
return "NOT TO DISCLOSE"; return "NOT TO DISCLOSE";
} }
@ -87,18 +80,16 @@ public class FastJsonUnitTest {
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
NameFilter formatName = new NameFilter() { NameFilter formatName = new NameFilter() {
public String process(Object object, String name, Object value) { public String process(Object object, String name, Object value) {
return name.toLowerCase().replace(" ", "_"); return name.toLowerCase()
.replace(" ", "_");
} }
}; };
SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName); SerializeConfig.getGlobalInstance()
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, .addFilter(Person.class, formatName);
"yyyy-MM-dd"); String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
assertEquals( 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\"}]");
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 // resetting custom serializer
SerializeConfig.getGlobalInstance().put(Person.class, null); SerializeConfig.getGlobalInstance()
.put(Person.class, null);
} }
} }

View File

@ -32,10 +32,9 @@ public class Person {
@Override @Override
public String toString() { public String toString() {
return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]";
+ firstName + ", dateOfBirth=" + dateOfBirth + "]";
} }
public int getAge() { public int getAge() {
return age; return age;
} }

View File

@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest {
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
doc = Jsoup.connect("https://spring.io/blog").get(); doc = Jsoup.connect("https://spring.io/blog")
.get();
} }
@Test @Test
public void loadDocument404() throws IOException { public void loadDocument404() throws IOException {
try { 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) { } catch (HttpStatusException ex) {
assertEquals(404, ex.getStatusCode()); assertEquals(404, ex.getStatusCode());
} }
@ -35,13 +37,13 @@ public class JsoupParserIntegrationTest {
@Test @Test
public void loadDocumentCustomized() throws IOException { public void loadDocumentCustomized() throws IOException {
doc = Jsoup.connect("https://spring.io/blog") doc = Jsoup.connect("https://spring.io/blog")
.userAgent("Mozilla") .userAgent("Mozilla")
.timeout(5000) .timeout(5000)
.cookie("cookiename", "val234") .cookie("cookiename", "val234")
.cookie("anothercookie", "ilovejsoup") .cookie("anothercookie", "ilovejsoup")
.referrer("http://google.com") .referrer("http://google.com")
.header("headersecurity", "xyz123") .header("headersecurity", "xyz123")
.get(); .get();
} }
@Test @Test
@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest {
@Test @Test
public void examplesExtracting() { public void examplesExtracting() {
Element firstArticle = doc.select("article").first(); Element firstArticle = doc.select("article")
Element timeElement = firstArticle.select("time").first(); .first();
Element timeElement = firstArticle.select("time")
.first();
String dateTimeOfFirstArticle = timeElement.attr("datetime"); String dateTimeOfFirstArticle = timeElement.attr("datetime");
Element sectionDiv = firstArticle.select("section div").first(); Element sectionDiv = firstArticle.select("section div")
.first();
String sectionDivText = sectionDiv.text(); String sectionDivText = sectionDiv.text();
String articleHtml = firstArticle.html(); String articleHtml = firstArticle.html();
String outerHtml = firstArticle.outerHtml(); String outerHtml = firstArticle.outerHtml();
@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest {
@Test @Test
public void examplesModifying() { public void examplesModifying() {
Element firstArticle = doc.select("article").first(); Element firstArticle = doc.select("article")
Element timeElement = firstArticle.select("time").first(); .first();
Element sectionDiv = firstArticle.select("section div").first(); Element timeElement = firstArticle.select("time")
.first();
Element sectionDiv = firstArticle.select("section div")
.first();
String dateTimeOfFirstArticle = timeElement.attr("datetime"); String dateTimeOfFirstArticle = timeElement.attr("datetime");
timeElement.attr("datetime", "2016-12-16 15:19:54.3"); timeElement.attr("datetime", "2016-12-16 15:19:54.3");
sectionDiv.text("foo bar"); 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"), "") Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!")
.text("Checkout this amazing website!") .attr("href", "http://baeldung.com")
.attr("href", "http://baeldung.com") .attr("target", "_blank");
.attr("target", "_blank");
firstArticle.appendChild(link); firstArticle.appendChild(link);
doc.select("li.navbar-link").remove(); doc.select("li.navbar-link")
firstArticle.select("img").remove(); .remove();
firstArticle.select("img")
.remove();
assertTrue(doc.html().contains("http://baeldung.com")); assertTrue(doc.html()
.contains("http://baeldung.com"));
} }
} }

View File

@ -6,23 +6,23 @@ import org.junit.jupiter.api.Test;
public class AssertionUnitTest { public class AssertionUnitTest {
@Test @Test
public void testConvertToDoubleThrowException() { public void testConvertToDoubleThrowException() {
String age = "eighteen"; String age = "eighteen";
assertThrows(NumberFormatException.class, () -> { assertThrows(NumberFormatException.class, () -> {
convertToInt(age); convertToInt(age);
}); });
assertThrows(NumberFormatException.class, () -> { assertThrows(NumberFormatException.class, () -> {
convertToInt(age); convertToInt(age);
}); });
} }
private static Integer convertToInt(String str) { private static Integer convertToInt(String str) {
if (str == null) { if (str == null) {
return null; return null;
} }
return Integer.valueOf(str); return Integer.valueOf(str);
} }
} }

View File

@ -24,9 +24,6 @@ public class AssumptionUnitTest {
@Test @Test
void assumptionThat() { void assumptionThat() {
String someString = "Just a string"; String someString = "Just a string";
assumingThat( assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
someString.equals("Just a string"),
() -> assertEquals(2 + 2, 4)
);
} }
} }

View File

@ -24,40 +24,33 @@ public class DynamicTestsExample {
@TestFactory @TestFactory
Collection<DynamicTest> dynamicTestsWithCollection() { Collection<DynamicTest> dynamicTestsWithCollection() {
return Arrays.asList( return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
} }
@TestFactory @TestFactory
Iterable<DynamicTest> dynamicTestsWithIterable() { Iterable<DynamicTest> dynamicTestsWithIterable() {
return Arrays.asList( return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
} }
@TestFactory @TestFactory
Iterator<DynamicTest> dynamicTestsWithIterator() { Iterator<DynamicTest> dynamicTestsWithIterator() {
return Arrays.asList( return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), .iterator();
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
.iterator();
} }
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsFromIntStream() { Stream<DynamicTest> dynamicTestsFromIntStream() {
return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj( return IntStream.iterate(0, n -> n + 2)
n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); .limit(10)
.mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
} }
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsFromStream() { Stream<DynamicTest> dynamicTestsFromStream() {
// sample input and output // sample input and output
List<String> inputList = List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
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> outputList =
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
// input generator that generates inputs using inputList // input generator that generates inputs using inputList
Iterator<String> inputGenerator = inputList.iterator(); Iterator<String> inputGenerator = inputList.iterator();
@ -75,57 +68,56 @@ public class DynamicTestsExample {
// combine everything and return a Stream of DynamicTest // combine everything and return a Stream of DynamicTest
return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor); return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
} }
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsFromStreamInJava8() { Stream<DynamicTest> dynamicTestsFromStreamInJava8() {
DomainNameResolver resolver = new DomainNameResolver(); DomainNameResolver resolver = new DomainNameResolver();
List<String> inputList = List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
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> outputList =
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); return inputList.stream()
.map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { int id = inputList.indexOf(dom);
int id = inputList.indexOf(dom); assertEquals(outputList.get(id), resolver.resolveDomain(dom));
assertEquals(outputList.get(id), resolver.resolveDomain(dom)); }));
}));
} }
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() { Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() {
List<Employee> inputList = List<Employee> inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
EmployeeDao dao = new EmployeeDao(); EmployeeDao dao = new EmployeeDao();
Stream<DynamicTest> saveEmployeeStream = inputList.stream().map(emp -> Stream<DynamicTest> saveEmployeeStream = inputList.stream()
DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { .map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
Employee returned = dao.save(emp.getId()); Employee returned = dao.save(emp.getId());
assertEquals(returned.getId(), emp.getId()); assertEquals(returned.getId(), emp.getId());
})); }));
Stream<DynamicTest> saveEmployeeWithFirstNameStream Stream<DynamicTest> saveEmployeeWithFirstNameStream = inputList.stream()
= inputList.stream().filter(emp -> !emp.getFirstName().isEmpty()) .filter(emp -> !emp.getFirstName()
.isEmpty())
.map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> { .map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> {
Employee returned = dao.save(emp.getId(), emp.getFirstName()); Employee returned = dao.save(emp.getId(), emp.getFirstName());
assertEquals(returned.getId(), emp.getId()); assertEquals(returned.getId(), emp.getId());
assertEquals(returned.getFirstName(), emp.getFirstName()); assertEquals(returned.getFirstName(), emp.getFirstName());
})); }));
return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream); return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream);
} }
class DomainNameResolver { class DomainNameResolver {
private Map<String, String> ipByDomainName = new HashMap<>(); private Map<String, String> ipByDomainName = new HashMap<>();
DomainNameResolver() { DomainNameResolver() {
this.ipByDomainName.put("www.somedomain.com", "154.174.10.56"); this.ipByDomainName.put("www.somedomain.com", "154.174.10.56");
this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132"); this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132");
this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156"); this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156");
} }
public String resolveDomain(String domainName) { public String resolveDomain(String domainName) {
return ipByDomainName.get(domainName); return ipByDomainName.get(domainName);
} }

View File

@ -33,12 +33,14 @@ public class EmployeesTest {
public void whenAddEmployee_thenGetEmployee() throws SQLException { public void whenAddEmployee_thenGetEmployee() throws SQLException {
Employee emp = new Employee(1, "john"); Employee emp = new Employee(1, "john");
employeeDao.add(emp); employeeDao.add(emp);
assertEquals(1, employeeDao.findAll().size()); assertEquals(1, employeeDao.findAll()
.size());
} }
@Test @Test
public void whenGetEmployees_thenEmptyList() throws SQLException { public void whenGetEmployees_thenEmptyList() throws SQLException {
assertEquals(0, employeeDao.findAll().size()); assertEquals(0, employeeDao.findAll()
.size());
} }
public void setLogger(Logger logger) { public void setLogger(Logger logger) {

View File

@ -7,19 +7,19 @@ import org.junit.jupiter.api.Test;
public class ExceptionUnitTest { public class ExceptionUnitTest {
@Test @Test
void shouldThrowException() { void shouldThrowException() {
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
throw new UnsupportedOperationException("Not supported"); throw new UnsupportedOperationException("Not supported");
}); });
assertEquals(exception.getMessage(), "Not supported"); assertEquals(exception.getMessage(), "Not supported");
} }
@Test @Test
void assertThrowsException() { void assertThrowsException() {
String str = null; String str = null;
assertThrows(IllegalArgumentException.class, () -> { assertThrows(IllegalArgumentException.class, () -> {
Integer.valueOf(str); Integer.valueOf(str);
}); });
} }
} }

View File

@ -13,21 +13,16 @@ class FirstUnitTest {
@Test @Test
void lambdaExpressions() { void lambdaExpressions() {
List<Integer> numbers = Arrays.asList(1, 2, 3); List<Integer> numbers = Arrays.asList(1, 2, 3);
assertTrue(numbers assertTrue(numbers.stream()
.stream() .mapToInt(i -> i)
.mapToInt(i -> i) .sum() > 5, "Sum should be greater than 5");
.sum() > 5, "Sum should be greater than 5");
} }
@Disabled("test to show MultipleFailuresError") @Disabled("test to show MultipleFailuresError")
@Test @Test
void groupAssertions() { void groupAssertions() {
int[] numbers = {0, 1, 2, 3, 4}; int[] numbers = { 0, 1, 2, 3, 4 };
assertAll("numbers", assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1));
() -> assertEquals(numbers[0], 1),
() -> assertEquals(numbers[3], 3),
() -> assertEquals(numbers[4], 1)
);
} }
@Test @Test

View File

@ -13,38 +13,38 @@ import org.junit.jupiter.api.Test;
//@RunWith(JUnitPlatform.class) //@RunWith(JUnitPlatform.class)
public class JUnit5NewFeaturesUnitTest { public class JUnit5NewFeaturesUnitTest {
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName());
@BeforeAll @BeforeAll
static void setup() { static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class"); log.info("@BeforeAll - executes once before all test methods in this class");
} }
@BeforeEach @BeforeEach
void init() { void init() {
log.info("@BeforeEach - executes before each test method in this class"); log.info("@BeforeEach - executes before each test method in this class");
} }
@DisplayName("Single test successful") @DisplayName("Single test successful")
@Test @Test
void testSingleSuccessTest() { void testSingleSuccessTest() {
log.info("Success"); log.info("Success");
} }
@Test @Test
@Disabled("Not implemented yet.") @Disabled("Not implemented yet.")
void testShowSomething() { void testShowSomething() {
} }
@AfterEach @AfterEach
void tearDown() { void tearDown() {
log.info("@AfterEach - executed after each test method."); log.info("@AfterEach - executed after each test method.");
} }
@AfterAll @AfterAll
static void done() { static void done() {
log.info("@AfterAll - executed after all test methods."); log.info("@AfterAll - executed after all test methods.");
} }
} }

View File

@ -12,27 +12,28 @@ import org.junit.jupiter.api.TestFactory;
public class LiveTest { public class LiveTest {
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); 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> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
@TestFactory @TestFactory
public Stream<DynamicTest> translateDynamicTestsFromStream() { public Stream<DynamicTest> translateDynamicTestsFromStream() {
return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { return in.stream()
int id = in.indexOf(word); .map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
assertEquals(out.get(id), translate(word)); int id = in.indexOf(word);
})); assertEquals(out.get(id), translate(word));
} }));
}
private String translate(String word) { private String translate(String word) {
if ("Hello".equalsIgnoreCase(word)) { if ("Hello".equalsIgnoreCase(word)) {
return "Cześć"; return "Cześć";
} else if ("Yes".equalsIgnoreCase(word)) { } else if ("Yes".equalsIgnoreCase(word)) {
return "Tak"; return "Tak";
} else if ("No".equalsIgnoreCase(word)) { } else if ("No".equalsIgnoreCase(word)) {
return "Nie"; return "Nie";
} }
return "Error"; return "Error";
} }
} }

View File

@ -14,36 +14,36 @@ public class RepeatedTestExample {
void beforeEachTest() { void beforeEachTest() {
System.out.println("Before Each Test"); System.out.println("Before Each Test");
} }
@AfterEach @AfterEach
void afterEachTest() { void afterEachTest() {
System.out.println("After Each Test"); System.out.println("After Each Test");
System.out.println("====================="); System.out.println("=====================");
} }
@RepeatedTest(3) @RepeatedTest(3)
void repeatedTest(TestInfo testInfo) { void repeatedTest(TestInfo testInfo) {
System.out.println("Executing repeated test"); System.out.println("Executing repeated test");
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
} }
@RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME) @RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)
void repeatedTestWithLongName() { void repeatedTestWithLongName() {
System.out.println("Executing repeated test with long name"); System.out.println("Executing repeated test with long name");
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
} }
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME) @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
void repeatedTestWithShortName() { void repeatedTestWithShortName() {
System.out.println("Executing repeated test with long name"); System.out.println("Executing repeated test with long name");
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
} }
@RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}") @RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}")
void repeatedTestWithCustomDisplayName() { void repeatedTestWithCustomDisplayName() {
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
} }
@RepeatedTest(3) @RepeatedTest(3)
void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) { void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition()); System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition());

View File

@ -2,10 +2,10 @@ package com.baeldung;
public final class StringUtils { public final class StringUtils {
public static Double convertToDouble(String str) { public static Double convertToDouble(String str) {
if (str == null) { if (str == null) {
return null; return null;
} }
return Double.valueOf(str); return Double.valueOf(str);
} }
} }

View File

@ -25,13 +25,15 @@ public class TestLauncher {
//@formatter:on //@formatter:on
TestPlan plan = LauncherFactory.create().discover(request); TestPlan plan = LauncherFactory.create()
.discover(request);
Launcher launcher = LauncherFactory.create(); Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener(); SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener }); launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
launcher.execute(request); launcher.execute(request);
summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out)); summaryGeneratingListener.getSummary()
.printTo(new PrintWriter(System.out));
} }
} }

View File

@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver {
@Override @Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class); return parameterContext.getParameter()
.getType()
.equals(EmployeeJdbcDao.class);
} }
@Override @Override

View File

@ -10,7 +10,9 @@ public class LoggingExtension implements TestInstancePostProcessor {
@Override @Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
Logger logger = LogManager.getLogger(testInstance.getClass()); Logger logger = LogManager.getLogger(testInstance.getClass());
testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger); testInstance.getClass()
.getMethod("setLogger", Logger.class)
.invoke(testInstance, logger);
} }
} }

View File

@ -30,9 +30,10 @@ public class AssertionsExampleTest {
List<Integer> list = Arrays.asList(1, 2, 3); List<Integer> list = Arrays.asList(1, 2, 3);
Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0)
.intValue(), 1), .intValue(), 1), () -> Assertions.assertEquals(
() -> Assertions.assertEquals(list.get(1) list.get(1)
.intValue(), 2), .intValue(),
2),
() -> Assertions.assertEquals(list.get(2) () -> Assertions.assertEquals(list.get(2)
.intValue(), 3)); .intValue(), 3));
} }

View File

@ -9,42 +9,51 @@ import org.junit.jupiter.api.extension.ParameterResolver;
public class InvalidPersonParameterResolver implements ParameterResolver { public class InvalidPersonParameterResolver implements ParameterResolver {
/** /**
* The "bad" (invalid) data for testing purposes has to go somewhere, right? * The "bad" (invalid) data for testing purposes has to go somewhere, right?
*/ */
public static Person[] INVALID_PERSONS = { public static Person[] INVALID_PERSONS = { new Person().setId(1L)
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"), .setLastName("Ad_ams")
new Person().setId(2L).setLastName(",Baker").setFirstName(""), .setFirstName("Jill,"),
new Person().setId(3L).setLastName(null).setFirstName(null), new Person().setId(2L)
new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"), .setLastName(",Baker")
new Person().setId(5L).setLastName("").setFirstName("English, Jane"), .setFirstName(""),
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, new Person().setId(3L)
// TODO: ADD MORE DATA HERE .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 @Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException { Object ret = null;
Object ret = null; //
// // Return a random, valid Person object if Person.class is the type of Parameter
// Return a random, valid Person object if Person.class is the type of Parameter /// to be resolved. Otherwise return null.
/// to be resolved. Otherwise return null. if (parameterContext.getParameter()
if (parameterContext.getParameter().getType() == Person.class) { .getType() == Person.class) {
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
}
return ret;
} }
return ret;
}
@Override @Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException { boolean ret = false;
boolean ret = false; //
// // If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here! if (parameterContext.getParameter()
if (parameterContext.getParameter().getType() == Person.class) { .getType() == Person.class) {
ret = true; ret = true;
}
return ret;
} }
return ret;
}
} }

View File

@ -9,35 +9,35 @@ package com.baeldung.param;
*/ */
public class Person { public class Person {
private Long id; private Long id;
private String lastName; private String lastName;
private String firstName; private String firstName;
public Long getId() { public Long getId() {
return id; return id;
} }
public Person setId(Long id) { public Person setId(Long id) {
this.id = id; this.id = id;
return this; return this;
} }
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public Person setLastName(String lastName) { public Person setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
return this; return this;
} }
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public Person setFirstName(String firstName) { public Person setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
return this; return this;
} }
} }

View File

@ -11,132 +11,122 @@ import java.util.Arrays;
*/ */
public class PersonValidator { public class PersonValidator {
/** /**
* Contrived checked exception to illustrate one possible * Contrived checked exception to illustrate one possible
* way to handle validation errors (via a checked exception). * way to handle validation errors (via a checked exception).
* *
* @author J Steven Perry * @author J Steven Perry
* *
*/ */
public static class ValidationException extends Exception { 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; public static boolean validateFirstName(Person person) throws ValidationException {
boolean ret = true;
// Probably should implement some more constructors, but don't want // The validation rules go here.
/// to tarnish the lesson... // 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 * @param person
* The message accompanying the exception. Should be meaningful. * 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) { public static boolean validateLastName(Person person) throws ValidationException {
super(message); 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,
private static final String[] ILLEGAL_NAME_CHARACTERS = { * 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.
* Validate the first name of the specified Person object. */
* private static boolean isStringValid(String candidate, String[] illegalCharacters) {
* @param person boolean ret = true;
* The Person object to validate. for (String illegalChar : illegalCharacters) {
* if (candidate.contains(illegalChar)) {
* @return - returns true if the specified Person is valid ret = false;
* break;
* @throws ValidationException }
* - this Exception is thrown if any kind of validation error occurs. }
*/ return ret;
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;
}
/**
* 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;
}
} }

View File

@ -15,88 +15,88 @@ import org.junit.runner.RunWith;
@DisplayName("Testing PersonValidator") @DisplayName("Testing PersonValidator")
public class PersonValidatorTest { 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 * Nested class, uses ExtendWith
* running all of the data through at least once. * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
* * to feed Test methods with "good" data.
* @param person
* A valid Person object to validate.
*/ */
@RepeatedTest(value = 10) @Nested
@DisplayName("All first names are valid") @DisplayName("When using Valid data")
public void validateFirstName(Person person) { @ExtendWith(ValidPersonParameterResolver.class)
try { public class ValidData {
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 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 * Nested class, uses ExtendWith
* running all of the data through at least once. * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
* * to feed Test methods with "bad" data.
* @param person
* A valid Person object to validate.
*/ */
@RepeatedTest(value = 10) @Nested
@DisplayName("All last names are valid") @DisplayName("When using Invalid data")
public void validateLastName(Person person) { @ExtendWith(InvalidPersonParameterResolver.class)
try { public class InvalidData {
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
* 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));
}
}
} }

View File

@ -9,42 +9,53 @@ import org.junit.jupiter.api.extension.ParameterResolver;
public class ValidPersonParameterResolver implements ParameterResolver { public class ValidPersonParameterResolver implements ParameterResolver {
/** /**
* The "good" (valid) data for testing purposes has to go somewhere, right? * The "good" (valid) data for testing purposes has to go somewhere, right?
*/ */
public static Person[] VALID_PERSONS = { public static Person[] VALID_PERSONS = { new Person().setId(1L)
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"), .setLastName("Adams")
new Person().setId(2L).setLastName("Baker").setFirstName("James"), .setFirstName("Jill"),
new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"), new Person().setId(2L)
new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"), .setLastName("Baker")
new Person().setId(5L).setLastName("English").setFirstName("Jane"), .setFirstName("James"),
new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"), new Person().setId(3L)
// TODO: ADD MORE DATA HERE .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 @Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException { Object ret = null;
Object ret = null; //
// // Return a random, valid Person object if Person.class is the type of Parameter
// Return a random, valid Person object if Person.class is the type of Parameter /// to be resolved. Otherwise return null.
/// to be resolved. Otherwise return null. if (parameterContext.getParameter()
if (parameterContext.getParameter().getType() == Person.class) { .getType() == Person.class) {
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
}
return ret;
} }
return ret;
}
@Override @Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException { boolean ret = false;
boolean ret = false; //
// // If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here! if (parameterContext.getParameter()
if (parameterContext.getParameter().getType() == Person.class) { .getType() == Person.class) {
ret = true; ret = true;
}
return ret;
} }
return ret;
}
} }

View File

@ -6,7 +6,7 @@ import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class) @RunWith(JUnitPlatform.class)
@SelectPackages("com.baeldung") @SelectPackages("com.baeldung")
//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) // @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
public class AllTests { public class AllTests {
} }