BAEL-5777 - Mocking a singleton with Mockito (#12977)

* BAEL-5777 - Mocking a singleton with Mockito

* BAEL-5777 - Mocking a singleton with Mockito - changing test class name

* BAEL-5777 - Mocking a singleton with Mockito - moving to new module
This commit is contained in:
Abhinav Pandey
2022-11-07 10:17:03 +05:30
committed by GitHub
parent c57284d9c9
commit 113c42199a
9 changed files with 167 additions and 0 deletions
@@ -0,0 +1,40 @@
package com.baeldung.singleton;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class ProductServiceUnitTest {
@Test
void givenValueExistsInCache_whenGetProduct_thenDAOIsNotCalled() {
ProductDAO productDAO = mock(ProductDAO.class);
CacheManager cacheManager = mock(CacheManager.class);
Product product = new Product("product1", "description");
ProductService productService = new ProductService(productDAO, cacheManager);
when(cacheManager.getValue(any(), any())).thenReturn(product);
productService.getProduct("product1");
Mockito.verify(productDAO, times(0)).getProduct(any());
}
@Test
void givenValueExistsInCache_whenGetProduct_thenDAOIsNotCalled_mockingStatic() {
ProductDAO productDAO = mock(ProductDAO.class);
CacheManager cacheManager = mock(CacheManager.class);
Product product = new Product("product1", "description");
try (MockedStatic<CacheManager> cacheManagerMock = mockStatic(CacheManager.class)) {
cacheManagerMock.when(CacheManager::getInstance).thenReturn(cacheManager);
when(cacheManager.getValue(any(), any())).thenReturn(product);
ProductService productService = new ProductService(productDAO);
productService.getProduct("product1");
Mockito.verify(productDAO, times(0)).getProduct(any());
}
}
}