APEX Test Class 0% code coverage - unit-testing

I am trying to deploy some code that does something simple, when the user clicks on the accept button, it checks a checkbox (I have a workflow set up on the checkbox) and then I need it to redirect me to a thank you page. At the moment I don't know if my code is correct so I need to get the test correct to test it.
My Apex class:
public class proposalCon {
ApexPages.StandardController stdCtrl;
Public List <PPM_Project__c> PPM_Project_List {get;set;}
public proposalCon(ApexPages.StandardController controller) {
stdCtrl= controller;
PPM_Project_List = [ select Short_Description__c from PPM_Project__c ];
}
public PageReference save(){
upsert PPM_Project_List;
PageReference reRend = new PageReference('/apex/final_approval_canvas_complete');
reRend.setRedirect(true);
return reRend;
}
}
And here is my test attempt:
#isTest
private class proposalConTest{
static testMethod void testProposalCon() {
// List of Message
List <PPM_Project__c> PPM_ProjectList = new List<PPM_Project__c>();
PPM_ProjectList.add(new PPM_Project__c (
Name = 'A Test' ,
Short_Description__c = 'Good Job',
Due_Date__c = system.today()+30,
Final_Design_Artwork__c ='http://proteusleadership.com/DE123'
));
PPM_ProjectList.add(new PPM_Project__c (
Name = 'A Test 2' ,
Short_Description__c = 'Good Job',
Due_Date__c = system.today()+30,
Final_Design_Artwork__c ='http://proteusleadership.com/DEf123'
));
insert PPM_ProjectList;
Account account = new Account(Name='Test Co Pty Ltd');
insert account;
Contact contact = new Contact(firstName='TestFN',LastName='TestLN',email='testfn.testln#test.com',AccountId=account.Id);
insert contact;
// ** Start Testing ***/
proposalCon controller = new proposalCon();
PageReference reRend = new PageReference('/apex/final_approval_canvas_complete');
reRend.setRedirect(true);
PPM_ProjectList = [ select Short_Description__c from PPM_Project__c ];
}
}
I have been trying with no luck and any help would be greatly appreciated.
Thank you.
Joe

You need to instantiate a Standard Controller (feeding it a list of PPM Projects) and then instantiate your custom controller extension - like this:
PPM_Project__c proj = new PPM_Project__c() //you may need further parameters here.
ApexPages.StandardController stdController = new apexPages.StandardController(proj);
proposalCon controller = new proposalCon (stdController);
Then you can save, rerender as you like. Let me know if this works - I haven't executed this code, but this is how I create my own controller extension tests.
This should at least compile. However, I think you may really want a StandardSetController.
The docs are here:
SalesforceDocs
To make a testmethod for the StandardSetController, use something like this:
//instantiate the ApexPages.StandardSetController with an array of projects
ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(PPM_ProjectList);
//create custom controller with the StandardSetController as a param
ProposalCon ext = new ProposalCon(stdSetController);
This guy has more details on how to create a test method for a StandardSetController (and other controllers)

Related

Sales force - Test Apex Class List

I made an Apex Class in the Sandbox to call a List.
Now I need to implement it in the production. To do so, I need to implement a Test with at least 75% Success.
The Apex Class produces a List of “dfind_Research_Projekt__c” from which “dfind_Potenzieller_Kandidat__c “ is the actual record, I use this list to make an iteration and show all the “dfind_Research_Projekt__c” on the page from “dfind_Potenzieller_Kandidat__c “.
This is my Apex Class:
public with sharing class dfind_Pot_Job_Application_List {
#AuraEnabled
//Get Pot Job Application List
public static List<dfind_Research_Projekt__c> getJobApp(Id recordId) {
List<dfind_Research_Projekt__c> JobAppList = [Select Id, Name, dfind_Potenzieller_Kandidat__c, dfind_Job__c,
LastModifiedById, dfind_Bewerbungsdatum__c, dfind_Job_Name__c,
OwnerId
from dfind_Research_Projekt__c
where dfind_Potenzieller_Kandidat__c = :recordId
ORDER BY dfind_Bewerbungsdatum__c DESC NULLS LAST];
return JobAppList;
}
//Get User
#AuraEnabled
public static user fetchUser(){
User u = [select id,Name from User where id =: userInfo.getUserId()];
return u;
}
}
This is my test:
#isTest
public class TESTdfind_pot_job_app {
static testMethod void myUnitTest() {
//Create Data for Customer Objet
cxsrec__Potential_candidate__c objKandi = new cxsrec__Potential_candidate__c();
objKandi.Name = 'Test Kandidat';
insert objKandi;
//Create List
List<dfind_Research_Projekt__c> listOfPotApp = new List<dfind_Research_Projekt__c>{
new dfind_Research_Projekt__c(Name='Test Appplication'
, dfind_Job__c='a0w0X000008KKB5QAO'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ'),
new dfind_Research_Projekt__c(Name='Test Appplication 1'
, dfind_Job__c='a0w1x0000013aSRAAY'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ'),
new dfind_Research_Projekt__c(Name='Test Appplication 2'
, dfind_Job__c='a0w1x000000JJSBAA4'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ')
};
insert(listOfPotApp);
Test.startTest();
// Starts the scope of test
// Now check if it is giving desired results using system.assert
// Statement.New invoice should be created
List<dfind_Research_Projekt__c> JobAppList = new List<dfind_Research_Projekt__c>(listOfPotApp);
Test.stopTest(); // Ends the scope of test
for(Integer i=0;i<JobAppList.Size();i++) {
system.assertEquals(JobAppList[i].dfind_Potenzieller_Kandidat__c,objKandi.Id);
System.debug(i + 'Kandidat: ' + JobAppList[i].dfind_Potenzieller_Kandidat__c + ';');
System.debug(i + ': ' + objKandi.Id + ';');
}
system.assertEquals(1,1);
}
}
The hard-coded Ids in your unit test won't work. Your unit tests executes in an isolated data context and must generate all of its own test data.
As written, this test doesn't really do anything. It does not invoke the code you intend to test, as it must to evaluate its behavior and obtain code coverage. You'd need to call fetchUser() and getJobApp() at some point and write assertions about their return values. The assertions that are currently present are all tautological; they're guaranteed to pass and provide no information.
See How do I write an Apex unit test? on Salesforce Stack Exchange for introductory resources.

How to refer PageReference method from apex test class

I am new to apex, I have created a button to call the apex class through the visual force page.
Here is my visual force page code.
<apex:page standardController="Opportunity"
extensions="myclass"
action="{!autoRun}">
</apex:page>
Here is my apex class.
public class myclass {
private final Opportunity o;
String tmp;
public myclass(ApexPages.StandardController stdController) {
this.o = (Opportunity)stdController.getRecord();
}
public PageReference autoRun() {
String theId = ApexPages.currentPage().getParameters().get('id');
for (Opportunity o:[select id, name, AccountId, from Opportunity where id =:theId]) {
//Create the Order
Order odr = new Order(
OpportunityId=o.id
,AccountId = o.AccountId
,Name = o.Name
,EffectiveDate=Date.today()
,Status='Draft'
);
insert odr;
tmp=odr.id;
}
PageReference pageRef = new PageReference('/' + tmp);
pageRef.setRedirect(true);
return pageRef;
}
}
I want to create test class. I don't know how to refer PageReference autoRun() method from test class. Guys need help if some one can tell me about test class of this apex class.
You will need to configure the StandardController for the inserted Opportunity. Then pass the StandardController to pass to the constructor before calling the method to test.
E.g.
public static testMethod void testAutoRun() {
Opportunity o = new Opportunity();
// TODO: Populate required Opportunity fields here
insert o;
PageReference pref = Page.YourVisualforcePage;
pref.getParameters().put('id', o.id);
Test.setCurrentPage(pref);
ApexPages.StandardController sc = new ApexPages.StandardController(o);
myclass mc = new myclass(sc);
PageReference result = mc.autoRun();
System.assertNotEquals(null, result);
}

How to create new record from web service in ADF?

I have created a class and published it as web service. I have created a web method like this:
public void addNewRow(MyObject cob) {
MyAppModule myAppModule = new MyAppModule();
try {
ViewObjectImpl vo = myAppModule.getMyVewObject1();
================> vo object is now null
Row r = vo.createRow();
r.setAttribute("Param1", cob.getParam1());
r.setAttribute("Param2", cob.getParam2());
vo.executeQuery();
getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
As I have written in code, myAppModule.getMyVewObject1() returns a null object. I do not understand why! As far as I know AppModule has to initialize the object by itself when I call "getMyVewObject1()" but maybe I am wrong, or maybe this is not the way it should be for web methods. Has anyone ever faced this issue? Any help would be very appreciated.
You can check nice tutorial: Building and Using Web Services with JDeveloper
It gives you general idea about how you should build your webservices with ADF.
Another approach is when you need to call existing Application Module from some bean that doesn't have needed environment (servlet, etc), then you can initialize it like this:
String appModuleName = "org.my.package.name.model.AppModule";
String appModuleConfig = "AppModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(appModuleName, appModuleConfig);
Don't forget to release it:
Configuration.releaseRootApplicationModule(am, true);
And why you shouldn't really do it like this.
And even more...
Better aproach is to get access to binding layer and do call from there.
Here is a nice article.
Per Our PM : If you don't use it in the context of an ADF application then the following code should be used (sample code is from a project I am involved in). Note the release of the AM at the end of the request
#WebService(serviceName = "LightViewerSoapService")
public class LightViewerSoapService {
private final String amDef = " oracle.demo.lightbox.model.viewer.soap.services.LightBoxViewerService";
private final String config = "LightBoxViewerServiceLocal";
LightBoxViewerServiceImpl service;
public LightViewerSoapService() {
super();
}
#WebMethod
public List<Presentations> getAllUserPresentations(#WebParam(name = "userId") Long userId){
ArrayList<Presentations> al = new ArrayList<Presentations>();
service = (LightBoxViewerServiceImpl)getApplicationModule(amDef,config);
ViewObject vo = service.findViewObject("UserOwnedPresentations");
VariableValueManager vm = vo.ensureVariableManager();
vm.setVariableValue("userIdVariable", userId.toString());
vo.applyViewCriteria(vo.getViewCriteriaManager().getViewCriteria("byUserIdViewCriteria"));
Row rw = vo.first();
if(rw != null){
Presentations p = createPresentationFromRow(rw);
al.add(p);
while(vo.hasNext()){
rw = vo.next();
p = createPresentationFromRow(rw);
al.add(p);
}
}
releaseAm((ApplicationModule)service);
return al;
}
Have a look here too:
http://www.youtube.com/watch?v=jDBd3JuroMQ

Mock IDbDataAdapter Fill Method With Moq

I have an object that reads data from an Excel file using, which takes a IDbConnection, IDbDataAdapter and an IDbCommand. I use the adapters fill method to populate a table with data, and this is how I am currently mocking it:
[TestCase]
public void TestReadCellsFromSpreadsheetReadsSuccessfully()
{
var cells = new List<ReportData>
{
new ReportData { CellId = 1, ExcelCellLocation = "A1"},
new ReportData { CellId = 2, ExcelCellLocation = "A2"},
new ReportData { CellId = 3, ExcelCellLocation = "A3"},
new ReportData { CellId = 4, ExcelCellLocation = "A4"}
};
_mockAdapter.Setup(a => a.Fill(It.IsAny<DataSet>()))
.Callback((DataSet ds) =>
{
if (ds.Tables["Table"] == null)
{
ds.Tables.Add("Table");
ds.Tables["Table"].Columns.Add(new DataColumn());
}
var row = ds.Tables["Table"].NewRow();
row[0] = "Test";
ds.Tables["Table"].Rows.Add(row);
});
var excelReader = new ExcelReader(_mockConnection.Object, _mockAdapter.Object, _mockCommand.Object);
excelReader.ReadCellsFromSpreadsheet("Deal Summary", cells);
_mockCommand.VerifySet(c => c.CommandText = It.IsAny<string>(), Times.Exactly(cells.Count));
_mockAdapter.VerifySet(a => a.SelectCommand = _mockCommand.Object, Times.Exactly(cells.Count));
_mockAdapter.Verify(a => a.Fill(It.IsAny<DataSet>()), Times.Exactly(cells.Count));
}
This implementation works, but I feel like I'm doing too much to Mock the adapter... is there a better way to do this?
Do not pass those 3 objects as parameters. Instead pass IDataReader, IDataProvider or sth like that that returns data. Then You just mock this object. And you don't need reference to System.Data in project containing ExcellReader.
And two other things I don't like about your code.
Why TestCase instead of Test?
Are you sure you want to create command and fill dataset for each column separately? (but maybe I don't understand your code)
In general, I have some rules about data access:
Write a simple class that wraps all the data access logic, so that other classes don't have to deal with DataAdapters and all that crap.
When you write unit tests, don't mock out DataAdapters; instead just mock out the wrapper classes that you just created.
Make the data access wrapper logic so simple that it doesn't really need to be unit tested. If it DOES need to be tested, then write integration tests that hit a small sample database.

Moq - How to unit test changes on a reference in a method

Another day , another question. My service layer has the following method
public MatchViewData CreateMatch(string user)
{
var matchViewData = !HasReachedMaxNumberOfMatchesLimit(user) ?
CreateMatchAndAddToRepository(user) :
MatchViewData.NewInstance(new Match(user));
matchViewData.LimitReached = HasReachedMaxNumberOfMatchesLimit(user);
return matchViewData;
}
The method calls the this helper method to create a new match object:
private MatchViewData CreateMatchAndAddToRepository(string user)
{
var match = new Match(user);
MatchRepository.Add(match);
return MatchViewData.NewInstance(match);
}
The repository stores the given match object and sets the id to some value > 0.
public void Add(Match match)
{
Check.Require(match != null);
var numberOfMatchesBefore = Matches.Count;
SetIdPerReflection(match, NextVal());
Matches.Add(match);
Check.Ensure(numberOfMatchesBefore == Matches.Count - 1);
}
The matchviewdata object copies some properties of the the match object (including the id).
My unit test should verify that the resulting viewdata object in the service has an id > 0. To archieve this, i have to mock the repository and the behaviour of the add method. But the service method creates a new match object every time its been called and the add method on the repository updates the referenced match object (there is no need for a return value). I have no idea to solve this with moq.
This is my unit test so far:
[Test]
public void ServiceCreateMatchReturnedMatchViewDataHasNonZeroId()
{
var match = TestUtils.FakePersistentMatch(User, 1);
var repositoryMock = new Mock<IMatchRepository>();
repositoryMock.Setup(
r => r.Add(It.IsAny<Match>())).Callback(() => match.Id = 1);
var serviceFacade = new DefaultServiceFacade(repositoryMock.Object);
var returnedMatch = serviceFacade.CreateMatch(User);
Assert.That(returnedMatch.Id, Is.GreaterThan(0));
}
I tried some other variations - nothing works.
It looks to me your problem is in this line;
repositoryMock.Setup(
r => r.Add(It.IsAny<Match>())).Callback(() => match.Id = 1);
What you're actually doing here is setting the id of the first match object you have declared in your test, NOT the new match created in your service.
Because the Match object you will be supplying to the Repository is created internally, I can't think of an easy way to reference it in your Test method to setup a callback for it. To me, this is a sign you may be trying to test too much in one unit test.
I think you should simply test that the Add method is called and write a separate test to ensure that it works as exepected.
I propose something like this;
[Test]
public void ServiceAddsNewMatchToRepository()
{
var repositoryMock = new Mock<IMatchRepository>();
bool addCalled = false;
repositoryMock
.Expect(r => r.Add(It.Is<Match>(x => x.Id == 0))
.Callback(() => addCalled = true);
var serviceFacade = new DefaultServiceFacade(repositoryMock.Object);
serviceFacade.CreateMatch(User);
Assert.True(addCalled);
}
....
[Test]
public void AddingANewMatchGeneratesANewId()
{
var match = new Match(user);
var matchRepository = new MatchRepository();
var returnedMatch = matchRepository.Add(match);
Assert.That(returnedMatch.Id, Is.GreaterThan(0));
}