Creating a test Class for batch apex - salesforce

I am having truble creating a test class for this particular class. If anyone could provide some code that would implement this I would be very grateful.
Many thanks
Class:
global class TalentIntCustomerBatch implements Database.Batchable<sObject>, Database.AllowsCallouts{
global final String query;
global TalentIntCustomerBatch(String q){
query=q;
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
for(sObject s : scope){
Contact c = (Contact)s;
TalentIntegrationUtils.updateCustomer(c.Id, c.LastName);
}
}
global void finish(Database.BatchableContext BC){}
}

You will need to populate the data in test to create the contacts and any other objects your TalentIntegrationUtils class needs, but the following code should work to test it:
string query = 'Select Id, LastName From Contact';
TalentIntCustomerBatch ticb = new TalentIntCustomerBatch(query);
Database.executeBatch(ticb);
From the name of your class, you may be making call outs to external systems during the test. If this is the case you will either need to add an "if (Test.isRunningTest() == false)" block around all of your call outs or implement a mock response:
Testing Web Service Callouts
Testing HTTP Callouts by Implementing the HttpCalloutMock Interface

Related

Apex Batch, accessing global variable from an other class, getting null value

I have a simple batch with global variable as :
global with sharing class sampleBatchApex implements Database.Batchable<sObject>{
global List<Case> myList;
global Database.QueryLocator start(Database.BatchableContext BC){
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
//some stuff;
}
global void finish(Database.BatchableContext BC){
myList = SELECT ID ... FROM ...
}
}
And an other where I try to get myList
public class BatchApexProgressIndicatorController {
public static sampleBatchApex myBatchObject = new sampleBatchApex();
the batch is executed in an other method, and I'm monitoring the job. Once it's finished, I'm calling the following method to get myList
#AuraEnabled
public static List<Case> getCases(){
return myBatchObject.myList;
}
}
It keeps me getting empty list.
However if I System.debug the list in the finish method of the batch, i can see that the list is not empty.
Could you please hint me on how can I get this list from the other class ?
Thank you
You can't do that. Batch Apex and #AuraEnabled Lightning controller code execute in completely separate transaction contexts; they do not share any variables.
When your batch class is enqueued for execution it is serialized and later deserialized and executed by the platform. Your calling code does not retain a reference to the actual, executing batch instance. Further, your class isn't declared with the Database.Stateful marker interface, so it won't retain member variable values between btches in any case.
You'll need to use a different strategy to monitor your batch job, depending on just what your batch job does. This could be polling sObjects with SOQL, posting Platform Events from the batch, etc.

Retrieve executionId inside CommandInterceptor

I am implementing my own Activiti command intereceptor like this :
public class ActivitiCommandInterceptor extends AbstractCommandInterceptor {
private RuntimeService runtimeService;
private CommandInterceptor delegate;
public ActivitiSpringTxCommandInterceptor(RuntimeService runtimeService, CommandInterceptor delegate) {
this.runtimeService = runtimeService;
this.delegate=delegate;
}
#Override
public <T> T execute(CommandConfig config, Command<T> command) {
String myVariable = runtimeService.getVariable(<missingExecutionId>, "myVariableName");
...
}
}
Inside the execute() method I need to retrieve a variable from the execution context related to this command.
To do that, I need to have the executionId, but I can't find a way to retrieve it.
How can I get my variable from this interceptor?
Thanks
You can create a nativeExecutionQuery
This allows us to use SQL to perform operations directly on DB.
For your case, just find all the execution IDs that contains your variables, and filter them according to your need.

What is the design pattern name that used to create an object by passing an engine object

I have a class called DatabaseModel.
And an interface called DatabaseEngineInterface that have a methods such as:
insert
update
delete
select
So I can on running time determine which engine to use mysql or oracle which are a classes that implements the DatabaseEngineInterface
EngineDatabase engine = new MySQLEngine();
DatabaseModel db = new DatabaseModel(engine);
What is this design pattern called?
Specifically, this is the Constructor Injection pattern (described in my book), which is a special case of the Strategy pattern.
Isn't it an implementation of the strategy pattern? Wikipedia states that the strategy pattern is:
>a software design pattern that enables an algorithm's behavior to be selected at runtime
It also says that the strategy pattern:
defines a family of algorithms,
encapsulates each algorithm, and
makes the algorithms interchangeable within that family.
You are allowing the database which will be used (and so the behaviour) to be selected at run time. You have defined a family of algorithms (your interface), encapsulated each algorithm (by creating a class per provider) and they can be used interchangeably as the DatabaseModel depends only on the interface.
DaoFactory design pattern fits well for your implementation.
Interface
public interface DatabaseEngineInterface {
public void insert(User user);
public void update(User user);
public void delete(int userId);
}
Class which implements the above methods:
public class DatabaseModel implements DatabaseEngineInterface {
#Override
public void delete(int userId) {
// delete user from user table
}
#Override
public User[] findAll() {
// get a list of all users from user table
return null;
}
#Override
public User findByKey(int userId) {
// get a user information if we supply unique userid
return null;
}
#Override
public void insert(User user) {
// insert user into user table
}
#Override
public void update(User user) {
// update user information in user table
}
}
Factory
public class DatabaseModelDAOFactory {
public static UserDAO getUserDAO(String type) {
if (type.equalsIgnoreCase("mysql")) {
return new UserDAOMySQLImpl();
} else {
return new UserDAOORACLEImpl();
}
}
}
Client side code:
Then, in the client side instead of a hardcoded line like:
DatabaseModel userDAO=DatabaseModelDAOFactory.getUserDAODatabaseEngineInterface("jdbc");
You could have a properties file to be able to switch between DAOs dynamically, having retrieved that string from the properties file you can simply do:
DatabaseModel userDAO=DatabaseModelDAOFactory.getUserDaoDatabaseEngineInterface(myStringFromPropertiesFile);
myStringFromPropertiesFile would contain "mysql" or "oracle" according to the definition in your properties file.

How can I get started with PHPUnit, where my class construct requires a preconfigured db connection?

I have a class that uses a lot of database internally, so I built the constructor with a $db handle that I am supposed to pass to it.
I am just getting started with PHPUnit, and I am not sure how I should go ahead and pass the database handle through setup.
// Test code
public function setUp(/*do I pass a database handle through here, using a reference? aka &$db*/){
$this->_acl = new acl;
}
// Construct from acl class
public function __construct(Zend_Db_Adapter_Abstract $db, $config = array()){
You would do it like this:
public class TestMyACL extends PHPUnit_Framework_TestCase {
protected $adapter;
protected $config;
protected $myACL;
protected function setUp() {
$this->adapter = // however you create a new ZendDbADapter
$this->config = // however you create a new config array
$this->myACL = new ACL($this->adapter, $this->config); // This is the System Under Test (SUT)
}
}
IMHO, you need to work on your naming conventions. See Zend Framework Naming Conventions, for a start. An example would be the underscore, look up variables in the link. Also class naming.
You can do normally without reference same as constructor because this method is simplest.

Winforms: access class properties throughout application

I know this must be an age-old, tired question, but I cant seem to find anything thru my trusty friend (aka Google).
I have a .net 3.5 c# winforms app, that presents a user with a login form on application startup. After a successful login, I want to run off to the DB, pull in some user-specific data and hold them (in properties) in a class called AppCurrentUser.cs, that can thereafer be accessed across all classes in the assembly - the purpose here being that I can fill some properties with a once-off data read, instead of making a call to the DB everytime I need to. In a web app, I would usually use Session variables, and I know that the concept of that does not exist in WinForms.
The class structure resembles the following:
public class AppCurrentUser {
public AppCurrentUser() { }
public Guid UserName { get; set; }
public List<string> Roles { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
Now, I have some options that I need some expert advice on:
Being a "dumb" class, I should make the properties non-static, instantiate the class and then set the properties...but then I will only be able to access that instance from within the class that it was created in, right?
Logically, I believe that these properties should be static as I will only be using the class once throughout the application (and not creating new instances of it), and it's property values will be "reset" on application close. (If I create an instance of it, I can dispose of it on application close)
How should I structure my class and how do I access its properties across all classes in my assembly? I really would appreciate your honest and valued advice on this!!
Thanks!
Use the singleton pattern here:
public class AppUser
{
private static _current = null;
public static AppUser Current
{
get { return = _current; }
}
public static void Init()
{
if (_current == null)
{
_current = new AppUser();
// Load everything from the DB.
// Name = Dd.GetName();
}
}
public string Name { get; private set; }
}
// App startup.
AppUser.Init();
// Now any form / class / whatever can simply do:
var name = AppUser.Current.Name;
Now the "static" things are thread-unsafe. I'll leave it as an exercise of the reader to figure out how to properly use the lock() syntax to make it thread-safe. You should also handle the case if the Current property is accessed before the call to Init.
It depends on how you setup your architecture. If you're doing all your business logic code inside the actual form (e.g. coupling it to the UI), then you probably want to pass user information in as a parameter when you make a form, then keep a reference to it from within that form. In other words, you'd be implementing a Singleton pattern.
You could also use Dependency Injection, so that every time you request the user object, the dependency injection framework (like StructureMap) will provide you with the right object. -- you could probably use it like a session variable since you'll be working in a stateful environment.
The correct place to store this type of information is in a custom implementation of IIdentity. Any information that you need to identify a user or his access rights can be stored in that object, which is then associated with the current thread and can be queried from the current thread whenever needed.
This principal is illustrated in Rocky Lhotka's CLSA books, or google winforms custom identity.
I'm not convinced this is the right way but you could do something like this (seems to be what you're asking for anyway):
public class Sessions
{
// Variables
private static string _Username;
// properties
public static string Username
{
get
{
return _Username;
}
set
{
_Username = value;
}
}
}
in case the c# is wrong...i'm a vb.net developer...
then you'd just use Sessions.USername etc etc

Resources