Setting global properties for RTC Jazz Build definition - build

I have several Build Definitions in RTC/Jazz and i use a variable to set out DB-Release in various Build Definitions
Build-Lib
Build-Server-App
Build-Run-Test-Server
Build-Client-App
Build-Run-Test-Client
and in all Definitions i use the Property DB_SCHEMA,
DB_SCHEMA = 8.1
once we update our DB and use a new Schema i have to set the Build Property up to
DB_SCHEMA = 8.2
now i must update all Build-Definitions... and if i forget one or i misspell something, then my boss gets mad at me - joking, but honestly, i don't want to make mistakes
--> how can i define a global Property that can be used in all Build-Definitions?

I don't see any global property in the help page, so you might consider developing a program:
using the RTC Java API
for each build definition, setting the property to the expected value (as in this thread)
IBuildDefinition definition = (IBuildDefinition) buildDefinition.getWorkingCopy();
definition.setProperty("propertyName","");
definition = buildClient.save(definition, monitor);

Ok VonC here is my solution:
one Part is an RTC-Adapter which handles Connections from and to the RTC base:
(it provides further getter/setters wich are not relevant for this solution - i purged them)
RTC-Adapter
public class RtcAdapter {
//yes i know - having hardcoded user/pass is bad, ignore this - image it's in a property file or set by a popup dialog
private static final String repositoryURI = "https://xxxxxxxxxxxx/ccm";
private static final String userId = "xxxxxxxxxxx";
private static final String password = "xxxxxxxxxx";
private static final String projectAreaName = "xxxxxxxxxx";
private ITeamRepository teamRepository = null;
private IProgressMonitor monitor = new NullProgressMonitor();
private IProjectArea projectArea = null;
private ITeamBuildClient buildClient = null;
//i'm implementing a singleton class - you can argue with mie if it's a good approach
private static final RtcAdapter inst = new RtcAdapter();
private RtcAdapter(){
super();
}
public ITeamRepository getTeamRepository() {
return teamRepository;
}
public IProgressMonitor getMonitor() {
return monitor;
}
public IProjectArea getProjctArea(){
return projectArea;
}
public ITeamBuildClient getBuildClient(){
return buildClient;
}
private void setTeamRepository(ITeamRepository teamRepositoryIn) {
teamRepository = teamRepositoryIn;
}
/**
*
* #param repositoryURI
* #param userId
* #param password
* #param monitor
* #return
* #throws TeamRepositoryException
*/
private ITeamRepository login(String repositoryURI, String userId,String password, IProgressMonitor monitor) throws TeamRepositoryException {
ITeamRepository teamRepository = TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(monitor);
return teamRepository;
}
/**
* LoginHandler required by login function
*
*/
private static class LoginHandler implements ILoginHandler, ILoginInfo {
private String fUserId;
private String fPassword;
private LoginHandler(String userId, String password) {
fUserId = userId;
fPassword = password;
}
public String getUserId() {
return fUserId;
}
public String getPassword() {
return fPassword;
}
public ILoginInfo challenge(ITeamRepository repository) {
return this;
}
}
public static RtcAdapter inst() {
return inst;
}
public boolean connect() {
TeamPlatform.startup();
System.out.println("Team Platform Startup");
try {
IProgressMonitor monitor = new NullProgressMonitor();
setTeamRepository(login(repositoryURI, userId, password, monitor));
System.out.println("Logged in");
IProcessClientService processClient= (IProcessClientService) getTeamRepository().getClientLibrary(IProcessClientService.class);
URI uri= URI.create(projectAreaName.replaceAll(" ", "%20"));
projectArea = (IProjectArea) processClient.findProcessArea(uri, null, RtcAdapter.inst().getMonitor() );
buildClient = (ITeamBuildClient) getTeamRepository().getClientLibrary(ITeamBuildClient.class);
System.out.println("projet area = "+projectArea.getName() );
} catch (TeamRepositoryException e) {
System.out.println("TeamRepositoryException : " + e.getMessage());
e.printStackTrace();
return false;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
public void disconnect(){
System.out.println("Logged out");
TeamPlatform.shutdown();
}
}
the other part is the working Class, i called it BuildDefinitionHelper (what a great name, haha)
BuildDefinitionHelper
public class BuildDefinitionHelper {
/**
* #param args
*/
public static void main(String[] args) {
new BuildDefinitionHelper().startUp(); //not-so-nice startup, but i don't mind
}
private final String[] adaPublishDefinitionList = new String[]{
"publish ada develop-40",
"publish ada develop-40 nightly",
"publish ada develop-54",
"publish ada develop-54 nightly",
"publish ada develop-56",
"publish ada develop-56 nightly",
"publish ada develop-58",
"publish ada develop-58 nightly",
};
private final String BUILD_NR = "BUILD_NR";
private final String MAJOR = "MAJOR";
private final String MINOR = "MINOR";
private void startUp() {
final int major = 57;
final int minor = 11;
final int build = 1;
//connect
if (RtcAdapter.inst().connect() ){
//getting required resources - a singleton is helpful here (look above)
IProgressMonitor pMon = RtcAdapter.inst().getMonitor();
ITeamBuildClient buildClient = RtcAdapter.inst().getBuildClient();
try {
for (String adaPublish: adaPublishDefinitionList ){
//get build definition
IBuildDefinition workingCopy = getBuildDefinition(adaPublish, buildClient, pMon);
//seting properties
String propMajor = getFormattededInteger(major);
String propMinor = getFormattededInteger(minor);
String propBuild = getFormattededInteger(build);
setBuildProperty(MAJOR, propMajor, workingCopy);
setBuildProperty(MINOR, propMinor, workingCopy);
setBuildProperty(BUILD_NR, propBuild, workingCopy);
//store changes
saveBuildDefinition(workingCopy, buildClient, pMon);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (TeamRepositoryException e) {
e.printStackTrace();
}
//at the end: disconnect
RtcAdapter.inst().disconnect();
}
}
private void saveBuildDefinition(IBuildDefinition definition, ITeamBuildClient buildClient, IProgressMonitor progressMonitor) throws TeamBuildDuplicateItemException, IllegalArgumentException, TeamRepositoryException {
buildClient.save(definition, progressMonitor);
}
private String getFormattededInteger(int value) {
if (value >= 0 && value <= 9){
return "00"+value;
}
if (value >= 10 && value <= 99){
return "0"+value;
}
return ""+value;
}
private IBuildDefinition getBuildDefinition(String buildDefinitionName, ITeamBuildClient buildClient, IProgressMonitor progressMonitor) throws IllegalArgumentException, TeamRepositoryException {
IBuildDefinition buildDefinition = buildClient.getBuildDefinition(buildDefinitionName, progressMonitor );
IBuildDefinition definition = (IBuildDefinition) buildDefinition.getWorkingCopy();
return definition;
}
private void setBuildProperty(String propertyName, String propertyValue, IBuildDefinition definition ) throws TeamBuildDuplicateItemException, IllegalArgumentException, TeamRepositoryException {
definition.setProperty(propertyName,propertyValue);
System.out.println("set "+propertyName+" to "+ propertyValue+" in Build Definition "+definition.getId() );
}
private void printBuildDefinition(String[] buildDefinitionList, ITeamBuildClient buildClient, IProgressMonitor progressMonitor) throws IllegalArgumentException, TeamRepositoryException {
for (String buildDefinitionName: buildDefinitionList ){
IBuildDefinition buildDefinition = buildClient.getBuildDefinition(buildDefinitionName, progressMonitor );
IBuildDefinition definition = (IBuildDefinition) buildDefinition.getWorkingCopy();
System.out.println("name = "+buildDefinitionName+" definition = "+definition);
}
}
}

Related

Camunda does not contain any history

I have a problem that whenever I create a process instance in Camunda Process Service, it does not write anything to ACT_HI_OP_LOG. I am not sure why it is not saving the histories into database.
#Component
#Order(Ordering.DEFAULT_ORDER + 1)
public class ProcessEngineConfiguration implements ProcessEnginePlugin {
private String tenantId;
#Override
public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
HistoryLevel historyLevel = new HistoryLevelFull();
processEngineConfiguration.setHistoryLevel(historyLevel);
processEngineConfiguration.setTenantCheckEnabled(true);
// processEngineConfiguration.setHistory(org.camunda.bpm.engine.ProcessEngineConfiguration.HISTORY_FULL);
processEngineConfiguration.setTenantIdProvider(new TenantIdProvider() {
#Override
public String provideTenantIdForProcessInstance(TenantIdProviderProcessInstanceContext ctx) {
return tenantId;
}
#Override
public String provideTenantIdForHistoricDecisionInstance(TenantIdProviderHistoricDecisionInstanceContext ctx) {
return tenantId;
}
#Override
public String provideTenantIdForCaseInstance(TenantIdProviderCaseInstanceContext ctx) {
return tenantId;
}
});
processEngineConfiguration.setJobExecutor(processEngineConfiguration.getJobExecutor());
}
This is how I start the process.
ProcessInstance pi = null;
try {
identityService.setAuthentication(getAuthentication());
pi = runtimeService.startProcessInstanceByKey(flowName, businessKey, variables);
} finally {
identityService.setAuthentication(null);
}
if (pi == null)
return null;
Did you check configuration?
historyLevelCheckEnabled default value is true.
Can you try to set that value false.
If you set that false, this check would not be performed.

How to use #UsingDataSet in Arquillian test

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

When trying to use Mockito to unit test sending email, I create a multipartemail object in the function, but the test fails, why?

This is my unit testing code.
public class StatsTest extends AbstractTestCase {
#Mock
//EmailInfo mockMetricsEmail = Mockito.mock(EmailInfo.class);
//EmailSenderImpl mockEmailSenderImpl = Mockito.mock(EmailSenderImpl.class);
private MultiPartEmail mockMultiPartEmail = Mockito.mock(HtmlEmail.class);
private static final String testEmailBody = "This is the test email body.";
private static final String testSender = "seemakur#amazon.com";
private static final String testRecipient = ("seemakur#amazon.com");
private static final String testEmailSubject = "subject";
private static final String testHostName = "seemakur.desktop.amazon.com";
private static final MultiPartEmail testHtmlEmail = new HtmlEmail();
EmailSenderImpl emailSenderImplObj = new EmailSenderImpl();
EmailInfo emailInfoObj = new EmailInfo(testEmailBody, testSender, testRecipient, testEmailSubject, testHostName, testHtmlEmail);
#Before
public void setUp() throws Throwable {
super.setUp();
MockitoAnnotations.initMocks(this); // will instantiate "mockMultiPartEmail"
// instantiate our class under test
}
#Test(expected = EmailException.class)
public void testSendEmail() throws EmailException, IOException {
MultiPartEmail testMultiPartEmail = Mockito.spy(new HtmlEmail());
Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail(); //stub(spy.getMultiPartEmail()).toReturn(mockMultiPartEmail);
Mockito.when(mockMultiPartEmail.send()).thenThrow(new EmailException("Failed on multipartEmail.send(), hence could not send the email."));
// when the method under test is called
try {
//testEmailSenderImplObj.sendHtmlTableAsEmail(testMetricsEmail);
emailSenderImplObj.sendHtmlTableAsEmail(emailInfoObj); //inject mock & invoke what to test
fail("Expecting EmailException");
}catch(EmailException e){
e.printStackTrace();
}
Mockito.verify(mockMultiPartEmail).send();Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail(); //stub(spy.getMultiPartEmail()).toReturn(mockMultiPartEmail);
}
}
i have three classes associated with this email function:
firstly below is emailInfo data object
#Data
public class EmailInfo {
private String emailBody;
private String senderEmail;
private String receiversEmails;
private String emailSubject;
private String hostName;
private MultiPartEmail multiPartEmail;
public EmailInfo(String emailBody, String senderEmail, String receiversEmails, String emailSubject, String hostName, MultiPartEmail multiPartEmail) {
this.setEmailBody(emailBody);
this.setSenderEmail(senderEmail);
this.setReceiversEmails(receiversEmails);
this.setEmailSubject(emailSubject);
this.setHostName(hostName);
this.setMultiPartEmail(multiPartEmail);
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getEmailBody() {
return emailBody;
}
public void setEmailBody(String emailBody) {
this.emailBody = emailBody;
}
public String getReceiversEmails() {
return receiversEmails;
}
public void setReceiversEmails(String receiversEmails2) {
this.receiversEmails = receiversEmails2;
}
public String getEmailSubject() {
return emailSubject;
}
public void setEmailSubject(String emailSubject) {
this.emailSubject = emailSubject;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public MultiPartEmail getMultiPartEmail() {
return multiPartEmail;
}
public void setMultiPartEmail(MultiPartEmail multiPartEmail) {
this.multiPartEmail = multiPartEmail;
}
}
second class: EmailSenderImpl.java
public class EmailSenderImpl implements EmailSender{
// public MultiPartEmail getEmail(){
// return multiPartEmail;
// }
//
// public void setEmail(MultiPartEmail multiPartEmail){
// this.multiPartEmail = multiPartEmail;
// }
public void sendHtmlTableAsEmail(EmailInfo emailInfo)throws IOException, EmailException{
MultiPartEmail multiPartEmail = new HtmlEmail();
multiPartEmail.setHostName(emailInfo.getHostName());
multiPartEmail.addTo(emailInfo.getReceiversEmails());
multiPartEmail.setFrom(emailInfo.getSenderEmail());
multiPartEmail.setSubject(emailInfo.getEmailSubject());
multiPartEmail.setMsg((emailInfo.getEmailBody()).toString());
multiPartEmail.send();
}
}
lastly the EMailSender.java interface.
public interface EmailSender{
public abstract void sendHtmlTableAsEmail(EmailInfo emailInfo)throws IOException, EmailException;
}
I reason I have so many classes for one simple function is because i cannot use static methods, and i have to separate "business logic" from "function logic." And I need to have interfaces, that is necessary. If there is a better way to organize this, please let me know.
Now when I run the unit test, it fails on the line: "Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail(); //stub(spy.getMultiPartEmail()).toReturn(mockMultiPartEmail);
");"
the error reads: org.mockito.exceptions.misusing.NotAMockException
In your original code, your problem is that on this line
Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail();
you are trying to stub the behaviour of the created with this line
EmailInfo emailInfoObj = new EmailInfo(testEmailBody, testSender, testRecipient, testEmailSubject, testHostName, testHtmlEmail);
But this is not a mock or a spy. Mockito only lets you stub the behaviour of mocks and spies, not just arbitrary objects.
I can't tell whether you still have this issue after subsequent updates, as it's impossible to read code that's embedded in comments.

Is it possible to unit test BundleConfig in MVC4?

As far as I can tell, the answer is no. The issue I'm seeing comes from the Include(params string[]) method in the System.Web.Optimization.Bundle class. Internally this invokes System.Web.Optimization.IncludeDirectory(string, string, bool), which in turn uses this code:
DirectoryInfo directoryInfo = new DirectoryInfo(
HttpContext.Current.Server.MapPath(directoryVirtualPath));
While it is possible to set HttpContext.Current during a unit test, I can't figure out how to make its .Server.MapPath(string directoryVirtualPath) return a non-null string. Since the DirectoryInfo(string) constructor throws an exception when passed a null argument, such a test will always fail.
What is the .NET team's recommendation for this? Do we have to unit test bundling configurations as part of integration tests or user acceptance tests?
I have some good news for you, for RTM we added a new static property on BundleTable to enable more unit tests:
public static Func<string, string> MapPathMethod;
Edit Updated with a test virtual path provider:
So you can do something like this:
public class TestVirtualPathProvider : VirtualPathProvider {
private string NormalizeVirtualPath(string virtualPath, bool isDirectory = false) {
if (!virtualPath.StartsWith("~")) {
virtualPath = "~" + virtualPath;
}
virtualPath = virtualPath.Replace('\\', '/');
// Normalize directories to always have an ending "/"
if (isDirectory && !virtualPath.EndsWith("/")) {
return virtualPath + "/";
}
return virtualPath;
}
// Files on disk (virtualPath -> file)
private Dictionary<string, VirtualFile> _fileMap = new Dictionary<string, VirtualFile>();
private Dictionary<string, VirtualFile> FileMap {
get { return _fileMap; }
}
public void AddFile(VirtualFile file) {
FileMap[NormalizeVirtualPath(file.VirtualPath)] = file;
}
private Dictionary<string, VirtualDirectory> _directoryMap = new Dictionary<string, VirtualDirectory>();
private Dictionary<string, VirtualDirectory> DirectoryMap {
get { return _directoryMap; }
}
public void AddDirectory(VirtualDirectory dir) {
DirectoryMap[NormalizeVirtualPath(dir.VirtualPath, isDirectory: true)] = dir;
}
public override bool FileExists(string virtualPath) {
return FileMap.ContainsKey(NormalizeVirtualPath(virtualPath));
}
public override bool DirectoryExists(string virtualDir) {
return DirectoryMap.ContainsKey(NormalizeVirtualPath(virtualDir, isDirectory: true));
}
public override VirtualFile GetFile(string virtualPath) {
return FileMap[NormalizeVirtualPath(virtualPath)];
}
public override VirtualDirectory GetDirectory(string virtualDir) {
return DirectoryMap[NormalizeVirtualPath(virtualDir, isDirectory: true)];
}
internal class TestVirtualFile : VirtualFile {
public TestVirtualFile(string virtualPath, string contents)
: base(virtualPath) {
Contents = contents;
}
public string Contents { get; set; }
public override Stream Open() {
return new MemoryStream(UTF8Encoding.Default.GetBytes(Contents));
}
}
internal class TestVirtualDirectory : VirtualDirectory {
public TestVirtualDirectory(string virtualPath)
: base(virtualPath) {
}
public List<VirtualFile> _directoryFiles = new List<VirtualFile>();
public List<VirtualFile> DirectoryFiles {
get {
return _directoryFiles;
}
}
public List<VirtualDirectory> _subDirs = new List<VirtualDirectory>();
public List<VirtualDirectory> SubDirectories {
get {
return _subDirs;
}
}
public override IEnumerable Files {
get {
return DirectoryFiles;
}
}
public override IEnumerable Children {
get { throw new NotImplementedException(); }
}
public override IEnumerable Directories {
get {
return SubDirectories;
}
}
}
And then write a unit test using that like so:
[TestMethod]
public void StyleBundleCustomVPPIncludeVersionSelectsTest() {
//Setup the vpp to contain the files/directories
TestVirtualPathProvider vpp = new TestVirtualPathProvider();
var directory = new TestVirtualPathProvider.TestVirtualDirectory("/dir/");
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style1.0.css", "correct"));
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style.css", "wrong"));
vpp.AddDirectory(directory);
// Setup the bundle
ScriptBundle bundle = new ScriptBundle("~/bundles/test");
bundle.Items.VirtualPathProvider = vpp;
bundle.Include("~/dir/style{version}.css");
// Verify the bundle repsonse
BundleContext context = SetupContext(bundle, vpp);
BundleResponse response = bundle.GetBundleResponse(context);
Assert.AreEqual(#"correct", response.Content);
}
In .Net 4.5 things have slightly changed. Here is a working version of the approved answer updated to accommodate these changes (I am using Autofac). Note the "GenerateBundleResponse" instead of "GetBundleResponse":
[Fact]
public void StyleBundleIncludesVersion()
{
//Setup the vpp to contain the files/directories
var vpp = new TestVirtualPathProvider();
var directory = new TestVirtualPathProvider.TestVirtualDirectory("/dir/");
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style1.0.css", "correct"));
directory.DirectoryFiles.Add(new TestVirtualPathProvider.TestVirtualFile("/dir/style.css", "wrong"));
vpp.AddDirectory(directory);
// Setup the bundle
var bundleCollection = new BundleCollection();
var bundle = new ScriptBundle("~/bundles/test");
BundleTable.VirtualPathProvider = vpp;
bundle.Include("~/dir/style{version}.css");
bundleCollection.Add(bundle);
var mockHttpContext = new Mock<HttpContextBase>();
// Verify the bundle repsonse
var context = new BundleContext(mockHttpContext.Object, bundleCollection, vpp.ToString());
var response = bundle.GenerateBundleResponse(context);
Assert.Equal(#"correct", response.Content);
}

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