Error in apex test logs: common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject" - testing

Here is what i tried. I think the problem is somewhere in the test class when i create the apex test controller and i want to link the record of the controller to the solution that i created in the test class.
This is the error that i found in logs:
"common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject"|0x4888dd3c
apex class:
public with sharing class SolutionWrapper {
public ApexPages.StandardSetController controller;
public Opportunity opp{get; set;}
public Solutions__c oppId{get; set;}
public Solutions__c sol{get; set;}
public Solutions__c solution{get; set;}
public Account acc{get; set;}
public SolutionWrapper(ApexPages.StandardSetController controller) {
try{
solution = new Solutions__c();
solution = (Solutions__c)controller.getRecord();
if(solution.Id != null){
oppId = [SELECT id, Solutions__c.Opportunity__c
FROM Solutions__c
WHERE id =: solution.Id
LIMIT 1];
opp = [Select id,Name, AccountId, CurrencyIsoCode from
Opportunity where id =: oppId.Opportunity__c LIMIT:1];
}
if(opp.id !=null){
sol = [SELECT id,Name, Mail_Merge_Id__c,Solution_Country__c, Solutions__c.Opportunity__c
FROM Solutions__c
WHERE Solutions__c.Opportunity__c =: opp.id
LIMIT 1];
acc = [Select id,Name,Country__c from
Account where id=:opp.AccountId LIMIT: 1];
}
}
catch(Exception e){
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,e.getMessage()));
}
}
}
Here is my test class
apex test class:
#isTest
public class SolutionWrapperTest {
static testMethod void testMethodOpp(){
Account acc = new Account(Name='test', Country__c='test');
insert acc;
Opportunity opp = new Opportunity(Name='test', AccountId=acc.id, CurrencyIsoCode='GBP', StageName = 'Good',
CloseDate = date.today());
insert opp;
Solutions__c sol = new Solutions__c( Opportunity__c= opp.id, CurrencyIsoCode='GBP');
insert sol;
List<Solutions__c> listSol = new List<Solutions__c>();
listSol.add(sol);
PageReference pageRef = Page.NewVisualForcePage;
Test.setCurrentPage(pageRef);
Test.startTest();
ApexPages.StandardSetController stdController = new ApexPages.StandardSetController(listSol);
SolutionWrapper testSolution = new SolutionWrapper(stdController);
Test.stopTest();
}
}

Solution id is different from the one that i inserted in the test class. I inserted a dummy value (eq 'test') on a field like Currency. After that i selected from the db based on Currency instead of id.

Related

While using Spring MVC I am trying to insert a table data to another one using #Controller but don't know how

I am trying to transfer by insert from a table to another table in #Controller
I will explain here better,
So I have an Employee table and i want to transfer first name . last name and function , to the Monday table, but I don't really understand how I can do it .
here are some code i did PS. the language is Romanian so Luni = Monday the rest is is obvious.
I have all the CRUD implemented
WeekdayDAO
public class WeekdayDAO {
public void insertLuni(Luni luni) throws SQLException{
Connection conn = DBHelper.getConnection();
String insertString=" INSERT INTO luni (nume, prenume, funcite) SELECT nume, prenume,funtie FROM employee WHERE id=?" ;
PreparedStatement stmt = conn.prepareStatement(insertString);
stmt.setString(1, luni.getNume() );
stmt.setString(2, luni.getPrenume());
stmt.setString(3, luni.getFunctie());
stmt.executeUpdate();
DBHelper.closeConnection(conn);
}
Calendar controller
Explanation : so I need to create a link when i chose an employee by id to just add all the data I requested in Monday, because after that I want to show it in a table like all the Employees I added in that day.
#Controller
public class WeekController {
#RequestMapping(value = "detalii/{employeeId}")
public ModelAndView getEmployeeDetails(#PathVariable String employeeId) throws SQLException {
EmployeeDAO edao = new EmployeeDAO();
Employee employee = edao.getEmployeeById(employeeId);
edao.getEmployeeById(employeeId);
ModelMap model = new ModelMap();
model.put("employee", employee);
return new ModelAndView("employee/detalii", "model", model);
}
#RequestMapping(value = "detalii/{employeeId}"/addEmployeeDay.htm", method = RequestMethod.POST)
public ModelAndView addEmployeeDay(#PathVariable String employeeId, Model model) throws SQLException {
EmployeeDAO edao = new EmployeeDAO();
Employee employee = edao.getEmployeeById(employeeId);
edao.getEmployeeById(employeeId);
WeekdayDAO wdao = new WeekdayDAO();
Luni luni= wdao.insertLuni(luni);
return new ModelAndView("employee/edit", "model", model);
}
}
Other example is trying to change some stuff from the edit Employee but it doesn't work .
#RequestMapping(value = "editEmployee/{employeeId}")
public ModelAndView displayEditForm(#PathVariable String employeeId, Model model) throws SQLException {
EmployeeDAO edao = new EmployeeDAO();
Employee e = edao.getEmployeeById(employeeId);
model.addAttribute("employeeForm", e);
return new ModelAndView("employee/edit", "model", model);
}

ASP.NET Web API - SQL - Retrieving Information

I am having some issues with retrieving information from sql database using ASP.net Web API.
I have tried to use forms, which worked great (using gridview) but when I try to do it using a separate class dedicated to store my specific table information I get this error:
"Index was out of range. Must be non-negative and less than the size of the collection."
This is the code:
public ActionResult Details()
{
List<Employee> employeeList = new List<Employee>();
string CS = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
using (var myConn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("select * from tblEmployee", myConn);
myConn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int i = 0;
employeeList[i].PersonID = Convert.ToInt32(rdr["PersonID"]);
employeeList[i].Name = rdr["Name"].ToString();
employeeList[i].Gender = rdr["Gender"].ToString();
employeeList[i].City = rdr["City"].ToString();
employeeList[i].DepartmentID = Convert.ToInt32(rdr["DepartmentID"]);
i++;
}
return View(employeeList);
}
}
This is the Employee class:
[Table("tblEmployee")]
public class Employee
{
public int PersonID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DepartmentID { get; set; }
}
}
I get this error on any of the retrieving information lines.
The table has 5 columns: PersonID(int PK), Name(nvarchar), Gender(nvarchar), City(nvarchar), DepartmentID(int).
I checked many times the columns names to make sure I didn't got those wrong and I double checked the connection string which is also fine (the same code works with gridview using forms API).
Hope someone can help me with this. I didn't find any specific information on that and I guess it's should be easy and I'm doing something wrong here.
You are trying to populate a List<> object by using an index. To populate a List<> you need to use .Add(). You need to change your code from this:
int i = 0;
employeeList[i].PersonID = Convert.ToInt32(rdr["PersonID"]);
employeeList[i].Name = rdr["Name"].ToString();
employeeList[i].Gender = rdr["Gender"].ToString();
employeeList[i].City = rdr["City"].ToString();
employeeList[i].DepartmentID = Convert.ToInt32(rdr["DepartmentID"]);
i++;
To this:
Employee emp = new Employee();
emp.PersonID = Convert.ToInt32(rdr["PersonID"]);
emp.Name = rdr["Name"].ToString();
emp.Gender = rdr["Gender"].ToString();
emp.City = rdr["City"].ToString();
emp.DepartmentID = Convert.ToInt32(rdr["DepartmentID"]);
employeeList.Add(emp);
When adding a new item to a list, you should use .Add(). Here's one option:
while (rdr.Read())
{
employeeList.Add(new Employee {
PersonID = Convert.ToInt32(rdr["PersonID"]),
Name = rdr["Name"].ToString(),
Gender = rdr["Gender"].ToString(),
City = rdr["City"].ToString(),
DepartmentID = Convert.ToInt32(rdr["DepartmentID"])
});
}
You could then access individual items in the list with their index or by using foreach.

No DataSerializeFactory registered for namespace

I tried it in HZ 3.4 and 3.4.1 but with the same output
I`m trying to import dummy data to my Hazelcast cluster, with following function
HazelcastInstance cluster = HazelcastClient.newHazelcastClient(this.conf);
Map<String, Customer> mapCustomers = cluster.getMap("customers");
System.out.println(mapCustomers.size());
System.out.println("hello world");
for (int customerID = 0; customerID < 2000; customerID++) {
Customer p = new Customer();
mapCustomers.put(Integer.toString(customerID), p);
System.out.println("inserted customer number " + Integer.toString(customerID));
}
cluster.shutdown();
when I first run this code, there are no issues and the output is something like this
0
hello world
inserted customer number 0
inserted customer number 1
inserted customer number 2
inserted customer number 3
the problem is if I try to run the import function if there are data already - everytime I got
4
hello world
Exception in thread "main"
com.hazelcast.nio.serialization.HazelcastSerializationException: No DataSerializerFactory registered for namespace: 1
at com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:98)
at com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:39)
at com.hazelcast.nio.serialization.StreamSerializerAdapter.toObject(StreamSerializerAdapter.java:65)
at com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:260)
at com.hazelcast.client.spi.ClientProxy.toObject(ClientProxy.java:173)
at com.hazelcast.client.spi.ClientProxy.invoke(ClientProxy.java:128)
at com.hazelcast.client.proxy.ClientMapProxy.put(ClientMapProxy.java:352)
at com.hazelcast.client.proxy.ClientMapProxy.put(ClientMapProxy.java:200)
at com.test.queries.Importer.importDummyData(Importer.java:42)
at run_import.main(run_import.java:9)
I am using DataSerializableFactory
public class SerializerFactory implements DataSerializableFactory {
public static final int FACTORY_ID = 1;
public static final int CUSTOMER_TYPE = 1;
public static final int ORDER_TYPE = 2;
#Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case CUSTOMER_TYPE:
return new Customer();
case ORDER_TYPE:
return new Order();
}
return null;
}
}
public class Customer implements IdentifiedDataSerializable {
....
#Override
public int getFactoryId() {
return SerializerFactory.FACTORY_ID;
}
#Override
public int getId() {
return SerializerFactory.CUSTOMER_TYPE;
}
....
}
and my xml config:
....
<serialization>
<data-serializable-factories>
<data-serializable-factory factory-id="1">
SerializerFactory
</data-serializable-factory>
</data-serializable-factories>
<portable-version>0</portable-version>
</serialization>
....
You have to configure the DataSerializableFactory on both ends, servers and clients. That also means the code needs to be available at both positions :)

Many-to-many relationship, update referenced Set (update join table) throw NonUniqueObjectException

I am using hibernate. I have a Many-to-Many relationship between Student and Group classes. There is a join table named student_group which has student_id and group_id columns.
Student class:
#Entity
#Table(name = "student")
public class Student {
private int student_id; //primary key
#ManyToMany(mappedBy = "students")
private Set<Group> groups = new HashSet<Group>();
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="student_group",
joinColumns={#JoinColumn(name="student_id")},
inverseJoinColumns={#JoinColumn(name="group_id")})
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
//Setter & Getter for student_id
...
}
Group class:
#Entity
#Table(name = "group")
public class Group {
private int group_id;//primary key
private Set<Student> students = new HashSet<Student>();
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="student_group",
joinColumns={#JoinColumn(name="group_id")},
inverseJoinColumns={#JoinColumn(name="student_id")})
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
//Getter & Setting for group_id
...
}
In my main program I have a function which 1st find a student from database, then, add a group to the student and finally try to save the updated student to database:
public void addGroupToStudent(int studentId, Group newGroup){
//open a session & query the database to get a student by id
Session session = sessionFactory.openSession();
Student student = loadStudentById(session, id);
//Get above student's groups
Set<Group> groups = student.getGroups();
//Add the new group
groups.add(newGroup);
//SaveAndUpdate the student in database
Transaction transaction = session.beginTransaction();
try {
session.saveOrUpdate(student);
transaction.commit();
} catch (final HibernateException e) {...}
}
(The newGroup parameter in above function is retrieved from database with another session & query.)
But the above function throw the following exception:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.my.db.Group#5]
at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:697)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:296)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:241)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:109)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
Where am I wrong? How to get rid of this exception? Generally I just want to update a student's groups in database, which in turns should update the join table.

Create a test method to a class - Force.com

Can anyone help me to create a test method for the following class. The basic idea of this code is to clone a patent with all child elements and just change the date.
public class NovoDia {
//added an instance varaible for the standard controller
private ApexPages.StandardController controller {get; set;}
// add the instance for the variables being passed by id on the url
private Itinerario_Diario__c po {get;set;}
private Itinerario_Diario__c pi {get;set;}
// set the id of the record that is created -- ONLY USED BY THE TEST CLASS
public ID newRecordId {get;set;}
// initialize the controller
public NovoDia(ApexPages.StandardController controller) {
//initialize the stanrdard controller
this.controller = controller;
// load the current record
po = (Itinerario_Diario__c)controller.getRecord();
}
// method called from the VF's action attribute to clone the po
public PageReference cloneWithItems() {
// setup the save point for rollback
Savepoint sp = Database.setSavepoint();
Itinerario_Diario__c newPO;
try {
//copy the purchase order - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
po = [select Dia__c from Itinerario_Diario__c where id = :po.id];
newPO = po.clone(false);
insert newPO;
// set the id of the new po created for testing
newRecordId = newPO.id;
// copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
List<Viagem__c> items = new List<Viagem__c>();
//PI.Dia__c = PO.Dia__c;
for (Viagem__c pi : [Select Cliente__c,Inicio_planejado__c,Entrada_Sa_da_de_Turno__c,Meio_de_Solicitacao__c,Motorista__c,Rota__c,Tipo_de_Viagem__c,Turno__c,Veiculo__c From Viagem__c p where Itinerario_Diario__c = :po.id ]) {
Viagem__c newPI = pi.clone(false);
newPI.Itinerario_Diario__c = newPO.id;
//newPI.Dia__c = PO.Dia__c;
items.add(newPI);
}
insert items;
} catch (Exception e){
// roll everything back in case of error
Database.rollback(sp);
ApexPages.addMessages(e);
return null;
}
return new PageReference('/'+newPO.id+'/e?retURL=%2F'+newPO.id);
}
I really appreciate the help.
Thanks
Sylvio
static testmethod void NovoDia_Test(){
Itinerario_Diario__c itinerarioDiario= new Itinerario_Diario__c();
insert itinerarioDiario;
ApexPages.StandardController sc = new ApexPages.StandardController(itinerarioDiario);
NovoDia cttr = new NovoDia (sc);
cttr.cloneWithItems();
}