Heroku MemCached Junit Test

Heroku Memcached Cloud Junit Test

package com.example.cache;

import static org.junit.Assert.*;

import java.io.IOException;
import java.math.BigInteger;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.example.model.Customer;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CacheCustomerServiceTest {
	
	private static final String USERNAME="######";
	private static final String PASSWORD="######";
	private static final String HOST="######";
	
	@Configuration
	static class ContextConfiguration{
		
		@Bean
		public MemcachedClient memcachedConfig() {
		try{
			 AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" },
				        new PlainCallbackHandler(USERNAME, PASSWORD));

			MemcachedClient mc = new MemcachedClient(
					new ConnectionFactoryBuilder()
				                  .setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
				                  .setAuthDescriptor(ad).build(),
		    AddrUtil.getAddresses(HOST));
			return mc;
		} catch (IOException ex) {}
			return null;
		}
	}
	
	@Autowired MemcachedClient memcachedConfig;
	
	@Test
	public void testMemCachedSet() {
		memcachedConfig.set("customerKey", 3600, new Customer(new BigInteger("1"), "John", "Doe"));
		Object value = memcachedConfig.get("customerKey");
		System.out.println(value);
	}
}

JUnit Test Spring MVC Web Services

Spring MVC REST Controller

package com.example.controller.api;

import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.model.CustomerActivity;
import com.example.service.CustomerActivityRepository;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiError;
import com.wordnik.swagger.annotations.ApiErrors;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

@Controller
@RequestMapping(value = "/api/v1/customeractivity")
@Api(value = "Customer operations", listingClass = "CustomerController", basePath = "/api/v1/customeractivity", description = "All operations for customers activity")
public class CustomerActivityController {
	
	@Autowired
	@Qualifier("mongoRepository")
	private CustomerActivityRepository customerService;
	
	 @ApiOperation(value = "Find customer by Id", notes = "Get customer by specifying Id", httpMethod = "GET", responseClass = "Customer", multiValueResponse = true)
	 @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), @ApiError(code = 404, reason = "Customer not found") })
	 @RequestMapping(value = "/find/{customerId}", method = RequestMethod.GET, produces = "application/json")
	 public @ResponseBody List<CustomerActivity> findCustomerById(@ApiParam(internalDescription = "java.lang.string", name = "customerId", required = true, value = "string") @PathVariable String customerId) {
		 	List<CustomerActivity> customer = customerService.findCustomerActivityByCustomerId(customerId);
	        return customer;
	 }
}

Spring MVC REST Junit Test

package com.example.controller.api;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Date;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.example.model.CustomerActivity;
import com.example.service.CustomerActivityRepositoryImpl;

import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={CustomerActivityController.class, CustomerActivityRepositoryImpl.class})
public class CustomerActivityControllerTest {
	
	private MockMvc mockMvc;
	
	@Autowired CustomerActivityController customerActivityController;
	
	@Before
	public void setup() {
		this.mockMvc =  MockMvcBuilders.standaloneSetup(customerActivityController).build();
	}
	
	@Test
	public void testCustomerActivityFindCustomerById() throws Exception {
		CustomerActivity customerActivity = new CustomerActivity("123", "SMS Received", new Date(), "SMS", "Workflow", "http://workflow.com");
		CustomerActivityController mock = org.mockito.Mockito.mock(CustomerActivityController.class);
		when(mock.findCustomerById("123")).thenReturn(Arrays.asList(customerActivity));
		
		this.mockMvc.perform(get("/api/v1/customeractivity/find/123"))
		.andExpect(status().isOk())
		.andExpect(content().contentType("application/json"))
		.andExpect(jsonPath("$[0].customerId").value("123"));
		verifyNoMoreInteractions(mock);
	}
}

Salesforce Integration JUnit Testing Using Spring

Spring Configuration to test integration to Salesforce using PartnerConnection, EnterpriseConnection and BulkConnection. Create a properties file called salesforcesync.properties with all the login details

salesforcesync.properties

salesforce.sandbox.username=***your username ***
salesforce.sandbox.password=***your password + security token ***
salesforce.sandbox.url=https://test.salesforce.com/services/Soap/u/29.0
salesforce.sandbox.enterprise.url=https://test.salesforce.com/services/Soap/c/29.0/
salesforce.sandbox.version=29.0

salesforce.production.username=***your username ***
salesforce.production.password=***your password + security token ***
salesforce.production.url=https://login.salesforce.com/services/Soap/u/29.0
salesforce.production.enterprise.url=https://login.salesforce.com/services/Soap/c/29.0
salesforce.production.version=29.0

Salesforce Authentication Spring Configuration

package com.sforce.authentication;

import javax.inject.Inject;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.sforce.async.AsyncApiException;
import com.sforce.async.BulkConnection;

import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

/**
 * @author tmichels
 */
@PropertySource("classpath:/salesforcesync.properties")
@Configuration
public class SalesforceAuthenticationConfigImpl implements SalesforceAuthenticationConfig {

	@Inject
    private Environment environment;
		    
	private PartnerConnection partnerConnection = null;
	private BulkConnection bulkConnection = null;
	
    @Bean(name="loginToProductionSalesforce")
	public PartnerConnection loginToProductionSalesforce() {
    	try {
    		ConnectorConfig config = new ConnectorConfig();
    		config.setUsername(environment.getProperty("salesforce.production.username"));
    		config.setPassword(environment.getProperty("salesforce.production.password"));
			partnerConnection = Connector.newConnection(config);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return partnerConnection;
	}

	@Bean(name="loginToSandboxSalesforce")
	public PartnerConnection loginToSandboxSalesforce() {
		try {
			ConnectorConfig config = new ConnectorConfig();
			config.setUsername(environment.getProperty("salesforce.sandbox.username"));
			config.setPassword(environment.getProperty("salesforce.sandbox.password"));
			config.setAuthEndpoint(environment.getProperty("salesforce.sandbox.url"));
			partnerConnection = Connector.newConnection(config);
		} catch (ConnectionException ce) {
			ce.printStackTrace();
		}
		return partnerConnection;
	}

	
	@Bean(name="bulkLoginToProductionSalesforce")
	public BulkConnection bulkLoginToProductionSalesforce() {
		try {
			
			ConnectorConfig partnerConfig = new ConnectorConfig();
			partnerConfig.setUsername(environment.getProperty("salesforce.production.username"));
			partnerConfig.setPassword(environment.getProperty("salesforce.production.password"));
			partnerConfig.setAuthEndpoint(environment.getProperty("salesforce.production.url"));
			partnerConnection = Connector.newConnection(partnerConfig);
			
		    ConnectorConfig config = new ConnectorConfig();
		    config.setSessionId(partnerConfig.getSessionId());
		    String soapEndpoint = partnerConfig.getServiceEndpoint();
		    String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/"))
		        + "async/" + environment.getProperty("salesforce.sandbox.version");
		    config.setRestEndpoint(restEndpoint);
		    // This should only be false when doing debugging.
		    config.setCompression(true);
		    // Set this to true to see HTTP requests and responses on stdout
		    config.setTraceMessage(false);
		    bulkConnection = new BulkConnection(config);
		} catch (AsyncApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bulkConnection;
	}

	@Bean(name="bulkLoginToSandboxSalesforce")
	public BulkConnection bulkLoginToSandboxSalesforce() {
		try {
			ConnectorConfig partnerConfig = new ConnectorConfig();
			partnerConfig.setUsername(environment.getProperty("salesforce.sandbox.username"));
			partnerConfig.setPassword(environment.getProperty("salesforce.sandbox.password"));
			partnerConfig.setAuthEndpoint(environment.getProperty("salesforce.sandbox.url"));
			partnerConnection = Connector.newConnection(partnerConfig);
			
		    ConnectorConfig bulkconfig = new ConnectorConfig();
		    bulkconfig.setSessionId(partnerConfig.getSessionId());
		    String soapEndpoint = partnerConfig.getServiceEndpoint();
		    String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/"))
		        + "async/" + environment.getProperty("salesforce.sandbox.version");
		     bulkconfig.setRestEndpoint(restEndpoint);
		    // This should only be false when doing debugging.
		    bulkconfig.setCompression(true);
		    // Set this to true to see HTTP requests and responses on stdout
		    bulkconfig.setTraceMessage(false);
		    bulkConnection = new BulkConnection(bulkconfig);
		} catch (AsyncApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bulkConnection;
	}

	@Bean(name="loginToSalesforceSandboxEnterprise")
	public EnterpriseConnection loginToSandboxSalesforceEnterprise() {
		try {
			ConnectorConfig config = new ConnectorConfig();
			config.setUsername(environment.getProperty("salesforce.sandbox.username"));
			config.setPassword(environment.getProperty("salesforce.sandbox.password"));
			config.setAuthEndpoint(environment.getProperty("salesforce.sandbox.enterprise.url"));
			config.setValidateSchema(true);
			config.setCompression(false);
			config.setConnectionTimeout(360000);
			config.setTraceMessage(true);
			config.setPrettyPrintXml(true);
			enterpriseConnection = new EnterpriseConnection(config);
		} catch (ConnectionException ce) {
			ce.printStackTrace();
		}
		return enterpriseConnection;
	}

	@Bean(name="loginToSalesforceProductionEnterprise")
	public EnterpriseConnection loginToProductionSalesforceEnterprise() {
		try {
			ConnectorConfig config = new ConnectorConfig();
			config.setUsername(environment.getProperty("salesforce.production.username"));
			config.setPassword(environment.getProperty("salesforce.production.password"));
			config.setAuthEndpoint(environment.getProperty("salesforce.production.url"));
			config.setValidateSchema(true);
			config.setCompression(false);
			config.setConnectionTimeout(360000);
			config.setTraceMessage(true);
			config.setPrettyPrintXml(true);
		
			enterpriseConnection = new EnterpriseConnection(config);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return enterpriseConnection;
	}
}

Junit test class to assert login was successful

package com.sforce.authentication;

import static org.junit.Assert.*;

import javax.inject.Inject;
import javax.inject.Named;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import com.sforce.async.BulkConnection;
import com.sforce.authentication.SalesforceAuthenticationConfig;
import com.sforce.authentication.SalesforceAuthenticationConfigImpl;

import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;

/**
 * @author tmichels
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={SalesforceAuthenticationConfigImpl.class})
public class SalesforceAuthenticationServiceTest {

	@Inject @Named("loginToProductionSalesforce") PartnerConnection loginToProductionPartner;
	@Inject @Named("loginToSandboxSalesforce") PartnerConnection loginToSandboxPartner;
	@Inject @Named("bulkLoginToProductionSalesforce") BulkConnection loginToProductionBulkConnection;
	@Inject @Named("bulkLoginToSandboxSalesforce") BulkConnection loginToSandboxBulkConnection;
	@Inject @Named("loginToSalesforceSandboxEnterprise") EnterpriseConnection loginToSalesforceEnterpriseConnection;

	@Test
	public void testLoginToProductionSalesforce() {
		assertNotNull(loginToProductionPartner.getConfig().getSessionId());
		try {
			loginToProductionPartner.logout();
		} catch (ConnectionException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testLoginToSandboxSalesforce(){
		assertNotNull(loginToSandboxPartner.getConfig().getSessionId());
		try {
			loginToSandboxPartner.logout();
		} catch (ConnectionException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testBulkLoginToProductionSalesforce(){
		assertNotNull(loginToProductionBulkConnection.getConfig().getSessionId());
	}
	
	@Test
	public void testBulkLoginToSandboxSalesforce(){
		assertNotNull(loginToSandboxBulkConnection.getConfig().getSessionId());
	}
	
	@Test
	public void testLoginToSalesforceEnterprise(){
		assertNotNull(loginToSalesforceEnterpriseConnection.getConfig().getSessionId());
	}
}

Spring Jpa Transaction Manager Junit Testing

Setup Jpa Transaction Manager

package com.sforce.jpa;

import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.sforce.datasource.DataSourceConfigImpl;
import com.sforce.model.DWAccount;

@PropertySource("classpath:/salesforcesync.properties")
@Configuration
@EnableTransactionManagement
@Import( { DataSourceConfigImpl.class })
public class JpaConfigurationImpl {
	
	 @Inject private Environment environment;
	 @Inject @Named("testDwDataSource") private DataSource testDwDataSource;
		
	 @Bean
	 public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
	        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
	        localContainerEntityManagerFactoryBean.setDataSource(testDwDataSource);
	        localContainerEntityManagerFactoryBean.setPackagesToScan(DWAccount.class.getPackage().getName());
	       
	        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
	        jpaVendorAdapter.setGenerateDdl(false);
	        jpaVendorAdapter.setShowSql(true);
	        jpaVendorAdapter.setDatabasePlatform(environment.getProperty("dataSource.dialect"));
	        
	        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
	        return localContainerEntityManagerFactoryBean;
	    }
	 
	 @Bean
	 public PlatformTransactionManager transactionManager() throws Exception {
		 JpaTransactionManager transactionManager = new JpaTransactionManager();
	     transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
	     return transactionManager;
	 }
}

Test Jpa Transaction Manager

package com.sforce.jpa;

import static org.junit.Assert.*;

import javax.inject.Inject;
import javax.inject.Named;


import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@Transactional
@ContextConfiguration(classes={JpaConfigurationImpl.class})
public class JpaTransactionConfigTest {

	@PersistenceContext
        EntityManager entityManager;
	
	@Test
	public void testDWAccountInsert() {
		DWAccount newDWAccount = new DWAccount();
		newDWAccount.setId(new Long(1234));
		entityManager.persist(newDWAccount);
                assertNotNull(entityManager.find(DWAccount.class, new Long(1234));
	}
}