Lifecycle of #After method - junit

I am trying to gather some information after every test method, and would like to analyze the gathered information after the test class completes. So, I have a private member variable, a list which I would like to add to after every test method completes. However, at the end of the day, the member variable always remains null.
Note: My test class implements Callable interface.
Here is my code snippet:
{
private List<String statisticsCollector;
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
this.statisticsCollector = new ArrayList<String>();
}
#Override
public List<String> call() {
log.info("Starting a new thread of execution with Thread# -" + Thread.currentThread().getName());
core.run(this.getClass());
return getStatisticsCollector(); // this is always returing a list of size 0
}
#After
public void gatherSomeStatistics() {
x = x+1;
String sb = new String("Currently executing ----" + x);
log.info("Currently executing ----" + x);
addToStatisticsCollector(sb);
}
#Test
#FileParameters(value = "classpath:folder/testB.json", mapper = MyMapper.class)
public void testB(MarsTestDefinition testDefinition) {
runTests(testDefinition);
}
#Test
#FileParameters(value = "classpath:folder/testA.json", mapper = MyMapper.class)
public void testA(MyDefinition testDefinition) {
runTests(testDefinition);
}
public List<String> getStatisticsCollector() {
return this.statisticsCollector;
}
public void addToStatisticsCollector(String sb) {
this.statisticsCollector.add(sb);
}
}
So, why is it always getting reset, even though I am appending to the list in my #After annotated method?
Any help will be highly appreciated. Thanks

Try with following code, is it working ?
private static List<String> statisticsCollector = new ArrayList<String>();
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
}
public List<String> getStatisticsCollector() {
return statisticsCollector;
}

Related

How to run different tests on a single Document variable which was fetched with Jsoup.connect(string)

I have multiple test cases and I want to use a single Document variable with all of them.
There are more test units which will use this Document.
I had an idea to download the html code, in order to avoid connecting to the site multiple times and taking up server resources, but still I think that it wouldn't be an optional approach to testing.
public class ScrapperTest {
public ScrapperTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
/**
* Test of scrapeManufacturer method, of class Scrapper.
*/
#Test
public void testScrapeManufacturer() {
System.out.println("scrapeManufacturer");
Document html = null;
Scrapper instance = new ScrapperImpl();
String expResult = "";
String result = instance.scrapeManufacturer(html);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
}
/**
* Test of scrapeMinPrice method, of class Scrapper.
*/
#Test
public void testScrapeMinPrice() {
System.out.println("scrapeMinPrice");
Document html = null;
Scrapper instance = new ScrapperImpl();
String expResult = "";
String result = instance.scrapeMinPrice(html);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}

ArgumentCaptor is null

I'm trying to write a unit test for the code below where I instantiate a bean and pass it on to other private methods of the class for further processing before doing what the main method does:
public OverviewTabViewBean build(Listing listing) {
VehicleDetailListingBean vehicleDetailListingBean = new VehicleDetailListingBean();
applyVehicleDetailListingRules(listing, vehicleDetailListingBean);
OverviewTabViewBean overviewTabViewBean = new OverviewTabViewBean();
if (vehicleDetailListingBean != null) {
overviewTabViewBean.setMake(vehicleDetailListingBean.getMake());
overviewTabViewBean.setModel(vehicleDetailListingBean.getModel());
overviewTabViewBean.setAtCarId(vehicleDetailListingBean.getAtCarId());
..
}
return overviewTabViewBean;
private void applyCommonListingRules(Listing listing, VehicleDetailListingBean vehicleDetailListingBean) {
rulesEngineService.applyRules(listing, vehicleDetailListingBean, vehicleDetailRules.getCommonListingRules());
}
Test looks something like this:
#Captor
ArgumentCaptor<OverviewTabViewBean> overviewTabViewBean;
#Captor
ArgumentCaptor<VehicleDetailListingBean> vehicleDetailListingBean;
#Mock
private RulesEngineService rulesEngineService;
#Mock
private VehicleDetailRules vehicleDetailRules;
#Mock
private VehicleReferenceService vehicleReferenceService;
#BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
/**
* build
*/
#Test
public void build() {
Listing listing = new Listing();
listing.setListingId(111L);
listing.setListingType(ListingType.NEW);
List<Rule<Listing, ListingBean>> rules1 = new ArrayList<Rule<Listing, ListingBean>>();
List<Rule<Listing, ListingBean>> rules2 = new ArrayList<Rule<Listing, ListingBean>>();
doReturn(rules1).when(vehicleDetailRules).getCommonListingRules();
doReturn(rules2).when(vehicleDetailRules).getDetailListingRules();
overviewTabViewBeanBuilder.build(listing);
verify(rulesEngineService, times(2)).applyRules(anyObject(), vehicleDetailListingBean.capture(), anyList());
.....
}
vehicleDetailListingBean is returning as null a not stepping into the if block. What am I doing wrong here?

Mockito and JUnit issue

I have this test:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = Mockito.mock(WorkChronometer.class);
Mockito.when(workChronometer.getAccumulatedMinutes()).thenReturn(120);
Assert.assertEquals(expectedHours, workChronometer.getAccumulatedHours());
}
and the implementation of WorkChronometer:
public class WorkChronometer {
private DateTime startingInstant;
private DateTime stoppingInstant;
private Boolean counting;
//More methods
public Integer getAccumulatedMinutes() {
if (counting)
throw new RuntimeException("Call stopCount first!");
if (startingInstant == null || stoppingInstant == null)
return 0;
return Minutes.minutesBetween(startingInstant, stoppingInstant).getMinutes();
}
public Float getAccumulatedHours() {
Integer accumulatedMinutes = getAccumulatedMinutes();
return accumulatedMinutes / 60f;
}
}
When I execute the test, it fails:
junit.framework.AssertionFailedError: expected:<2.0> but was:<0.0>
But I don't know why. It seems the mock is not returning what I want.
What am I doing wrong?
Thanks.
You're mocking the class under test. Doing that relaces all the methods by methods doing nothing, and returning default values.
If you want to do that, you'll need a spy, or a partial mock.
With a spy:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = new WorkChronometer();
WorkChronometer spy = Mockito.spy(workChronometer);
doReturn(120).when(spy).getAccumulatedMinutes();
Assert.assertEquals(expectedHours, spy.getAccumulatedHours());
}
With a partial mock:
#Test
public void shouldReturn2Hours() {
Float expectedHours = 2f;
WorkChronometer workChronometer = Mockito.mock(WorkChronometer.class);
Mockito.when(workChronometer.getAccumulatedHours()).thenCallRealMethod();
Mockito.when(workChronometer.getAccumulatedMinutes()).thenReturn(120);
Assert.assertEquals(expectedHours, workChronometer.getAccumulatedHours());
}

Android. Robolectric. Testing AccountManager results

In my application I use method with account manager for getting owner emails. How I can test this method with Robolectric? Should I use for this purpose mocking? If I'm right, can I use Mockito? Is any tutorials how I can do it?
First I implemented the unit test
// Imports are skipped
/**
* Created by fminatchy on 25/02/14.
*/
#RunWith(RobolectricTestRunner.class)
#Config(manifest = "/src/main/AndroidManifest.xml")
public class TestAuthorization {
AccountManager accountManager;
Account account0;
Account account1;
Account account2;
#Before
public void init() {
creationComptes();
accountManager = AccountManager.get(Robolectric.application);
shadowOf(accountManager).addAccount(account0);
shadowOf(accountManager).addAccount(account1);
shadowOf(accountManager).addAccount(account2);
}
#Test
public void test_comptes() {
final AlbumsActivity activity = Robolectric.buildActivity(AlbumsActivity.class).create().get();
final String[] accountsName = activity.getGoogleAccounts();
assertThat(Arrays.asList(accountsName)).containsExactly("compte n°1", "compte n°3");
}
private void creationComptes() {
account0 = new Account("compte n°1", GoogleAccountManager.ACCOUNT_TYPE);
account1 = new Account("compte n°2", "pas google");
account2 = new Account("compte n°3", GoogleAccountManager.ACCOUNT_TYPE);
}
and their is the code located in the activity :
public String[] getGoogleAccounts() {
final AccountManager accountManager = AccountManager.get(this.getApplicationContext());
Account[] accounts = accountManager.getAccountsByType(GoogleAccountManager.ACCOUNT_TYPE);
String[] names = new String[accounts.length];
for (int i = 0; i < names.length; i++) {
names[i] = accounts[i].name;
}
return names;
}

Ehcache hangs in test

I am in the process of rewriting a bottle neck in the code of the project I am on, and in doing so I am creating a top level item that contains a self populating Ehcache. I am attempting to write a test to make sure that the basic call chain is established, but when the test executes it hands when retrieving the item from the cache.
Here are the Setup and the test, for reference mocking is being done with Mockito:
#Before
public void SetUp()
{
testCache = new Cache(getTestCacheConfiguration());
recordingFactory = new EntryCreationRecordingCache();
service = new Service<Request, Response>(testCache, recordingFactory);
}
#Test
public void retrievesResultsFromSuppliedCache()
{
ResultType resultType = mock(ResultType.class);
Response expectedResponse = mock(Response.class);
addToExpectedResults(resultType, expectedResponse);
Request request = mock(Request.class);
when(request.getResultType()).thenReturn(resultType);
assertThat(service.getResponse(request), sameInstance(expectedResponse));
assertTrue(recordingFactory.requestList.contains(request));
}
private void addToExpectedResults(ResultType resultType,
Response response) {
recordingFactory.responseMap.put(resultType, response);
}
private CacheConfiguration getTestCacheConfiguration() {
CacheConfiguration cacheConfiguration = new CacheConfiguration("TEST_CACHE", 10);
cacheConfiguration.setLoggingEnabled(false);
return cacheConfiguration;
}
private class EntryCreationRecordingCache extends ResponseFactory{
public final Map<ResultType, Response> responseMap = new ConcurrentHashMap<ResultType, Response>();
public final List<Request> requestList = new ArrayList<Request>();
#Override
protected Map<ResultType, Response> generateResponse(Request request) {
requestList.add(request);
return responseMap;
}
}
Here is the ServiceClass
public class Service<K extends Request, V extends Response> {
private Ehcache cache;
public Service(Ehcache cache, ResponseFactory factory) {
this.cache = new SelfPopulatingCache(cache, factory);
}
#SuppressWarnings("unchecked")
public V getResponse(K request)
{
ResultType resultType = request.getResultType();
Element cacheEntry = cache.get(request);
V response = null;
if(cacheEntry != null){
Map<ResultType, Response> resultTypeMap = (Map<ResultType, Response>) cacheEntry.getValue();
try{
response = (V) resultTypeMap.get(resultType);
}catch(NullPointerException e){
throw new RuntimeException("Result type not found for Result Type: " + resultType);
}catch(ClassCastException e){
throw new RuntimeException("Incorrect Response Type for Result Type: " + resultType);
}
}
return response;
}
}
And here is the ResponseFactory:
public abstract class ResponseFactory implements CacheEntryFactory{
#Override
public final Object createEntry(Object request) throws Exception {
return generateResponse((Request)request);
}
protected abstract Map<ResultType,Response> generateResponse(Request request);
}
After wrestling with it for a while, I discovered that the cache wasn't being initialized. Creating a CacheManager and adding the cache to it resolved the problem.
I also had a problem with EHCache hanging, although only in a hello-world example. Adding this to the end fixed it (the application ends normally).
CacheManager.getInstance().removeAllCaches();
https://stackoverflow.com/a/20731502/2736496