package com.ford.car;
import org.junit.jupiter.api.AfterAll;
import org.mockito.MockSettings;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.ScopedMock;
import java.util.concurrent.ConcurrentLinkedQueue;
public abstract class BaseUnitTest {
private AutoCloseable closeable;
private final static ConcurrentLinkedQueue<ScopedMock> scopedMocks = new ConcurrentLinkedQueue<>();
@AfterAll
public static void afterAll() {
closeScopedMocks();
}
/**
* paired with #mockStatic() and #mockConstruction()
*/
protected static void closeScopedMocks() {
for (ScopedMock mockedStatic : scopedMocks) {
if (null != mockedStatic)
try {
mockedStatic.close();
} catch (Exception e) {
e.printStackTrace();
}
}
scopedMocks.clear();
}
/**
* must call #closeMocks() after test complete
*/
protected void openMocks() {
closeable = MockitoAnnotations.openMocks(this);
}
/**
* paired with #openMocks()
*/
protected void closeMocks() {
try {
if (null != closeable)
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* must call #closeScopedMocks() after test complete
*/
protected static <T> void mockStatic(Class<T> classToMock) {
scopedMocks.add(Mockito.mockStatic(classToMock));
}
protected static <T> void mockStatic(Class<T> classToMock, MockSettings mockSettings) {
scopedMocks.add(Mockito.mockStatic(classToMock, mockSettings));
}
/**
* must call #closeScopedMocks() after test complete
*/
protected static <T> void mockConstruction(Class<T> classToConstruct) {
scopedMocks.add(Mockito.mockConstruction(classToConstruct));
}
protected static <T> void mockConstruction(Class<T> classToConstruct, MockSettings mockSettings) {
scopedMocks.add(Mockito.mockConstruction(classToConstruct, mockSettings));
}
}