Getting null value in the response from a soap service - web-services

I'm trying to call a soap service. I did't get any exception but response contains null value. But service atleast returns error message. please find or guide any solution.
#Component("createCardServiceImpl")
public class CreateCardServiceImpl implements CreateCardService {
private static final ObjectFactory WS_CLIENT_FACTORY = new ObjectFactory();
private WebServiceTemplate webServiceTemplate;
#Autowired
public void YourServiceClient(WebServiceTemplate webServiceTemplate) {
this.webServiceTemplate = webServiceTemplate;
}
#Override
public FVCardUpdateResponse createUpdateCardRequest(FVCardUpdateRequest fvCardUpdateRequest) {
FVCardUpdateResponse fvCardUpdateResponse=new FVCardUpdateResponse();
try{
FVCardUpdateRequest request = WS_CLIENT_FACTORY.createFVCardUpdateRequest();
request=fvCardUpdateRequest;
SoapActionCallback actionCallBack = new SoapActionCallback("https://www.sampleService/Selfservice.asmx") {
public void doWithMessage(WebServiceMessage msg) {
SoapMessage smsg = (SoapMessage)msg;
SoapHeader soapHeader = smsg.getSoapHeader();
try{
StringSource headerSource = new StringSource("<UserCredentials xmlns='http://www.corecard.com/Prepaid'>\n" +
"<userid>"+"srihari"+"</userid>\n" +
"<password>"+"srihari123"+"</password>\n" +
"</UserCredentials>");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(headerSource, soapHeader.getResult());
smsg.setSoapAction("http://www.sampleservice/CardUpdate");
}catch(Exception e)
{
e.printStackTrace();
}
}
};
fvCardUpdateResponse = (FVCardUpdateResponse) webServiceTemplate.marshalSendAndReceive("https://www.sampleService/Selfservice.asmx", request, actionCallBack);
System.out.println("source "+fvCardUpdateResponse);
}catch (SoapFaultClientException e) {
System.out.println("fault code "+e.getFaultCode());
System.out.println("fault string "+e.getFaultStringOrReason());
System.out.println("stack trace "+e.fillInStackTrace().getLocalizedMessage());
e.printStackTrace();
} catch (WebServiceIOException we) {
System.out.println("In web service IO Exception "+we.getRootCause());
we.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return fvCardUpdateResponse;
}
}
This is my Objec tFactory class
#XmlRegistry
public class ObjectFactory {
public ObjectFactory() {
}
public FVCardUpdateRequest createFVCardUpdateRequest() {
return new FVCardUpdateRequest();
}
public FVCardUpdateResponse createFVCardUpdateResponse()
{
return new FVCardUpdateResponse();
}
}
This is my request class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "CARDUPDATE",propOrder={"CLIENTID","CARDNUMBER","FIRSTNAME"})
#XmlRootElement(name = "CARDUPDATE")
public class FVCardUpdateRequest {
#XmlElement(name = "CLIENTID")
private String CLIENTID;
#XmlElement(name = "CARDNUMBER")
private String CARDNUMBER;
//Other setters and getters
}
This is my response class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "CardUpdateResponse",propOrder={"CARDUPDATE_RET"})
#XmlRootElement(name = "CardUpdateResponse",namespace="http://www.sampleurl.com/Prepaid")
public class FVCardUpdateResponse {
#XmlElement(name="CARDUPDATE_RET")
private CARDUPDATE_RET CARDUPDATE_RET;
//Setters and getters
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "CARDUPDATE_RET", propOrder = {
"ResErrorMsg",
"ResErrorCode",
"ResCode",
"AccountNumber"
})
public class CARDUPDATE_RET {
#XmlElement(name = "AccountNumber")
private String AccountNumber;
#XmlElement(name = "ResCode")
private String ResCode;
#XmlElement(name = "ResErrorCode")
private String ResErrorCode;
#XmlElement(name = "ResErrorMsg")
private String ResErrorMsg;
}
This is my exaple xml response:
<?xml version="1.0" encoding="UTF-8"?>
<CardUpdateResponse xmlns="http://www.sampleurl.com/Prepaid">
<CARDUPDATE_RET>
<ResErrorMsg>Card Updated Successfully</ResErrorMsg>
<ResErrorCode>Msgcu01</ResErrorCode>
<ResCode>1</ResCode>
<ACCOUNTNUMBER>2000000003918246</ACCOUNTNUMBER>
</CARDUPDATE_RET>
</CardUpdateResponse>

Finally i found my mistake in my application that my request and response pojo's are not correct.
My response pojo is like this
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "CardUpdateResponse",namespace="http://www.corecard.com/Prepaid")
public class FVCardUpdateResponse {
#XmlElement(name="CARDUPDATE_RET", namespace="http://www.corecard.com/Prepaid")
private CARDUPDATE_RET response;
//Getters and setters
public static class CARDUPDATE_RET{
#XmlElement(name = "ACCOUNTNUMBER", namespace="http://www.corecard.com/Prepaid")
private String AccountNumber;
#XmlElement(name = "ResCode", namespace="http://www.corecard.com/Prepaid")
private String ResCode;
#XmlElement(name = "ResErrorCode", namespace="http://www.corecard.com/Prepaid")
private String ResErrorCode;
#XmlElement(name = "ResErrorMsg", namespace="http://www.corecard.com/Prepaid")
private String ResErrorMsg;
//Getters and Setters
}
}

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)

Mockito - Unable to initialize Spy on HttpEntity

The code I'm testing works correctly, logs are right.
Tests in error:
ConnectorTest: Unable to initialize #Spy annotated field 'entity'.
Why can't I use verify on the http entity?
Is there a better way to test it? Should I spy on the logs otherwise?
CLASS TO BE TESTED:
public class Connector {
private static final String hostname = "localhost";
private int varnishPort = 8000;
private int connectionTimeout = 5000; //millis
private int requestTimeout = 5000;
private int socketTimeout = 5000;
private final HttpHost host;
private HttpClient httpClient;
private HttpEntity entity;
private HttpResponse response;
public Connector(){
host = new HttpHost(this.hostname, this.varnishPort);
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(connectionTimeout);
requestBuilder = requestBuilder.setConnectionRequestTimeout(requestTimeout);
requestBuilder = requestBuilder.setSocketTimeout(socketTimeout);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
httpClient = builder.build();
}
public void invalidateVarnishCache( String level, String idDb ) {
try{
String xPurgeRegex = level+"/"+idDb+"$";
Header header = new BasicHeader( "X-Purge-Regex", xPurgeRegex );
BasicHttpRequest purgeRequest = new BasicHttpRequest("PURGE", "/" );
purgeRequest.setHeader(header);
response = httpClient.execute(host, purgeRequest);
entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if( statusCode >= 300 ){
int respLength = entity.getContent().available();
byte[] errorResp = new byte[ respLength ];
entity.getContent().read(errorResp, 0, respLength);
// log error
}else{
// log success
}
EntityUtils.consume(entity);
}catch(Exception e){
// log exception
}
}
}
MY TEST:
#RunWith(MockitoJUnitRunner.class)
public class ConnectorTest {
#Mock
private HttpClient httpClient;
// #Spy
// private HttpEntity entity;
#InjectMocks
private Connector varnishPurger = new Connector();
#Test
public void purgeFail() throws Exception{
HttpResponse response500 = new BasicHttpResponse( new ProtocolVersion( "HTTP/1.1", 0, 0), 500, "NO!_TEST" );
HttpEntity entity500 = new StringEntity("BAD entity. [test]");
response500.setEntity(entity500);
doReturn( response500 )
.when( httpClient ).execute( isA(HttpHost.class), isA(BasicHttpRequest.class) );
varnishPurger.invalidateVarnishCache("level_test_500", "id_test_500");
// verify( entity, times( 1 ) ).getContent().available(); // HOW DO I MAKE THIS WORK?
}
...
}
HttpEntity is an interface, it cannot be spied, only mocked. So just change the annotation with #Mock, or another option is to declare an initialised instance :
#Spy HttpEntity entity = new BasicHttpEntity();
Anyway the exception message is rather clear on why this happens :
org.mockito.exceptions.base.MockitoException: Unable to initialize #Spy annotated field 'entity'.
Type 'HttpEntity' is an interface and it cannot be spied on.
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.mockito.exceptions.base.MockitoException: Type 'HttpEntity' is an interface and it cannot be spied on.
... 21 more
This behaviour is aligned with Mockito.spy(Object), this method cannot be invoked if there's no instance.
However the recent Mockito.spy(Class) does not complain about that. This may be a functionality that wasn't ported to the annotation subsystem.
Nonetheless it is semantically wrong to spy on an interface as it doesn't have behaviour.
I solved in this way:
class MockHttpEntity implements HttpEntity{
String msg = "Test_";
InputStream inps;
int count = 0;
public MockHttpEntity(String msg){
this.msg += msg;
inps = IOUtils.toInputStream(this.msg);
}
#Override
public InputStream getContent(){
System.out.println("\n"+(++count)+") Mocked getContent() called.\n");
return inps;
}
public int times(){
return count;
}
#Override public void consumeContent(){ }
#Override public Header getContentEncoding(){ return null; }
#Override public long getContentLength(){ return 0; }
#Override public Header getContentType(){ return null;}
#Override public boolean isChunked(){ return false; }
#Override public boolean isRepeatable(){ return false; }
#Override public boolean isStreaming(){ return false; }
#Override public void writeTo(OutputStream outstream){ }
}
#RunWith(MockitoJUnitRunner.class)
public class ConnectorTest {
#Mock
private HttpClient httpClient;
#InjectMocks
private Connector varnishPurger = new Connector();
#Test
public void purgeFailureResponse() throws Exception{
MockHttpEntity mockedHttpEntity = new MockHttpEntity("bad entity");
HttpResponse response500 = new BasicHttpResponse( new ProtocolVersion( "HTTP/1.1", 0, 0), 500, "NO!_TEST" );
response500.setEntity( mockedHttpEntity );
doReturn( response500 )
.when( httpClient ).execute( isA(HttpHost.class), isA(BasicHttpRequest.class) );
varnishPurger.invalidateVarnishCache("level_test_no", "id_test_no");
Assert.assertTrue( mockedHttpEntity.times() == 2 );
}
...
}

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);

JAXB Object won't marshal/unmarshal List property

With the following:
#XmlRootElement(name = "purchase")
#XmlType(propOrder = {"memberId", "propertyA", "propertyB", "propertyC", "listProps"})
public class ClassA {
private Long memberId;
private Integer propertyA;
private String propertyB;
private Integer propertyC;
private List<ClassB> listProps;
public ClassA() {
}
#XmlElement(name = "memberId")
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
#XmlElement(name = "propertyA")
public Integer getPropertyA() {
return propertyA;
}
public void setPropertyA(Integer propertyA) {
this.propertyA = propertyA;
}
#XmlElement(name = "propertyB")
public String getPropertyB() {
return propertyB;
}
public void setPropertyB(String propertyB) {
this.propertyB = propertyB;
}
#XmlElement(name = "propertyC")
public Integer getPropertyC() {
return propertyC;
}
public void setPropertyC(Integer propertyC) {
this.propertyC = propertyC;
}
#XmlElement(name = "listProps")
public List<ClassB> getListProps() {
return listProps;
}
public void setListProps(List<ClassB> listProps) {
this.listProps = listProps;
}
}
#XmlRootElement(name = "listProp")
#XmlType(propOrder = {"countA", "countB"})
public class ClassB {
private int countA;
private int countB;
public ClassB() {
}
public int getCountA() {
return countA;
}
public int getCountB() {
return countB;
}
#XmlElement(name = "countA")
public void setCountA(int countA) {
this.countA = countA;
}
#XmlElement(name = "countB")
public void setCountB(int countB) {
this.countB = countB;
}
}
When I try and marshal / unmarshal objects of type ClassA, the listProps is always empty regardless of how many objects I have put in it. Can anyone tell me what I am doing wrong?
When I marshal your model classes as follows:
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ClassA.class);
List<ClassB> classBs = new ArrayList<ClassB>();
classBs.add(new ClassB());
classBs.add(new ClassB());
ClassA classA = new ClassA();
classA.setListProps(classBs);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(classA, System.out);
}
}
I get the following output, so there is no problem with your list property:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purchase>
<listProps>
<countA>0</countA>
<countB>0</countB>
</listProps>
<listProps>
<countA>0</countA>
<countB>0</countB>
</listProps>
</purchase>
As I understand your problem is to unmarshal list of values which you have marshaled. The same problem I faced with jaxb-impl lib +2.2.x when unmarshaling results into empty list while XML contains at least 1 element. Try to instantiate list if it is null in method getListProps so JAXB could populate it. I feel like the problem is in List + XmlAccessorType.PROPERTY as it does not create list by default and tries to use existing one, because it is null setListProps is called with empty collection.

EntityManger null in seam unit tests

Below is the code I am trying to test, but getting null pointer exception on entityManager.find coz entityManager = null. Any suggestions?
#Name("UserProfileConverter")
#BypassInterceptors
#Converter(forClass= UserProfile.class)
public class UserProfileConverter implements javax.faces.convert.Converter {
#Logger
private static Log logger;
public Object getAsObject(FacesContext arg0, UIComponent uiComponent, String s) {
EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");
UserProfile p;
if(s == null || s.equals("null")) {
return null;
} else {
try {
long i = Long.parseLong(s);
return entityManager.find(UserProfile.class, i);
} catch (NumberFormatException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
}
}
return null;
}
public String getAsString(FacesContext context, UIComponent uiComponetn, Object arg2) {
return ((CsaRole)arg2).getCsaRoleId() + "";
}
}
Here is my test class..
public class UserProfileConverterTest extends SeamTest {
private UserProfileConverter converter;
private FacesContext mockFacesContext;
private UIComponent mockUiComponent;
private final static Logger logger = Logger.getLogger(UserProfileConverterTest.class);
#BeforeClass
public void setup() {
converter = new UserProfileConverter();
}
#Test
public void testGetAsObject()
throws Exception {
new ComponentTest() {
#Override
protected void testComponents() throws Exception {
String value = "11111111111";
converter.getAsObject(mockFacesContext, mockUiComponent, value);
}
}.run();
}
}
public class UserProfileConverterTest extends SeamTest {
EntityManager mockEntityManager;
private UserProfileConverter converter;
UIComponent mockUiComponent = null;
MockFacesContext mockFacesContext = null;
#BeforeClass
public void setup() {
converter = new CsaUserProfileConverter();
mockEntityManager = EasyMock.createMock(EntityManager.class);
}
class BaseComponentTest extends ComponentTest {
protected void testComponents() throws Exception {
ScopeType.EVENT.getContext().set("entityManager", mockEntityManager);
}
}
#Test
public void testGetAsObject() throws Exception {
new BaseComponentTest() {
protected void testComponents() throws Exception {
super.testComponents();
UserProfile expectedResult = new UserProfile();
EasyMock.expect(mockEntityManager.find(UserProfile.class,1L)).andReturn(expectedResult);
//Replay Mock
EasyMock.replay(mockEntityManager);
Object target = converter.getAsObject(mockFacesContext,mockUiComponent,"1");
Assert.assertEquals(expectedResult, target);
//Verify the Mock
EasyMock.verify(mockEntityManager);
}
}.run();
}