How to use #UsingDataSet in Arquillian test - unit-testing

I have trouble using #UsingDataSet in my project.
Example in manual https://docs.jboss.org/author/display/ARQ/Persistence
doesn`t helps.
I have simple entity:
#Entity(name = "game")
#Table(name = "game_entity", schema = "graph")
#GenericGenerator(name="uuid2", strategy = "uuid2")
public class Game implements Serializable {
private static final long serialVersionUID = -4832711740307931146L;
private UUID id;
private String name;
#Id
#GeneratedValue(generator="uuid2")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotNull
#Column(name = "name", length = 256, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object value) {
if (!(value instanceof Game)) {
return false;
}
if (value == this) {
return true;
}
Game obj = (Game) value;
if (!obj.getId().equals(getId())) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result = 29;
result += 29 * (getId() != null ? getId().hashCode() : 0);
result += 29*(getName() != null ? getName().hashCode() : 0);
return result;
}
}
And .yml file
game_entity:
- id : d5c58afd-7c99-41bb-ab0a-6357bfddfe14
name : Call of Duty
My test:
public class MyTest extends Arquillian {
#PersistenceContext(unitName = "spo")
private EntityManager em;
#Test
#UsingDataSet("datasets/gameDataSet.yml")
public void testAttribute() {
System.out.println("Hello world !");
}
#Deployment
public static WebArchive createArchive() {
WebArchive war = ShrinkWrap
.create(WebArchive.class, "myTest.war")
.addAsLibraries(
// blah-blah-blah
)
.addAsResource("my-persistence.xml", "META-INF/persistence.xml")
//.addAsResource("datasets/gameDataSet.yml", "datasets/gameDataSet.yml") // do I need to add this to archive ??
.addAsWebInfResource("META-INF/beans.xml", "beans.xml")
.setWebXML("web.xml")
;
return war;
}
}
When I run this test I getting 2 "strange" exeptions.
Sometimes:
Caused by: org.dbunit.dataset.NoSuchColumnException: game_entity.ID - (Non-uppercase input column: id) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
But there are 2 columns in database! "id" and "name"
Sometimes, even more strange exception:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "info_resource_attributes" does not exist
This is cross-table for another 2 entities, it exist in archive and myPersistence.xml but I dont use them in this test.
I use Wildfly 10 and Postgres 9.5. Without #UsingDataSet everything fine.
But I dont want programmaticaly hardcode data for tests like that:
Entity newEntityForTest = new Entity();
newEntityForTest.setA(...);
newEntityForTest.setB(...);
newEntityForTest.setC(...);
em.persist(newEntityForTest);
// testing ...
em.remove(newEntityForTest);

Related

Validation of the application resource model has failed during application initialization

I'm trying to create a simple get request using jersey
but got exception
can someone tell me where I got it wrong?
The excption is - "Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
"
VersionResource.java
#Path("/versions")
public class VersionResource extends BaseResource<VersionDao, VersionTable>
{
public VersionResource(VersionDao objectDao)
{
super(objectDao);
}
#Override
#Path("/getAppVersions")
#GET
#UnitOfWork
public String getAllRecords(#Context HttpServletRequest req, #QueryParam("callback") String callback) throws JsonProcessingException
{
return super.getAllRecords(req, callback);
}
}
VersionTable.java
#Entity(name = "Versions")
#Table(name = "Versions")
#NamedQueries({ #NamedQuery(name = QueryNames.QUERY_VERSION_GET_ALL, query = "select c from Versions c"), })
public class VersionTable extends baseDataBase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "VersionId")
private short versionId;
#Column(name = "VersionPlatform")
#JsonProperty
#NotEmpty
private String versionPlatform;
#Column(name = "VersionNumber")
#JsonProperty
#NotEmpty
private String versionNumber;
#Column(name = "VersionDescription")
#JsonProperty
#NotEmpty
private String versionDescription;
public short getVersionId()
{
return versionId;
}
public void setVersionId(short versionId)
{
this.versionId = versionId;
}
public String VersionPlatformEnum()
{
return versionPlatform;
}
public void setVersionPlatform(String versionPlatform)
{
this.versionPlatform = versionPlatform;
}
public String getVersionNumber()
{
return versionNumber;
}
public void setVersionNumber(String versionNumber)
{
this.versionNumber = versionNumber;
}
public String getVersionDescription()
{
return versionDescription;
}
public void setVersionDescription(String versionDescription)
{
this.versionDescription = versionDescription;
}
}
VersionDao.java
public class VersionDao extends baseAbstractDao<VersionTable> implements IDatabaseActions<VersionTable>
{
public VersionDao(SessionFactory sessionFactory)
{
super(sessionFactory);
}
#Override
public ObjectDaoResponse getAllTableRecords() throws JsonProcessingException
{
List<VersionTable> list = list(namedQuery(QueryNames.QUERY_VERSION_GET_ALL));
return ObjectDaoResponse.getAnOkResponse(list);
}
}
I think you need a no arg constructor for your VersionResource class, but if you really need an argument the value should be passed by injection (see: https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/jaxrs-resources.html#d0e2692)

Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value:

Hi here is Bussinss object class where pwdId and userId are notnull in db
#Entity
#Table(name="CLOUD_SVR_PASSWORDS_HISTORY")
#NamedQuery(name="CloudSvrPasswordsHistory.findAll", query="SELECT c FROM CloudSvrPasswordsHistory c")
public class CloudSvrPasswordsHistory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="PWD_ID",nullable=false)
private long pwdId;
#Column(name="OLD_PASSWORD")
private String oldPassword;
#Column(name="CURRENT_PASSWORD")
private String currentPassword;
#Column(name="PWD_CHANGE_TYPE")
private String pwdChangeType;
#Column(name="CREATED_DATE")
private Timestamp createdDate;
#ManyToOne
#JoinColumn(name="USER_ID",nullable=false)
private CloudSvrUser user;
public long getPwdId() {
return pwdId;
}
public void setPwdId(long pwdId) {
this.pwdId = pwdId;
}
public String getOldPassword() {
return oldPassword;
}
public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getPwdChangeType() {
return pwdChangeType;
}
public void setPwdChangeType(String pwdChangeType) {
this.pwdChangeType = pwdChangeType;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
public CloudSvrUser getUser() {
return user;
}
public void setUser(CloudSvrUser user) {
this.user = user;
}
here is my service implementation class only one method I am specifyng
#Transactional
public void changePassword(CloudSvrPasswordsHistory pwdInfo)throws BusinessException
{
//String password=null;
try{
System.out.println("servcimpl----------");
CloudSvrUser dbUser =getUser(pwdInfo);
if(dbUser != null){
List<CloudSvrPasswordsHistory> newPwdList = new ArrayList<CloudSvrPasswordsHistory>();
CloudSvrPasswordsHistory changedPwd = new CloudSvrPasswordsHistory();
changedPwd.setOldPassword(pwdInfo.getOldPassword());
changedPwd.setCurrentPassword(pwdInfo.getCurrentPassword());
newPwdList.add(changedPwd);
dbUser.setPassCode(changedPwd.getCurrentPassword());
//set childs to parent
pwdInfo.setUser(dbUser);
dbUser.setUserPwdList(newPwdList);
//password=
changedPwd(dbUser);
System.out.println("serviceimplend---------");
}
}
catch(DaoException daoexception)
{
throw new BusinessException(daoexception.getMessage());
}
//return password;
}
here is my DAOImpl class
#Repository("passwordDao")
public class PasswordDaoImpl extends BaseDaoImpl implements PasswordDao
{
PasswordDaoImpl()
{}
public void ChangedPwd(CloudSvrUser user)
{
//String password=null;
List<CloudSvrPasswordsHistory> pwdinfo = user.getUserPwdList();
for(CloudSvrPasswordsHistory changedPwd:pwdinfo)
{
//changedPwd.setPwdId((new Long(1)));
changedPwd.setCreatedDate(new Timestamp(System.currentTimeMillis()));
changedPwd.setPwdChangeType("ByUser");
}
try{
super.getHibernateTemplate().update(user);
//this.userDao.updateUser(dbUser);
}
catch(DataAccessException accessException){
throw new DaoException("Internal DB error occured.");
}
//return password ;
}
when giving request getting exception in console
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.omnypay.dao.bo.CloudSvrPasswordsHistory.user
please help me
The error says the user property of CloudSvrPasswordsHistory entity is null, where as hibernate is expecting it to be not-null, this is because you told hibernate that nullable=false for user property using this mapping:
#ManyToOne
#JoinColumn(name="USER_ID",nullable=false)
private CloudSvrUser user;
So to fix the issue you have to set the user property for your CloudSvrPasswordsHistory entity as:
changedPwd.setUser(dbUser);

how can i resolve this "Etat HTTP 500 - java.lang.NullPointerException"?

i'm developping a restful web service that extract data (messages) from my database and return all messages!
every single message is a MsgBean ( with an id, contenu, from, numexp,... )
the web service couldn't return a table so i created a new object that contain a table (msgTable) of MsgBean !
while running my web service on the rest console, i got this error :
Etat HTTP 500 - java.lang.NullPointerException
type Rapport d''exception
message java.lang.NullPointerException
description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.
Click to see the rest of error
my MsgBean is :
#XmlRootElement
public class MsgBean implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String frommm;
private String contenu;
private String DateEnvoi;
private String NumExp;
private int idu;
public MsgBean(){};
#XmlElement
public int getIdu() {
return idu;
}
public void setIdu(int idu) {
this.idu = idu;
}
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getFrommm() {
return frommm;
}
public void setFrommm(String frommm) {
this.frommm = frommm;
}
#XmlElement
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
#XmlElement
public String getDateEnvoi() {
return DateEnvoi;
}
public void setDateEnvoi(String DateEnvoi) {
this.DateEnvoi = DateEnvoi;
}
#XmlElement
public String getNumExp() {
return NumExp;
}
public void setNumExp(String NameExp) {
this.NumExp = NameExp;
}
}
my msgTabl is :
#XmlRootElement
public class msgTabl implements Serializable {
String test;
MsgBean[] m = new MsgBean[100];
public msgTabl(){};
#XmlElement
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
#XmlElement
public MsgBean getM(int i) {
return m[i];
}
public void setM(int i, MsgBean mb) {
this.m[i].setId(mb.getId());
this.m[i].setIdu(mb.getIdu());
this.m[i].setFrommm(mb.getFrommm());
this.m[i].setNumExp(mb.getNumExp());
this.m[i].setDateEnvoi(mb.getDateEnvoi());
this.m[i].setContenu(mb.getContenu());
}
}
and here is the web service that i did test with :
#GET
#Path("/historiquemethod")
#Produces("application/json")
//#Produces("text/plain")
public msgTabl historique(
#QueryParam("pseudo") String pseudo,
#QueryParam("motDePasse") String motDePasse
) {
msgTabl tab = new msgTabl();
MsgBean ms = new MsgBean();
// set information into our msg to test
ms.setContenu("contenu");
ms.setFrommm("8080");
ms.setNumExp("2584126");
ms.setId(1);
ms.setIdu(2);
ms.setDateEnvoi("date");
// set the message into the first table case
tab.setM(0, ms);
tab.setTest("ok");
return tab;
}
In setM method do this in first line :
this.m[i] = new MsgBean();
Problem is that you have instantiated your array but the objects are null inside that array. So you need to first instantiate the object at required index and then use it.
UPDATE FOR COMMENT
Make a getter method for your m like this getM() and annotate it with XmlElement(Remove the annotation from your current overloaded getM(int i) method). The method getM(int i) cannot be used by JAXB, since jaxb needs simple getter and setter for your properties.

Mock with Rhino mock -MVVM

I am using Rhino mock for mocking in my test methods. Could someone please see the TODO part in the test method and help me to mock it?
This is my service interface:
public interface ICustomersServiceAgent
{
void GetCustomers(EventHandler<GetCustomersCompletedEventArgs> callback);
void SaveCustomer(POC.Model.Customer cust, EventHandler<SaveCustomerCompletedEventArgs> callback);
}
This is my ViewModel
public class CustomerVM : ViewModelBase
{
private Model.Customer _curentCustomer;
private RelayCommand _saveCommand;
private ICustomersServiceAgent ServiceAgent { get; set; }
private bool isSaved;
private RelayCommand _calculateAgeCommand;
private Decimal age;
private DateTime dateOfBirth;
public CustomerVM(ICustomersServiceAgent serviceAgent)
{
if (serviceAgent == null)
{
ServiceAgent = ServiceManager.GetCustomerServiceManagement();
}
else
{
ServiceAgent =serviceAgent;
}
WireCommands();
}
// if curent object is null then it should be intialize
public Model.Customer CurentCustomer
{
get { return _curentCustomer ?? (_curentCustomer = new Model.Customer()); }
set
{
if (_curentCustomer != value)
{
_curentCustomer = value;
OnPropertyChanged("CurentCustomer");
}
}
}
public RelayCommand CalculateAgeCommand
{
get;
private set;
}
private void WireCommands()
{
SaveCustomerCommand = new RelayCommand(SaveCustomer);
SaveCustomerCommand.IsEnabled = true;
CalculateAgeCommand = new RelayCommand(CalculateAge);
}
private void SaveCustomer()
{
var cus = CurentCustomer;
ServiceAgent.SaveCustomer(cus, (s, e) =>
{
IsSaved = e.Result;
});
}
private void CalculateAge()
{
Age = DateTime.Now.Year - DateOfBirth.Year;
}
public RelayCommand SaveCustomerCommand
{
get;
private set;
}
public bool IsSaved
{
get { return isSaved; }
set
{
isSaved = value;
OnPropertyChanged("IsSaved");
}
}
public decimal Age
{
get { return age; }
set {
age = value;
OnPropertyChanged("Age");
}
}
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set {
dateOfBirth = value;
OnPropertyChanged("DateOfBirth");
}
}
}
I want to test the SaveCustomerCommand in ViewModel above.
So In the my test method, I want to mock the void SaveCustomer(POC.Model.Customer cust, EventHandler<SaveCustomerCompletedEventArgs> callback) method in the ICustomersServiceAgent interface.
This is my test method, see the ToDo part
[TestMethod]
public void SaveCustomerCommandTest()
{
var customerServiceMock = MockRepository.GenerateMock<ICustomersServiceAgent>();
var customerVM = new POC.SilverlightClient.ViewModel.CustomerVM(customerServiceMock);
// TO do : Code to mock SaveCustomer method ///////////////////////////////////
var saveCustomerCommand = customerVM.SaveCustomerCommand;
saveCustomerCommand.Execute(null);
Assert.IsTrue(customerVM.IsSaved);
}
Could someone please explain how I can do this?
I don't see why you need to mock SaveCustomer. All the private SaveCustomer method does is invoke the ServiceAgent service which you already are mocking. I assume the RelayCommand class invokes the delegate you're sending in the constructor parameter which is the call to SaveCustomer. Have you tried running the unit test in your question as-is?
Try following:
customerServiceMock.Stub(sa => sa.SaveCustomer(Arg<POC.Model.Customer>.Is.Anything, Arg<EventHandler<SaveCustomerCompletedEventArgs>>.Is.Anything)).WhenCalled(invocation =>
{
((EventHandler<SaveCustomerCompletedEventArgs>)invocation.Arguments[1])(
customerServiceMock,
new SaveCustomerCompletedEventArgs { Result = true });
});

How to set value of list<String> in DynamicJasper

I need to generate dynamic count of columns in me report. So I set to my JasperPrint the massive of Object:
Object[] obj = new Object[selectedUsers.size()];
//fill the massive
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));
My obj is a class:
public class ResultsDTO {
private String login;
private Integer id;
private List<String> list;
private Object[] results;
public Object[] getResults() {
return results;
}
public void setResults(Object[] results) {
this.results = results;
}
public ResultsDTO(){
}
public ResultsDTO(Integer id,String login) {
super();
this.login = login;
this.id = id;
}
public ResultsDTO(String login, Integer id, List<String> list) {
super();
this.login = login;
this.id = id;
this.list = list;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public void addToList(String day_result){
this.list.add(day_result);
}
}
and then I try to create columns:
FastReportBuilder firstReport = new FastReportBuilder();
List<AbstractColumn> column_list = new ArrayList<AbstractColumn>();
AbstractColumn columnId = getColumn("id", Integer.class,"№", 30, headerStyle, detailStyle);
AbstractColumn columnLogin = getColumn("login", String.class,"ФИО", 150, headerStyle, detailStyle);
for (int i = 0; i < header.size(); i++){
AbstractColumn column = getColumn("results", Object.class, header.get(i), 80, headerStyle, detailStyle);
column_list.add(column);
}
Eventually I have an exception:
net.sf.jasperreports.engine.design.JRValidationException: Report
design not valid :
1. Class "java.lang.Object" not supported for text field expression.
Please, help! I don' know how to use jasper and list or array
Jasper Reports does not allow Object as a valid type for its elements. I has to be one of the following:
String
Number (or any subclass of it)
Date
Boolean
You should ask each element in the form for its class and pass proper class to the column builder.