<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
</plugin>
package com.example.demo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MainTest {
@Test
void testSum() {
assertEquals(2, 1 + 1);
}
}
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.076 s -- in org.example.MainTest
class MyTest {
@Test
void testRecordCount() {
List<Course> all = repository.findAll();
assertTrue(all.size() < 10);
}
}
class MyTest {
@Test
void testRecordCountAssertJ() {
List<Course> all = repository.findAll();
assertThat(all).hasSizeLessThan(10);
}
}
class MyTest {
@Test
void testAndreiDidNotWriteAnyCourse() {
List<Course> all = repository.findAll();
assertThat(all).extracting("author").doesNotContain("Андрей");
}
}
class MyTest {
@Test
void testRecordCount() {
List<Course> all = repository.findAll();
assertThat(all.size(), is(lessThan(10)));
}
@Test
void testAndreiDidNotWriteAnyCourse() {
List<Course> all = repository.findAll();
assertThat(all, is(not(contains(hasProperty("author", is("Андрей"))))));
}
}
public interface UserService {
void updateUser(Long id, String firstName, String lastName);
}
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public void updateUser(Long id, String firstName, String lastName) {
User user = userRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("No User with ID=" + id));
user.update(firstName, lastName);
}
}
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final AuditService auditService;
@Override
public void updateUser(Long id, String firstName, String lastName) {
try {
User user = userRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("No User with ID=" + id));
user.update(firstName, lastName);
} catch (RuntimeException e) {
auditService.auditFailedUserCreation(id, e);
throw e;
}
}
}
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final AuditService auditService;
private final EmailService emailService;
@Override
public void updateUser(Long id, String firstName, String lastName) {
try {
User user = userRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("No User with ID=" + id));
user.update(firstName, lastName);
emailService.notifyAdmin(new UserUpdatedEvent(id));
}
catch (RuntimeException e) {
auditService.auditFailedUserCreation(id, e);
throw e;
}
}
}
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public void updateUser(Long id, String firstName, String lastName) {
User user = userRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("No User with ID=" + id));
user.update(firstName, lastName);
}
}
public class AuditUserService implements UserService {
private final UserService origin;
private final AuditService auditService;
@Override
public void updateUser(Long id, String firstName, String lastName) {
try {
origin.updateUser(id, firstName, lastName);
}
catch (RuntimeException e) {
auditService.auditFailedUserCreation(id, e);
throw e;
}
}
}
public class EmailUserService implements UserService {
private final UserService origin;
private final EmailService emailService;
@Override
public void updateUser(Long id, String firstName, String lastName) {
origin.updateUser(id, firstName, lastName);
emailService.notifyAdmin(new UserUpdatedEvent(id));
}
}
public interface Card {
BigDecimal getCreditLimit();
BigDecimal getAnnualCharge();
}
public interface StandardCard implements Card {
...
}
public interface GoldCard implements Card {
...
}
public interface PlatinumCard implements Card {
...
}
public class CardFactory {
public static Card newCard(ClientAttributes attributes) {
// some calculations
// ...
// return new Card instance
}
}
public interface CardFactory {
Card newCard(ClientAttributes attributes);
}
public class StandardCardFactory implements CardFactory {
public Card newCard(ClientAttributes attributes) {
...
return new StandardCard();
}
}
public class GoldCardFactory implements CardFactory {
public Card newCard(ClientAttributes attributes) {
...
return new GoldCard();
}
}
public class PlatinumCardFactory implements CardFactory {
public Card newCard(ClientAttributes attributes) {
...
return new PlatinumCard();
}
}
public class CallCenter {
public void answerIncomingCall(Call call) {
if (!firstOperator.isOnCall()) {
firstOperator.answer(call);
} else if (!secondOperator.isOnCall()) {
secondOperator.answer(call);
} else if (!thirdOperator.isOnCall()) {
thirdOperator.answer(call);
} else if (!fourthOperator.isOnCall()) {
fourthOperator.answer(call);
// и так далее
}
}
}
public class CallCenter {
private Operator firstOperator;
public CallCenter() {
Operator firstOperator = new HumanOperatorImpl("Вася");
Operator secondOperator = new HumanOperatorImpl("Маша");
Operator thirdOperator = new HumanOperatorImpl("Петя");
Operator fourthOperator = new HumanOperatorImpl("Оля");
Operator robotOperator = new RobotOperatorImpl();
firstOperator.setNextOperator(secondOperator);
secondOperator.setNextOperator(thirdOperator);
thirdOperator.setNextOperator(fourthOperator);
fourthOperator.setNextOperator(robotOperator);
}
public void answerIncomingCall(Call call) {
firstOperator.answer(call);
}
}
public interface Operator {
void answer(Call call);
Boolean isOnCall();
void setNextOperator(Operator next);
}
public class HumanOperatorImpl implements Operator {
private String name;
private Boolean onCall; // Сейчас оператор говорит по телефону?
private Operator next; // Следующий оператор в цепочке
public HumanOperatorImpl(String name) {
this.name = name;
}
@Override
public boolean isOnCall() {
return onCall;
}
@Override
public void setNextOperator(Operator next) {
this.next = next;
}
@Override
public void answer(Call call) {
if (this.onCall) {
// Текущий оператор говорит по телефону - переводим звонок на следующего
next.answer(call);
}
System.out.println("Здравствуйте, оператор " + this.name + " слушает"); // Ответ на звонок
}
}
public class RobotOperatorImpl implements Operator {
@Override
public void answer(Call call) {
System.out.println("Нет свободных операторов, перезвоните позже.");
}
@Override
public Boolean isOnCall() {
return false;
}
@Override
public void setNextOperator(Operator next) {
throw new UnsupportedOperationException("Робот - это последний оператор");
}
}
interface Car {
void drive();
}
class CarImpl {
void drive() {...}
}
class ABSCarImpl {
void drive() {...}
void slowdown() {...}
}
class NoABSCarImpl {
void drive() {...}
void slowdown() {...}
}
class HydraulicSteeringABSCarImpl {
void drive() {...}
void slowdown() {...}
void steer() {...}
}
class ElectricSteeringABSCarImpl {
void drive() {...}
void slowdown() {...}
void steer() {...}
}
class MechanicalSteeringABSCarImpl {
void drive() {...}
void slowdown() {...}
void steer() {...}
}
class HydraulicSteeringNoABSCarImpl {
void drive() {...}
void slowdown() {...}
void steer() {...}
}
class ElectricSteeringNoABSCarImpl {
void drive() {...}
void slowdown() {...}
void steer() {...}
}
class MechanicalSteeringNoABSCarImpl {
void drive() {...}
void slowdown() {...}
void steer() {...}
}
interface SlowdownStrategy {
void slowdown();
}
interface SteerStrategy {
void steer();
}
class HydraulicSteeringStrategy implements SteeringStrategy {
void steer() {
// Поворот с гидроусилителем
}
}
class ElectricSteeringStrategy implements SteeringStrategy {
void steer() {
// Поворот с электроусилителем
}
}
class MechanicalSteeringStrategy implements SteeringStrategy {
void steer() {
// Поворот без усилителя
}
}
class ABSSlowdownStrategy implements SlowdownStrategy {
void slowdown() {
// Торможение с АБС
}
}
class NoABSSlowdownStrategy implements SlowdownStrategy {
void slowdown() {
// Торможение без АБС
}
}
public class HotelService {
public Room findRoom(RoomId roomId) {
// поиск комнаты по ID
}
public Order bookRoom(RoomId roomId) {
// забронировать комнату
}
public List<Order> getOrders() {
// получить список текущих заказов
}
public void notifyOrdering(OrderId orderId) {
// отправить уведомление об оформлении заказа
}
}
public class RoomService {
public Room findRoom(RoomId roomId) {
// поиск комнаты по ID
}
}
public class OrderService {
public Order bookRoom(RoomId roomId) {
// забронировать комнату
}
public List<Order> getOrders() {
// получить список текущих заказов
}
}
public class NotifyService {
public void notifyOrdering(OrderId orderId) {
// отправить уведомление об оформлении заказа
}
}
public class NotifyService {
public void notifyOrdering(OrderId orderId, NotificationType type) {
if (type.equals(NotificationType.SMS)) {
// логика обработки SMS
} else if (type.equals(NotificationType.EMAIL)) {
// логика обработки EMAIL
}
}
}
public interface NotificationAction {
NotificationType type();
void notify(OrderId orderId);
}
public class SmsNotificationAction {
@Override
public NotificationType type() {
return NotificationType.SMS;
}
public void notify(OrderId orderId) {
// логика уведомлений по sms
}
}
public class EmailNotificationAction {
@Override
public NotificationType type() {
return NotificationType.EMAIL;
}
public void notify(OrderId orderId) {
// логика уведомлений по email
}
}
public class NotificationService {
private final List<NotificationAction> actions;
public NotificationService(List<NotificationAction> actions) {
this.actions = actions;
}
public void notifyOrdering(OrderId orderId, NotificationType type) {
boolean foundAction = false;
for (NotificationAction action : actions) {
if (action.type().equals(type)) {
foundAction = true;
action.notify(orderId);
break; // выходим из цикла, если нашли нужный action
}
}
if (!foundAction) {
// если не нашли подходящего action, кидаем исключение
throw new AbsendNotificationException("Couldn't find NotificationAction for type=" + type);
}
}
}
public class Main {
public static void main(String[] args) {
NotificationService service = new NotificationService(
List.of(
new SmsNotificationAction(),
new EmailNotificationAction()
)
);
// дальнейшие действия
}
}
public interface NotificationAction {
NotificationType type();
/**
* Notifies user of order about its submission.
*
* @param orderId id of order
* @throws NotificationActionException if couldn't send notification due to error
*/
void notify(OrderId orderId);
}
public class NotificationService {
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
private final List<NotificationAction> actions;
public NotificationService(List<NotificationAction> actions) {
this.actions = actions;
}
public void notifyOrdering(OrderId orderId, NotificationType type) {
boolean foundAction = false;
for (NotificationAction action : actions) {
if (action.type().equals(type)) {
foundAction = true;
try {
action.notify(orderId);
break; // выходим из цикла, если нашли нужный action
} catch (NotificationActionException e) {
LOG.error("Couldn't execute action '{}'. Trying next one", action, e);
}
}
}
if (!foundAction) {
// если не нашли подходящего action, кидаем исключение
throw new AbsendNotificationException("Couldn't find NotificationAction for type=" + type);
}
}
}
public class NotificationService {
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
private final List<NotificationAction> actions;
public NotificationService(List<NotificationAction> actions) {
this.actions = actions;
}
public void notifyOrdering(OrderId orderId, NotificationType type) {
boolean foundAction = false;
for (NotificationAction action : actions) {
if (action.type().equals(type)) {
foundAction = true;
try {
action.notify(orderId);
break; // выходим из цикла, если нашли нужный action
} catch (NotificationActionException e) {
LOG.error("Couldn't execute action '{}'. Trying next one", action, e);
}
}
}
if (!foundAction) {
// если не нашли подходящего action, кидаем исключение
throw new AbsendNotificationException("Couldn't find NotificationAction for type=" + type);
}
}
}
public class NotificationService {
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
private final List<NotificationAction> actions = List.of(
new SmsNotificationAction(),
new EmailNotificationAction()
);
public void notifyOrdering(OrderId orderId, NotificationType type) {
boolean foundAction = false;
for (NotificationAction action : actions) {
if (action.type().equals(type)) {
foundAction = true;
try {
action.notify(orderId);
break; // выходим из цикла, если нашли нужный action
} catch (NotificationActionException e) {
LOG.error("Couldn't execute action '{}'. Trying next one", action, e);
}
}
}
if (!foundAction) {
// если не нашли подходящего action, кидаем исключение
throw new AbsendNotificationException("Couldn't find NotificationAction for type=" + type);
}
}
}
class NotificationServiceTest {
@Test
void shouldThrowExceptionIfActionsListIsEmpty() {
NotificationService service = new NotificationService();
assertThrows(
AbsendNotificationException.class,
() -> service.notifyOrdering(new OrderId(1), NotificationType.SMS)
);
}
}
public class NotificationService {
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
private final List<NotificationAction> actions;
public NotificationService(List<NotificationAction> actions) {
this.actions = actions;
}
public void notifyOrdering(OrderId orderId, NotificationType type) {
boolean foundAction = false;
for (NotificationAction action : actions) {
if (action.type().equals(type)) {
foundAction = true;
try {
action.notify(orderId);
break; // выходим из цикла, если нашли нужный action
} catch (NotificationActionException e) {
LOG.error("Couldn't execute action '{}'. Trying next one", action, e);
}
}
}
if (!foundAction) {
// если не нашли подходящего action, кидаем исключение
throw new AbsendNotificationException("Couldn't find NotificationAction for type=" + type);
}
}
}
class NotificationServiceTest {
@Test
void shouldThrowExceptionIfActionsListIsEmpty() {
NotificationService service = new NotificationService(Collections.emptyList());
assertThrows(
AbsendNotificationException.class,
() -> service.notifyOrdering(new OrderId(1), NotificationType.SMS)
);
}
}
class NotificationServiceTest {
@Test
void shouldSucceedNotifying() {
final var actionResult = new AtomicBoolean(false);
final var notificationAction = new NotificationAction() {
@Override
public NotificationType type() {
return NotificationType.EMAIL;
}
@Override
public void notify(OrderId orderId) {
actionResult.set(true);
}
};
NotificationService service = new NotificationService(List.of(notificationAction));
assertDoesNotThrow(
() -> service.notifyOrdering(new OrderId(1), NotificationType.EMAIL)
);
assertTrue(actionResult.get());
}
}
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
class NotificationServiceTest {
@Test
void shouldSucceedNotifyingWithMocks() {
final var notificationAction = Mockito.mock(NotificationAction.class);
Mockito.when(notificationAction.type())
.thenReturn(NotificationType.EMAIL);
NotificationService service = new NotificationService(List.of(notificationAction));
assertDoesNotThrow(
() -> service.notifyOrdering(new OrderId(1), NotificationType.EMAIL)
);
Mockito.verify(notificationAction, Mockito.times(1)).notify(Mockito.any());
}
}
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.50</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>target/jacoco.exec</dataFile>
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
Rule violated for package org.example.action: lines covered ratio is 0.00, but expected minimum is 0.50
Rule violated for package org.example.exception: lines covered ratio is 0.33, but expected minimum is 0.50
class Sorts {
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}