Unit test for method retrieving data from CacheManger using for loop

caffeine cache unit test
spring boot cacheable unit test
integration testing caching
spring boot test cache already exists

I have a method that with retrieve persons from a next webapi and store in cache and i want to fetch the same cached data from the cache Manager. I am having difficulties to write unit test for this method. Any help is highly appreciated

import javax.cache.Cache;
import javax.cache.CacheManager;

@Autowired
@Qualifier(value = "cacheManager")
private CacheManager cacheManager;

*public List<Person> fallbackPersons() {
      List<Person> data = new ArrayList<>();
    for (Cache.Entry<Object, Object> entry :cacheManager.getCache("person"){ 
        data = (List<Person>) entry.getValue();
        }
    return data;
}*

You can mock the CacheManager, stub it and verify result as below:

    @RunWith(MockitoJUnitRunner.class)
    public class PersonsServiceTest {

        @Mock
        private CacheManager cacheManager;

        @InjectMocks
        PersonsService service = new PersonsService();

        @Before
        public void setup() {
             MockitoAnnotations.initMocks(this);
        }

        @Test
        public void fallbackPersonsWithNonEmptyCache() {
            List<Person> persons = Collections.singletonList(new Person());  // create person object as your Person class definition
            // mock cache entry
            Cache.Entry <Object, Object> entry = Mockito.mock(Cache.Entry.class);

            // do stubbing
            Mockito.when(entry.getValue()).thenReturn(persons);
            Mockito.when(cacheManager.getCache(Matchers.anyString()))
                    .thenReturn(entry);

            // execute
            List<Person> persons = service.fallbackPersons();

            // verify
            Assert.assertNotNull(persons);
            Assert.assertFalse(persons.isEmpty());
        }
    }

Unit test for method retrieving data from CacheManger using for loop, I have a method that with retrieve persons from a next webapi and store in cache and i want to fetch the same cached data from the cache Manager. I am having  You can use the Microsoft unit test framework for managed code to set up a unit test method to retrieve values from a data source. The method is run successively for each row in the data source, which makes it easy to test a variety of input by using a single method.

The correct solution to my problem.

@ActiveProfiles("test")
@RunWith(MockitoJUnitRunner.class)
@Slf4j
public class CacheTest {

    @Spy
    @InjectMocks
    PersonService personService;

    @Mock
    private CacheManager cacheManager;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void fallbackMCCsWithNonEmptyCache() {

        List<Person> persons = Collections.singletonList(new Person());

        Iterator<Cache.Entry <Object, Object>> cacheIterator = 
        Mockito.mock(Iterator.class);
        Cache <Object, Object> cache = Mockito.mock(Cache.class);
        Cache.Entry <Object, Object> entry = Mockito.mock(Cache.Entry.class);
        Mockito.when(cacheManager.getCache(Mockito.anyString()))
        .thenReturn(cache);
        Mockito.when(cache.iterator()).thenReturn(cacheIterator);
        List<Person> personList = personService.fallbackPersons();
        Assert.assertNotNull(personList);
        Assert.assertTrue(personList.isEmpty());
    }
}

Optimizing Spring Integration Tests, The more we simplify our code by using Spring modules (data, security, social…) Thereafter, impacting our feedback loop and getting on the way of best development practices. tests; Refactoring into unit tests – the best way to get a solid and snappy build lateinit var cacheManager: CacheManager. First, create a new class extending haxe.unit.TestCase and add own test methods. Every test method name must start with "test". class MyTestCase extends haxe.unit. TestCase {public function testBasic {assertEquals ("A", "A");}} Running unit tests. To run the test, an instance of haxe.unit.TestRunner has to be created. Add the TestCase using the

1. Unit testing

If your intention is to unit test the public method fallbackPersons by mocking CacheManager, I strongly recommend to change the style you inject the cacheManager bean, by using constructor injection:

import javax.cache.Cache;
import javax.cache.CacheManager;

@Service    
public class PersonsService {
    private final CacheManager cacheManager;

    @Autowired
    public PersonsService(@Qualifier(value = "cacheManager") CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    public List<Person> fallbackPersons() {
        List<Person> data = new ArrayList<>();
        for (Cache.Entry<Object, Object> entry : cacheManager.getCache("person")) { 
            data = (List<Person>) entry.getValue();
        }

        return data;
    }
}

This class is now very easy to unit test by injecting the mock of CacheManager and program its behavior, you will not need to bootstrap the Spring context (to apply @Autowired), or use Powermock library to access private properties.

Example of unit test:

public class PersonsServiceTest {
    @Test
    public void fallbackPersonsWithEmptyCache() {
        CacheManager cacheManager = Mockito.mock(CacheManager.class);
        Mockito.when(cacheManager.getCache(Matchers.anyString()))
            .thenReturn(Collections.emptyList());

        PersonsService service = new PersonsService(cacheManager);
        List<Person> persons = service.fallbackPersons();
        Assert.assertNotNull(persons);
        Assert.assertTrue(persons.isEmpty());
    }
}

2. Integration testing

If you actually would like to test your service with real cache manager implementation from Spring, then you should look into example on how to use AbstractJUnit4SpringContextTests or AbstractTestNGSpringContextTests classes provided by Spring Framework. They will allow you to initialize true Spring context and inject real CacheManager implementations like EhCahce, etc.

Spring JdbcTemplate Unit Testing, a powerful tool for developers to focus on writing SQL queries and extracting results. Firstly, let's start with a data access object (DAO) class that uses JdbcTemplate: There are two ways to unit test methods that use JdbcTemplate. object so that we don't need to run the SQL statement on a database:. A JUnit test is a method contained in a class which is only used for testing. This is called a Test class . To define that a certain method is a test method, annotate it with the @Test annotation. This method executes the code under test.

Writing unit tests, No way to get that right without unit testing! You're throwing a regex at some string? The unit test data provider should already exist before you start with guides are: No loops, no additional class inheritance, no additional helper methods if not new CacheManager(); $subject->flushCachesInGroup('​nonExistingGroup'); }. Let’s refactor the previous test method by replacing test data creation with a call to a utility class method. First, you need to create the test utility class. The TestDataFactory class is a special type of class—it is a public class that is annotated with isTest and can be accessed only from a running test.

Junit json assert, Learn how to use a JSONassert library, focused on understanding JSON data Run on Feb 12, 2013 · Easy JUnit testing with Elastic Search It was quite assertEquals(Object expected, Object actual) This method asserts that two objects are equal. Programming With Assertions An assertion is a statement in the Java TM  A unit test that’s supposed to fail will (incorrectly) succeed when it’s testing the wrong thing. This is why test-driven development (TDD) makes heavy use of the red/green/refactor loop: the “red” part of the loop ensures the unit test will fail when the code is incorrect.

Build local unit tests, Overview · Develop a TV input service · Work with channel data · Manage TV user You can evaluate your app's logic using local unit tests when you need to run tests A test method begins with the @Test annotation and contains the code to exercise Given a Context object retrieved from Robolectric. It's great for storing some simple configuration information or other small sets of data. Whenever you write a class that is designed to be serialized using XML serialization (or any serialization for that matter), you should make sure you have some unit tests to ensure the data is persisted and retrieved as expected.

Comments
  • Thank you for you response. below line should return the cache instead of emptyList Mockito.when(cacheManager.getCache(Matchers.anyString())) .thenReturn(Collections.emptyList()); Also I am still getting the NullPointerExcetpion from from line for (Cache.Entry<Object, Object> entry :cacheManager.getCache("person"){
  • @suraz i have updated the example, please have a look!
  • I checked with your updated example @yogen but i am getting the same error of NullPointerException.
  • @suraz assert or debug before execute if cacheManager has been mocked.. also make sure you have @RunWith(MockitoRunner.class) because that is telling to enable mock annotations.. if still getting same error, tell me the difference on code i gave you and you have.
  • thank you for you quick response.it help me to figure out the solution. Actually, i had to mock every single step to pass the test. Below i have posted the solution hopefully it might somebody.
  • Thank you for you response. below line should return the cache instead of emptyList Mockito.when(cacheManager.getCache(Matchers.anyString())) .thenReturn(Collections.emptyList()); Also I am still getting the NullPointerExcetpion from from line for (Cache.Entry<Object, Object> entry :cacheManager.getCache("person"){