Build optimization 6.07 (#2219)

* refactor testng

* refactor testng

* Remove test suites from surefire

* Refactor

* Refactor
This commit is contained in:
Grzegorz Piwowarek 2017-07-06 23:22:41 +02:00 committed by GitHub
parent c99bb7fced
commit b9b230f83e
66 changed files with 524 additions and 1311 deletions

View File

@ -1,24 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -1,49 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>baeldung</groupId>
<artifactId>springdatainjectiondemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringDataInjectionDemo</name>
<description>Spring Data Injection Demp</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,12 +0,0 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataInjectionDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataInjectionDemoApplication.class, args);
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.didemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.didemo.model.Order;
import com.baeldung.didemo.service.CustomerServiceConstructorDI;
import com.baeldung.didemo.service.CustomerServiceConstructorWithoutSpringDI;
import com.baeldung.didemo.service.CustomerServiceFieldDI;
import com.baeldung.didemo.service.CustomerServiceSetterDI;
import com.baeldung.didemo.service.OrderService;
@RestController
@RequestMapping(value = "/orders")
public class OrderController {
@Autowired
CustomerServiceConstructorDI constructorDI;
@Autowired
CustomerServiceFieldDI fieldDI;
@Autowired
CustomerServiceSetterDI setterDI;
@RequestMapping(method = RequestMethod.GET)
public List<Order> getOrdersFieldDI(@RequestParam(required = false) String dIMethod) {
if ("setter".equals(dIMethod)) {
return setterDI.getCustomerOrders(1l);
} else if ("constructor".equals(dIMethod)) {
return constructorDI.getCustomerOrders(1l);
} else if ("field".equals(dIMethod)) {
return fieldDI.getCustomerOrders(1l);
} else {
OrderService orderSvc = new OrderService();
CustomerServiceConstructorWithoutSpringDI customerSvc = new CustomerServiceConstructorWithoutSpringDI(orderSvc);
return customerSvc.getCustomerOrders(1l);
}
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung.didemo.model;
public class Order {
private Integer id;
private String item;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
// other order properties..
}

View File

@ -1,25 +0,0 @@
package com.baeldung.didemo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class CustomerServiceConstructorDI {
OrderService orderService;
@Autowired
public CustomerServiceConstructorDI(OrderService orderService) {
super();
this.orderService = orderService;
}
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
}

View File

@ -1,20 +0,0 @@
package com.baeldung.didemo.service;
import java.util.List;
import com.baeldung.didemo.model.Order;
public class CustomerServiceConstructorWithoutSpringDI {
OrderService orderService;
public CustomerServiceConstructorWithoutSpringDI(OrderService orderService) {
super();
this.orderService = orderService;
}
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
}

View File

@ -1,19 +0,0 @@
package com.baeldung.didemo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class CustomerServiceFieldDI {
@Autowired
OrderService orderService;
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
}

View File

@ -1,24 +0,0 @@
package com.baeldung.didemo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class CustomerServiceSetterDI {
OrderService orderService;
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
@Autowired
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.didemo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class OrderService {
public List<Order> getOrdersForCustomer(Long id) {
List<Order> orders = new ArrayList<Order>();
Order order1 = new Order();
order1.setId(1);
order1.setItem("Pizza");
Order order2 = new Order();
order2.setId(1);
order2.setItem("Garlic Bread");
orders.add(order1);
orders.add(order2);
return orders;
}
}

View File

@ -1,65 +0,0 @@
package com.baeldung.didemo;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.didemo.model.Order;
import com.baeldung.didemo.service.CustomerServiceConstructorDI;
import com.baeldung.didemo.service.CustomerServiceFieldDI;
import com.baeldung.didemo.service.CustomerServiceSetterDI;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataInjectionDemoApplicationTests {
@Autowired
CustomerServiceConstructorDI constructorDI;
@Autowired
CustomerServiceFieldDI fieldDI;
@Autowired
CustomerServiceSetterDI setterDI;
@Test
public void givenConstructorDI_whenNumberOfOrdersIsTwo_thenCorrect() {
List<Order> orders = constructorDI.getCustomerOrders(1l);
Assert.assertNotNull(orders);
Assert.assertTrue(orders.size() == 2);
}
@Test
public void givenFieldDI_whenNumberOfOrdersIsTwo_thenCorrect() {
List<Order> orders = fieldDI.getCustomerOrders(1l);
Assert.assertNotNull(orders);
Assert.assertTrue(orders.size() == 2);
}
@Test
public void givenSetterDI_whenNumberOfOrdersIsTwo_thenCorrect() {
List<Order> orders = setterDI.getCustomerOrders(1l);
Assert.assertNotNull(orders);
Assert.assertTrue(orders.size() == 2);
}
@Test
public void givenAllThreeTypesOfDI_whenNumberOfOrdersIsEqualInAll_thenCorrect() {
List<Order> ordersSetter = setterDI.getCustomerOrders(1l);
List<Order> ordersConstructor = constructorDI.getCustomerOrders(1l);
List<Order> ordersField = fieldDI.getCustomerOrders(1l);
Assert.assertNotNull(ordersSetter);
Assert.assertNotNull(ordersConstructor);
Assert.assertNotNull(ordersField);
Assert.assertTrue(ordersSetter.size() == 2 && ordersConstructor.size() == ordersSetter.size() && ordersField.size() == ordersSetter.size());
}
}

View File

@ -1,24 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>baeldung</groupId>
<artifactId>call-all-getters</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>call-all-getters</name>
<description>Calling all getters using Introspector</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,18 +0,0 @@
package com.baeldung;
import java.util.List;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
public class CallAllGettersApplication {
public static void main(String[] args) throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> nullProps = Utils.getNullPropertiesList(customer);
System.out.println(nullProps);
}
}

View File

@ -1,63 +0,0 @@
package com.baeldung.reflection.model;
/**
*
* @author himanshumantri
*
*/
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", emailId=").append(emailId).append(", phoneNumber=")
.append(phoneNumber).append("]");
return builder.toString();
}
public Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

View File

@ -1,43 +0,0 @@
package com.baeldung.reflection.util;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.baeldung.reflection.model.Customer;
public class Utils {
public static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
List<String> nullProps = propDescList.stream()
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
return nullProps;
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
Predicate<PropertyDescriptor> isNull = new Predicate<PropertyDescriptor>() {
@Override
public boolean test(PropertyDescriptor pd) {
Method getterMethod = pd.getReadMethod();
boolean result = false;
try {
result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
// Handle the exception
e.printStackTrace();
}
return result;
}
};
return isNull;
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
public class CallAllGettersApplicationTests {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = Utils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId","phoneNumber");
Assert.assertTrue(result.size() == expectedFieldNames.size());
Assert.assertTrue(result.containsAll(expectedFieldNames));
}
}

View File

@ -9,6 +9,8 @@ import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
public class ArrayCopyUtilUnitTest {
private static Employee[] employees;
private static final int MAX = 2;
@ -46,10 +48,10 @@ public class ArrayCopyUtilUnitTest {
System.arraycopy(array, 2, copiedArray, 0, 3);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[2]);
Assert.assertTrue(copiedArray[1] == array[3]);
Assert.assertTrue(copiedArray[2] == array[4]);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[2]);
assertTrue(copiedArray[1] == array[3]);
assertTrue(copiedArray[2] == array[4]);
}
@Test
@ -58,10 +60,10 @@ public class ArrayCopyUtilUnitTest {
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[1]);
Assert.assertTrue(copiedArray[1] == array[2]);
Assert.assertTrue(copiedArray[2] == array[3]);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[1]);
assertTrue(copiedArray[1] == array[2]);
assertTrue(copiedArray[2] == array[3]);
}
@Test
@ -73,9 +75,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
assertTrue(copiedArray[1] != array[1]);
}
@Test
@ -85,7 +87,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@ -96,9 +98,9 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
assertTrue(copiedArray[1] != array[1]);
}
@Test
@ -108,7 +110,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
@ -138,7 +140,7 @@ public class ArrayCopyUtilUnitTest {
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test

View File

@ -24,7 +24,7 @@ public class CompletableFutureLongRunningUnitTest {
assertEquals("Hello", result);
}
public Future<String> calculateAsync() throws InterruptedException {
private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
@ -44,7 +44,7 @@ public class CompletableFutureLongRunningUnitTest {
assertEquals("Hello", result);
}
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {

View File

@ -24,8 +24,8 @@ public class LongAccumulatorUnitTest {
//when
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);

View File

@ -17,7 +17,7 @@ public class CopyOnWriteArrayListUnitTest {
public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();
@ -42,7 +42,7 @@ public class CopyOnWriteArrayListUnitTest {
public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() {
//given
final CopyOnWriteArrayList<Integer> numbers =
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
//when
Iterator<Integer> iterator = numbers.iterator();

View File

@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertEquals;
@ -19,7 +23,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = 500;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@ -41,7 +45,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = 10_000;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);
@ -63,7 +67,7 @@ public class DelayQueueIntegrationTest {
int delayOfEachProducedMessageMilliseconds = -10_000;
DelayQueueConsumer consumer = new DelayQueueConsumer(queue, numberOfElementsToProduce);
DelayQueueProducer producer
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
= new DelayQueueProducer(queue, numberOfElementsToProduce, delayOfEachProducedMessageMilliseconds);
//when
executor.submit(producer);

View File

@ -1,10 +1,10 @@
package com.baeldung.concurrent.future;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.concurrent.ForkJoinPool;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FactorialSquareCalculatorUnitTest {

View File

@ -8,7 +8,12 @@ import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

View File

@ -9,65 +9,65 @@ import static junit.framework.TestCase.assertEquals;
public class SharedObjectWithLockManualTest {
@Test
public void whenLockAcquired_ThenLockedIsTrue() {
final SharedObjectWithLock object = new SharedObjectWithLock();
@Test
public void whenLockAcquired_ThenLockedIsTrue() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
assertEquals(true, object.isLocked());
service.shutdown();
}
service.shutdown();
}
@Test
public void whenLocked_ThenQueuedThread() {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
@Test
public void whenLocked_ThenQueuedThread() {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
executeThreads(object, threadCount, service);
assertEquals(object.hasQueuedThreads(), true);
assertEquals(object.hasQueuedThreads(), true);
service.shutdown();
service.shutdown();
}
}
public void whenTryLock_ThenQueuedThread() {
final SharedObjectWithLock object = new SharedObjectWithLock();
public void whenTryLock_ThenQueuedThread() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
assertEquals(true, object.isLocked());
service.shutdown();
}
service.shutdown();
}
@Test
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
@Test
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
Thread.sleep(1000);
assertEquals(object.getCounter(), 4);
executeThreads(object, threadCount, service);
Thread.sleep(1000);
assertEquals(object.getCounter(), 4);
service.shutdown();
service.shutdown();
}
}
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(object::perform);
}
}
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(object::perform);
}
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.concurrent.locks;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
@ -10,49 +9,49 @@ import static junit.framework.TestCase.assertEquals;
public class SynchronizedHashMapWithRWLockManualTest {
@Test
public void whenWriting_ThenNoReading() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
@Test
public void whenWriting_ThenNoReading() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeWriterThreads(object, threadCount, service);
executeWriterThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), false);
assertEquals(object.isReadLockAvailable(), false);
service.shutdown();
}
service.shutdown();
}
@Test
public void whenReading_ThenMultipleReadingAllowed() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 5;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
@Test
public void whenReading_ThenMultipleReadingAllowed() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 5;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeReaderThreads(object, threadCount, service);
executeReaderThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), true);
assertEquals(object.isReadLockAvailable(), true);
service.shutdown();
}
service.shutdown();
}
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
try {
object.put("key" + threadCount, "value" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
try {
object.put("key" + threadCount, "value" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++)
service.execute(() -> {
object.get("key" + threadCount);
});
}
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++)
service.execute(() -> {
object.get("key" + threadCount);
});
}
}

View File

@ -42,7 +42,7 @@ public class PriorityBlockingQueueIntegrationTest {
try {
Integer poll = queue.take();
LOG.debug("Polled: " + poll);
} catch (InterruptedException e) {
} catch (InterruptedException ignored) {
}
}
});

View File

@ -1,13 +1,13 @@
package com.baeldung.concurrent.synchronize;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BaeldungSychronizedBlockTest {
@ -17,7 +17,7 @@ public class BaeldungSychronizedBlockTest {
BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();
IntStream.range(0, 1000)
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount());
@ -28,7 +28,7 @@ public class BaeldungSychronizedBlockTest {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());

View File

@ -1,14 +1,14 @@
package com.baeldung.concurrent.synchronize;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BaeldungSynchronizeMethodsTest {
@ -19,7 +19,7 @@ public class BaeldungSynchronizeMethodsTest {
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(method::calculate));
.forEach(count -> service.submit(method::calculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSum());
@ -31,7 +31,7 @@ public class BaeldungSynchronizeMethodsTest {
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(method::synchronisedCalculate));
.forEach(count -> service.submit(method::synchronisedCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSyncSum());
@ -42,7 +42,7 @@ public class BaeldungSynchronizeMethodsTest {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedMethods.staticSum);

View File

@ -7,13 +7,15 @@ import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UseLocalDateTimeUnitTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
}
}

View File

@ -7,48 +7,50 @@ import java.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UseLocalDateUnitTest {
UseLocalDate useLocalDate = new UseLocalDate();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
}
@Test
public void whenUsingClock_thenLocalDate() {
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
}
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
}
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
}
@Test
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
}
}

View File

@ -83,7 +83,7 @@ public class ComputerUtilsUnitTest {
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
Double initialValue = new Double(999.99);
Double initialValue = 999.99;
final Double actualValue = macbookPro.calculateValue(initialValue);
Assert.assertEquals(766.659, actualValue, 0.0);
}

View File

@ -6,7 +6,12 @@ import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@ -14,6 +19,10 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class FileOperationsManualTest {
@Test
@ -25,7 +34,7 @@ public class FileOperationsManualTest {
InputStream inputStream = new FileInputStream(file);
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -36,7 +45,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -47,7 +56,7 @@ public class FileOperationsManualTest {
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@ -61,7 +70,7 @@ public class FileOperationsManualTest {
InputStream inputStream = urlConnection.getInputStream();
String data = readFromInputStream(inputStream);
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
@ -72,7 +81,7 @@ public class FileOperationsManualTest {
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -84,7 +93,7 @@ public class FileOperationsManualTest {
byte[] fileBytes = Files.readAllBytes(path);
String data = new String(fileBytes);
Assert.assertEquals(expectedData, data.trim());
assertEquals(expectedData, data.trim());
}
@Test
@ -98,7 +107,7 @@ public class FileOperationsManualTest {
lines.forEach(line -> data.append(line).append("\n"));
lines.close();
Assert.assertEquals(expectedData, data.toString().trim());
assertEquals(expectedData, data.toString().trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {

View File

@ -1,15 +1,13 @@
package com.baeldung.filesystem.jndi.test;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import com.baeldung.filesystem.jndi.LookupFSJNDI;
import org.junit.Test;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.File;
import org.junit.Test;
import com.baeldung.filesystem.jndi.LookupFSJNDI;
import static org.junit.Assert.assertNotNull;
public class LookupFSJNDIIntegrationTest {
LookupFSJNDI fsjndi;

View File

@ -25,7 +25,7 @@ public class FunctionalInterfaceUnitTest {
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("John", s -> s.length());
Integer value = nameMap.computeIfAbsent("John", String::length);
assertEquals(new Integer(4), nameMap.get("John"));
assertEquals(new Integer(4), value);

View File

@ -2,7 +2,7 @@ package com.baeldung.hashing;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class SHA256HashingUnitTest {

View File

@ -2,7 +2,6 @@ package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
@ -17,6 +16,9 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HttpRequestLiveTest {
@Test
@ -39,7 +41,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
@ -67,7 +69,7 @@ public class HttpRequestLiveTest {
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}

View File

@ -15,7 +15,7 @@ class OffHeapArray {
return (Unsafe) f.get(null);
}
public OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
this.size = size;
address = getUnsafe().allocateMemory(size * BYTE);
}
@ -32,7 +32,7 @@ class OffHeapArray {
return size;
}
public void freeMemory() throws NoSuchFieldException, IllegalAccessException {
void freeMemory() throws NoSuchFieldException, IllegalAccessException {
getUnsafe().freeMemory(address);
}

View File

@ -1,24 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>baeldung</groupId>
<artifactId>spring-check-null</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-check-if-a-property-is-null</name>
<description>Calling getters using Introspector</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,21 +0,0 @@
package com.baeldung;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
@SpringBootApplication
public class SpringCheckIfAPropertyIsNullApplication {
public static void main(String[] args) throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> nullProps = Utils.getNullPropertiesList(customer);
System.out.println(nullProps);
}
}

View File

@ -1,63 +0,0 @@
package com.baeldung.reflection.model;
/**
*
* @author himanshumantri
*
*/
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", emailId=").append(emailId).append(", phoneNumber=")
.append(phoneNumber).append("]");
return builder.toString();
}
public Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

View File

@ -1,34 +0,0 @@
package com.baeldung.reflection.util;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.baeldung.reflection.model.Customer;
public class Utils {
public static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
List<String> nullProps = new ArrayList<String>();
propDescList.stream().forEach(p -> {
Method getterMethod = p.getReadMethod();
try {
if (getterMethod != null && getterMethod.invoke(customer) == null) {
// If the value if null for that field
nullProps.add(p.getName());
}
} catch (Exception e) {
// Handle the exception
e.printStackTrace();
}
});
return nullProps;
}
}

View File

@ -1,31 +0,0 @@
package com.baeldung;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringCheckIfAPropertyIsNullApplicationTests {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = Utils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId","phoneNumber");
Assert.assertTrue(result.size() == expectedFieldNames.size());
Assert.assertTrue(result.containsAll(expectedFieldNames));
}
}

View File

@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
public class AopLoggingIntegrationTest {
@Before

View File

@ -2,7 +2,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>testng</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
@ -43,27 +42,6 @@
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<suiteXmlFiles>
<suiteXmlFile>src\test\resources\parametrized_testng.xml</suiteXmlFile>
<suiteXmlFile>src\test\resources\test_group.xml</suiteXmlFile>
<suiteXmlFile>src\test\resources\test_setup.xml</suiteXmlFile>
<suiteXmlFile>src\test\resources\test_suite.xml</suiteXmlFile>
</suiteXmlFiles>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -1,77 +0,0 @@
package baeldung.com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParametrizedUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ParametrizedUnitTest.class);
@Test
@Parameters({"value", "isEven"})
public void givenNumberFromXML_ifEvenCheckOK_thenCorrect(int value, boolean isEven) {
Assert.assertEquals(isEven, value % 2 == 0);
}
@DataProvider(name = "numbers")
public static Object[][] evenNumbers() {
return new Object[][]{{1, false}, {2, true}, {4, true}};
}
@Test(dataProvider = "numbers")
public void givenNumberFromDataProvider_ifEvenCheckOK_thenCorrect(Integer number, boolean expected) {
Assert.assertEquals(expected, number % 2 == 0);
}
@Test(dataProvider = "numbersObject")
public void givenNumberObjectFromDataProvider_ifEvenCheckOK_thenCorrect(EvenNumber number) {
Assert.assertEquals(number.isEven(), number.getValue() % 2 == 0);
}
@DataProvider(name = "numbersObject")
public Object[][] parameterProvider() {
return new Object[][]{{new EvenNumber(1, false)}, {new EvenNumber(2, true)}, {new EvenNumber(4, true),}};
}
}
class EvenNumber {
private int value;
private boolean isEven;
public EvenNumber(int number, boolean isEven) {
this.value = number;
this.isEven = isEven;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public boolean isEven() {
return isEven;
}
public void setEven(boolean even) {
isEven = even;
}
@Override
public String toString() {
return "EvenNumber{" +
"value=" + value +
", isEven=" + isEven +
'}';
}
}

View File

@ -1,21 +0,0 @@
package baeldung.com;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PriorityUnitTest {
private String testString = "10";
private int testInt = 23;
@Test(priority = 1)
public void givenString_whenChangedToInt_thenCorrect() {
Assert.assertTrue(Integer.valueOf(testString) instanceof Integer);
}
@Test(priority = 2)
public void givenInt_whenChangedToString_thenCorrect() {
Assert.assertTrue(String.valueOf(testInt) instanceof String);
}
}

View File

@ -1,25 +1,25 @@
package baeldung.com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DependentUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentUnitTest.class);
private String email = "abc@qwe.com";
@Test
public void givenEmail_ifValid_thenTrue() {
boolean valid = email.contains("@");
Assert.assertEquals(valid, true);
}
@Test(dependsOnMethods = {"givenEmail_ifValid_thenTrue"})
public void givenValidEmail_whenLoggedIn_thenTrue() {
LOGGER.info("Email {} valid >> logging in", email);
}
}
package com.baeldung;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DependentLongRunningUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentLongRunningUnitTest.class);
private String email = "abc@qwe.com";
@Test
public void givenEmail_ifValid_thenTrue() {
boolean valid = email.contains("@");
Assert.assertEquals(valid, true);
}
@Test(dependsOnMethods = {"givenEmail_ifValid_thenTrue"})
public void givenValidEmail_whenLoggedIn_thenTrue() {
LOGGER.info("Email {} valid >> logging in", email);
}
}

View File

@ -1,44 +1,44 @@
package baeldung.com;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
public class GroupIntegrationTest {
@BeforeGroups("database")
public void setupDB() {
System.out.println("setupDB()");
}
@AfterGroups("database")
public void cleanDB() {
System.out.println("cleanDB()");
}
@Test(groups = "selenium-test")
public void runSelenium() {
System.out.println("runSelenium()");
}
@Test(groups = "selenium-test")
public void runSelenium1() {
System.out.println("runSelenium()1");
}
@Test(groups = "database")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}
@Test(groups = "database")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}
@Test(dependsOnGroups = {"database", "selenium-test"})
public void runFinal() {
System.out.println("runFinal");
}
package com.baeldung;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
public class GroupIntegrationTest {
@BeforeGroups("database")
public void setupDB() {
System.out.println("setupDB()");
}
@AfterGroups("database")
public void cleanDB() {
System.out.println("cleanDB()");
}
@Test(groups = "selenium-test")
public void runSelenium() {
System.out.println("runSelenium()");
}
@Test(groups = "selenium-test")
public void runSelenium1() {
System.out.println("runSelenium()1");
}
@Test(groups = "database")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}
@Test(groups = "database")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}
@Test(dependsOnGroups = {"database", "selenium-test"})
public void runFinal() {
System.out.println("runFinal");
}
}

View File

@ -1,14 +1,14 @@
package baeldung.com;
import org.testng.Assert;
import org.testng.annotations.Test;
public class MultiThreadedIntegrationTest {
@Test(threadPoolSize = 5, invocationCount = 10, timeOut = 1000)
public void givenMethod_whenRunInThreads_thenCorrect() {
int count = Thread.activeCount();
Assert.assertTrue(count > 1);
}
}
package com.baeldung;
import org.testng.Assert;
import org.testng.annotations.Test;
public class MultiThreadedIntegrationTest {
@Test(threadPoolSize = 5, invocationCount = 10, timeOut = 1000)
public void givenMethod_whenRunInThreads_thenCorrect() {
int count = Thread.activeCount();
Assert.assertTrue(count > 1);
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class ParametrizedLongRunningUnitTest {
@Test
@Parameters({"value", "isEven"})
public void givenNumberFromXML_ifEvenCheckOK_thenCorrect(int value, boolean isEven) {
assertEquals(isEven, value % 2 == 0);
}
@DataProvider(name = "numbers")
public static Object[][] evenNumbers() {
return new Object[][]{{1, false}, {2, true}, {4, true}};
}
@Test(dataProvider = "numbers")
public void givenNumberFromDataProvider_ifEvenCheckOK_thenCorrect(Integer number, boolean expected) {
assertEquals(expected, number % 2 == 0);
}
@Test(dataProvider = "numbersObject")
public void givenNumberObjectFromDataProvider_ifEvenCheckOK_thenCorrect(EvenNumber number) {
assertEquals(number.isEven(), number.getValue() % 2 == 0);
}
@DataProvider(name = "numbersObject")
public Object[][] parameterProvider() {
return new Object[][]{{new EvenNumber(1, false)}, {new EvenNumber(2, true)}, {new EvenNumber(4, true),}};
}
class EvenNumber {
private int value;
private boolean isEven;
EvenNumber(int number, boolean isEven) {
this.value = number;
this.isEven = isEven;
}
int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
boolean isEven() {
return isEven;
}
public void setEven(boolean even) {
isEven = even;
}
@Override
public String toString() {
return "EvenNumber{" +
"value=" + value +
", isEven=" + isEven +
'}';
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung;
import org.testng.annotations.Test;
import static org.testng.Assert.assertTrue;
public class PriorityLongRunningUnitTest {
@Test(priority = 1)
public void givenString_whenChangedToInt_thenCorrect() {
String testString = "10";
assertTrue(Integer.valueOf(testString) instanceof Integer);
}
@Test(priority = 2)
public void givenInt_whenChangedToString_thenCorrect() {
int testInt = 23;
assertTrue(String.valueOf(testInt) instanceof String);
}
}

View File

@ -1,14 +1,14 @@
package baeldung.com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class RegistrationUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationUnitTest.class);
@Test
public void whenCalledFromSuite_thanOK() {
LOGGER.info("Registration successful");
}
}
package com.baeldung;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class RegistrationLongRunningUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationLongRunningUnitTest.class);
@Test
public void whenCalledFromSuite_thanOK() {
LOGGER.info("Registration successful");
}
}

View File

@ -1,14 +1,14 @@
package baeldung.com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class SignInUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SignInUnitTest.class);
@Test
public void whenCalledFromSuite_thanOK() {
LOGGER.info("SignIn successful");
}
}
package com.baeldung;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class SignInLongRunningUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SignInLongRunningUnitTest.class);
@Test
public void whenCalledFromSuite_thanOK() {
LOGGER.info("SignIn successful");
}
}

View File

@ -1,28 +1,28 @@
package baeldung.com;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SimpleUnitTest extends TestNG {
private int number;
@BeforeClass
public void setup() {
number = 12;
}
@AfterClass
public void tearDown() {
number = 0;
}
@Test
public void givenNumber_whenEven_thenTrue() {
Assert.assertTrue(number % 2 == 0);
}
}
package com.baeldung;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SimpleLongRunningUnitTest extends TestNG {
private int number;
@BeforeClass
public void setup() {
number = 12;
}
@AfterClass
public void tearDown() {
number = 0;
}
@Test
public void givenNumber_whenEven_thenTrue() {
Assert.assertTrue(number % 2 == 0);
}
}

View File

@ -1,98 +1,102 @@
package baeldung.com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.*;
import java.util.ArrayList;
import java.util.List;
public class SummationServiceIntegrationTest extends TestNG {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentUnitTest.class);
private List<Integer> numbers;
private int testCount = 0;
@BeforeClass
public void initialize() {
numbers = new ArrayList<>();
}
@AfterClass
public void tearDown() {
numbers = null;
}
@BeforeSuite(groups = "regression")
public void runBeforeRegressionSuite() {
numbers = new ArrayList<>();
numbers.add(-11);
numbers.add(2);
}
@AfterSuite(groups = "regression")
public void runAfterRegressionSuite() {
numbers = null;
}
@BeforeGroups("negative_tests")
public void runBeforeEachNegativeGroup() {
numbers.clear();
}
@BeforeGroups("regression")
public void runBeforeEachRegressionGroup() {
numbers.add(-11);
numbers.add(2);
}
@BeforeGroups("positive_tests")
public void runBeforeEachPositiveGroup() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@AfterGroups("positive_tests,regression,negative_tests")
public void runAfterEachGroup() {
numbers.clear();
}
@BeforeMethod
public void runBeforeEachTest() {
testCount++;
}
@AfterMethod
public void runAfterEachTest() {
}
@Test(groups = "positive_tests", enabled = false)
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream().reduce(0, Integer::sum);
Assert.assertEquals(sum, 6);
}
@Test(groups = "negative_tests")
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream().reduce(0, Integer::sum);
Assert.assertEquals(0, sum);
}
@Test(groups = "regression")
public void givenNegativeNumber_sumLessthanZero_thenCorrect() {
int sum = numbers.stream().reduce(0, Integer::sum);
Assert.assertTrue(sum < 0);
}
@Test(expectedExceptions = ArithmeticException.class)
public void givenNumber_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
}
package com.baeldung;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
public class SummationServiceIntegrationTest extends TestNG {
private List<Integer> numbers;
private int testCount = 0;
@BeforeClass
public void initialize() {
numbers = new ArrayList<>();
}
@AfterClass
public void tearDown() {
numbers = null;
}
@BeforeSuite(groups = "regression")
public void runBeforeRegressionSuite() {
numbers = new ArrayList<>();
numbers.add(-11);
numbers.add(2);
}
@AfterSuite(groups = "regression")
public void runAfterRegressionSuite() {
numbers = null;
}
@BeforeGroups("negative_tests")
public void runBeforeEachNegativeGroup() {
numbers.clear();
}
@BeforeGroups("regression")
public void runBeforeEachRegressionGroup() {
numbers.add(-11);
numbers.add(2);
}
@BeforeGroups("positive_tests")
public void runBeforeEachPositiveGroup() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@AfterGroups("positive_tests,regression,negative_tests")
public void runAfterEachGroup() {
numbers.clear();
}
@BeforeMethod
public void runBeforeEachTest() {
testCount++;
}
@AfterMethod
public void runAfterEachTest() {
}
@Test(groups = "positive_tests", enabled = false)
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream().reduce(0, Integer::sum);
Assert.assertEquals(sum, 6);
}
@Test(groups = "negative_tests")
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream().reduce(0, Integer::sum);
Assert.assertEquals(0, sum);
}
@Test(groups = "regression")
public void givenNegativeNumber_sumLessthanZero_thenCorrect() {
int sum = numbers.stream().reduce(0, Integer::sum);
Assert.assertTrue(sum < 0);
}
@Test(expectedExceptions = ArithmeticException.class)
public void givenNumber_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
}

View File

@ -1,11 +1,11 @@
package baeldung.com;
import org.testng.annotations.Test;
public class TimeOutIntegrationTest {
@Test(timeOut = 1000, enabled = false)
public void givenExecution_takeMoreTime_thenFail() {
while (true) ;
}
}
package com.baeldung;
import org.testng.annotations.Test;
public class TimeOutIntegrationTest {
@Test(timeOut = 1000, enabled = false)
public void givenExecution_takeMoreTime_thenFail() {
while (true) ;
}
}

View File

@ -14,14 +14,12 @@ public class CustomisedListener implements ITestListener {
LOGGER.info("PASSED TEST CASES");
context.getPassedTests()
.getAllResults()
.stream()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("FAILED TEST CASES");
context.getFailedTests()
.getAllResults()
.stream()
.forEach(result -> {
LOGGER.info(result.getName());
});

View File

@ -7,7 +7,7 @@
<parameter name="value" value="1"/>
<parameter name="isEven" value="false"/>
<classes>
<class name="baeldung.com.ParametrizedUnitTest"/>
<class name="com.baeldung.ParametrizedLongRunningUnitTest"/>
</classes>
</test>
</suite>

View File

@ -7,7 +7,7 @@
</run>
</groups>
<classes>
<class name="baeldung.com.SummationServiceIntegrationTest"/>
<class name="com.baeldung.SummationServiceIntegrationTest"/>
</classes>
</test>
</suite>

View File

@ -7,7 +7,7 @@
</run>
</groups>
<classes>
<class name="baeldung.com.SummationServiceIntegrationTest">
<class name="com.baeldung.SummationServiceIntegrationTest">
<methods>
<include name="givenNumbers_sumEquals_thenCorrect"/>
</methods>

View File

@ -5,9 +5,9 @@
</listeners>
<test name="test suite">
<classes>
<class name="baeldung.com.RegistrationUnitTest" />
<class name="baeldung.com.SignInUnitTest" />
<class name="baeldung.com.SimpleUnitTest" />
<class name="com.baeldung.RegistrationLongRunningUnitTest" />
<class name="com.baeldung.SignInLongRunningUnitTest" />
<class name="com.baeldung.SimpleLongRunningUnitTest" />
</classes>
</test>
</suite>