I'm working on a generic collection class template, let's say List(T) where i'd like to be able to do something like php's late static binding. Might be best illustrated with some simplified sample code. This code compiles fine as is on dmd, but it needs a small change to be the way I want.
module main;
import std.stdio;
import std.string;
class List(T)
{
private T[] _list;
public void append(T t)
{
_list ~= t;
}
// this is where some help is needed...
public List select(bool delegate(T t) dg)
{
// auto should be whatever subclass of List(T) is calling this method.
auto result = new List!T();
foreach(t; _list)
{
if (dg(t)) result.append(t);
}
return result;
}
int opApply(int delegate(ref T) dg)
{
int result = 0;
for (int i = 0; i < _list.length; i++)
{
result = dg(_list[i]);
if (result)
break;
}
return result;
}
}
enum Gender
{
MALE,
FEMALE,
SECRET
}
class Person
{
private string _firstName;
private string _lastName;
private string _email;
private Gender _gender;
#property public string firstName() {return _firstName;}
#property public string lastName() {return _lastName;}
#property public string email() {return _email;}
#property public Gender gender() {return _gender;}
public this()
{
}
public this(string firstName, string lastName, Gender gender = Gender.SECRET, string email = "info#example.com")
{
this();
this._firstName = firstName;
this._lastName = lastName;
this._gender = gender;
this._email = email;
}
override public string toString()
{
if (email.length > 0)
{
return "%s %s <%s>".format(firstName, lastName, email);
}
else
{
return "%s %s".format(firstName, lastName);
}
}
}
class PeopleList : List!Person
{
// I would like to be able to make this: public PeopleList selectByGender(Gender gender)
public List!Person selectByGender(Gender gender)
{
return select(p => p.gender == gender);
}
}
void main(string[] args)
{
auto people = new PeopleList();
people.append(new Person("Kris", "Herlaar", Gender.MALE));
people.append(new Person("John", "Doe", Gender.MALE));
people.append(new Person("Steve", "Wozniak", Gender.MALE));
people.append(new Person("Walter", "Bright", Gender.MALE));
people.append(new Person("Amelia", "Earhart", Gender.FEMALE, null));
people.append(new Person("Susan", "Anthony", Gender.FEMALE, null));
foreach(p; people.selectByGender(Gender.FEMALE))
{
writeln(p);
}
}
How would I go about making sure that PeopleList.select would also return an instance of PeopleList instead of a List!Person so that the commented out declaration of selectByGender is correct?
I could probably mock about with Object.factory(this.classinfo.name) inside the implementation and actually get the correct type of instance for result but I figure that would not help with the declared return-type.
I'd want to make chaining methods possible so I'd need the compiler to allow me to return instances of whatever subclass is calling List(T).select I imagine it could be done with a nested template, but haven't been able to come up with anything that would compile, let alone seem elegant.
Additional info in reply to received feedback
I am aware of std.algorithm and of filter, In real life; this code does not represent an actual use-case but a thought experiment to learn more of the abilities/limits of D and its' templates.
This is an unfortunate use of inheritance. PersonList shouldn't exist: It is not in any way polymorhpic.
What I think you intend to do is to provide a helper method: selecting people by gender from a list.
D has something called unified function call syntax, which allows you to call free functions as if the first parameter was the actual this instance. So you could rewrite your code like this:
public List!People selectByGender(List!People list, Gender gender)
{
return list.select(p => p.gender == gender);
}
void main(string[] args)
{
auto people = new List!People();
// ...
foreach(p; people.selectByGender(Gender.FEMALE))
{
writeln(p);
}
}
I don't know if you've looked into std.algorithm yet. But it basically renders all your List(T) code redundant. You could just create an array (or any other range of Person) with your persons and then do:
foreach (p; people.filter!(p => p.gender == Gender.FEMALE))
{
writeln(p);
}
and be done with it. This style resembles (essential elements of) functional programming, pipes and filters or component programming (within the D community), whatever you like to call it. Also filter et al won't allocate a new List, but rather generate their results from the original array on the fly, or lazily, or streaming. You can force them to save the results in a new buffer by using array from std.array.
This is one of the basic cases where forcing yourself to think in Inheritance hierachies is not the most elegant way to go.
You can use Template This Parameters as described in http://dlang.org/template.html#TemplateThisParameter
Here's some example code from the page.
interface Addable(T) {
final R add(this R)(T t) {
return cast(R)this; // cast is necessary, but safe
}
}
class List(T) : Addable!T {
List remove(T t) {
return this;
}
}
void main() {
auto list = new List!int;
list.add(1).remove(1); // ok
}
And here's your code using it.
module main;
import std.stdio;
import std.string;
class List(T)
{
private T[] _list;
public void append(T t)
{
_list ~= t;
}
// select is now templatized based on the most derived class
public This select(this This)(bool delegate(T t) dg)
{
// auto should be whatever subclass of List(T) is calling this method.
auto result = new This();
foreach(t; _list)
{
if (dg(t)) result.append(t);
}
return result;
}
int opApply(int delegate(ref T) dg)
{
int result = 0;
for (int i = 0; i < _list.length; i++)
{
result = dg(_list[i]);
if (result)
break;
}
return result;
}
}
enum Gender
{
MALE,
FEMALE,
SECRET
}
class Person
{
private string _firstName;
private string _lastName;
private string _email;
private Gender _gender;
#property public string firstName() {return _firstName;}
#property public string lastName() {return _lastName;}
#property public string email() {return _email;}
#property public Gender gender() {return _gender;}
public this()
{
}
public this(string firstName, string lastName, Gender gender = Gender.SECRET, string email = "info#example.com")
{
this();
this._firstName = firstName;
this._lastName = lastName;
this._gender = gender;
this._email = email;
}
override public string toString()
{
if (email.length > 0)
{
return "%s %s <%s>".format(firstName, lastName, email);
}
else
{
return "%s %s".format(firstName, lastName);
}
}
}
class PeopleList : List!Person
{
public PeopleList selectByGender(Gender gender)
{
return this.select(p => p.gender == gender);
}
}
void main(string[] args)
{
auto people = new PeopleList();
people.append(new Person("Kris", "Herlaar", Gender.MALE));
people.append(new Person("John", "Doe", Gender.MALE));
people.append(new Person("Steve", "Wozniak", Gender.MALE));
people.append(new Person("Walter", "Bright", Gender.MALE));
people.append(new Person("Amelia", "Earhart", Gender.FEMALE, null));
people.append(new Person("Susan", "Anthony", Gender.FEMALE, null));
foreach(p; people.selectByGender(Gender.FEMALE))
{
writeln(p);
}
}
Related
I have different value objects, each with a different set of fields. How can I check against these with a Hamcrest matcher?
public class ValueObjectA {
public Integer field1;
public String field2;
public long filed3;
public Object filed4;
}
public class ValueObjectB {
public String field1;
public int field2;
}
This is, what I want to do:
resultA = getResultA();
ValueObjectA expectedA = new ValueObjectA();
expectedA.field1 = 4;
resultB = getResultB();
ValueObjectB expectedB = new ValueObjectB();
expectedB.field1 = "foo";
assertThat(resultA, new ValueObjectMatcher(expectedA));
assertThat(resultB, new ValueObjectMatcher(expectedB));
I found a PropertyMatcher but that only uses public getters. I can write something similar, that uses reflection to get the public fields. But is there a readymade one?
You can use a library we recent open sourced for doing this. It works similar to the PropertyMatcher but was designed to do deep object graphs. An upshot is that it "just works" on public fields.
shazamcrest on github
Anyway, I wrote something based on the PropertyMatcher, in case someone wants to write unit tests for eg. com.j256.ormlite :
public class ValueObjectMatcher extends TypeSafeDiagnosingMatcher {
private final Object expectedVo;
private final Set<String> fieldNames;
private final List<FieldMatcher> fieldMatchers;
public ValueObjectMatcher(final Object expectedVo) {
Field[] fieldsToMatch = expectedVo.getClass().getFields();
this.expectedVo = expectedVo;
this.fieldNames = fieldNamesFrom(fieldsToMatch);
this.fieldMatchers = fieldMatchersFor(expectedVo, fieldsToMatch);
}
#Override
protected boolean matchesSafely(final Object item, final Description mismatchDescription) {
return hasAllFields(item, mismatchDescription) && hasMatchingValues(item, mismatchDescription);
}
#Override
public void describeTo(final Description description) {
description.appendText("same field values as " + expectedVo.getClass().getSimpleName())
.appendList(" <", ", ", ">", fieldMatchers);
}
private boolean hasMatchingValues(final Object item, final Description mismatchDescription) {
mismatchDescription.appendText(item + " has <");
int mismatchCount = 0;
for (FieldMatcher fieldMatcher : fieldMatchers) {
if (!fieldMatcher.matches(item)) {
if (mismatchCount != 0) {
mismatchDescription.appendText(", ");
}
fieldMatcher.describeMismatch(item, mismatchDescription);
mismatchCount++;
}
}
mismatchDescription.appendText(">");
return mismatchCount == 0;
}
private boolean hasAllFields(final Object item, final Description mismatchDescription) {
final Field[] fields = item.getClass().getFields();
final Set<String> itemsFieldNames = fieldNamesFrom(fields);
boolean result = true;
for (String fieldName : fieldNames) {
if (!itemsFieldNames.contains(fieldName)) {
result = false;
mismatchDescription.appendText("missing field: " + fieldName);
}
}
return result;
}
private List<FieldMatcher> fieldMatchersFor(final Object expectedVo, final Field[] fields) {
List<FieldMatcher> result = new ArrayList<FieldMatcher>(fields.length);
try {
for (Field field : fields) {
result.add(new FieldMatcher(field, expectedVo));
}
}
catch (NoSuchFieldException e) {
throw new IllegalStateException("Programmer exception, pls replace programmer: " +
"field list doesn't match with the fields of the provided expectedVo", e);
}
catch (IllegalAccessException e) {
throw new IllegalStateException("Programmer exception, pls replace programmer: " +
"field list doesn't match with the fields of the provided expectedVo", e);
}
return result;
}
private Set<String> fieldNamesFrom(final Field[] fieldsToMatch) {
HashSet<String> result = new HashSet<String>();
for (Field field : fieldsToMatch) {
result.add(field.getName());
}
return result;
}
public class FieldMatcher extends DiagnosingMatcher<Object> {
private final Object expectedFieldValue;
private final String fieldName;
private FieldMatcher(Field field, Object expectedVo) throws NoSuchFieldException, IllegalAccessException {
this.fieldName = field.getName();
this.expectedFieldValue = expectedVo.getClass().getField(fieldName).get(expectedVo);
}
#Override
protected boolean matches(final Object item, final Description mismatchDescription) {
try {
final Field fieldItem = item.getClass().getField(fieldName);
final Object fieldObjectItem = fieldItem.get(item);
if (fieldObjectItem == null) {
if (expectedFieldValue != null) {
mismatchDescription.appendText(fieldName + ": " + fieldObjectItem);
}
} else if (!fieldObjectItem.equals(expectedFieldValue)) {
mismatchDescription.appendText(fieldName + ": " + fieldObjectItem);
}
}
catch (IllegalAccessException e) {
mismatchDescription.appendText(fieldName + " is inaccessible");
e.printStackTrace();
}
catch (NoSuchFieldException e) {
mismatchDescription.appendText(fieldName + " doesn't exist");
e.printStackTrace();
}
return false;
}
#Override
public void describeTo(final Description description) {
description.appendText(fieldName + ": " + expectedFieldValue);
}
}
}
I have two entities as People and Story. Now I post my story and check my stories, but returns different Story List occasionally. I mean, usr.stories.hashCode() is not same in differernt request from the exactly same user. The database table is always correct, so I am very confused. I checked out Hibernate reference for better details, but it didn't help at all.
Model class:
#MappedSuperclass
public class People{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer id;
#OrderBy(value = "id DESC")
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "people")
public List<Story> stories = new LinkedList<Story>();
public People(){
}
}
#MappedSuperclass
public class Story{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "people_id")
public People people;
#Column(name = "story", nullable = false)
public String story;
public Story(String story){
this.story = story;
}
}
REST class:
#Path("/story")
public class StoryRS {
#POST
public StreamingOutput create(final #Context HttpServletRequest req, final String story) throws IOException{
return new StreamingOutput() {
#Override
public void write(OutputStream os) {
HttpSession hs = req.getSession(false);
if (hs != null && story != null && story.trim().length() > 0) {
Integer uid = (Integer) hs.getAttribute("uid");
People usr = uid != null ? PeopleDAO.findById(uid) : null;
if (usr != null) {
Story obj = new Story(story);
EntityManagerHelper.beginTransaction();
StoryDAO.save(obj);
EntityManagerHelper.commit();
os.write(obj.id);
}
}
os.close();
}
};
}
#GET
public StreamingOutput create(final #Context HttpServletRequest req) throws IOException{
return new StreamingOutput() {
#Override
public void write(OutputStream os) {
HttpSession hs = req.getSession(false);
if (hs != null && story != null && story.trim().length() > 0) {
Integer uid = (Integer) hs.getAttribute("uid");
People usr = uid != null ? PeopleDAO.findById(uid) : null;
if (usr != null && usr.stories != null && usr.stories.size()>0) {
os.write(usr.stories...);
}
}
os.close();
}
};
}
}
PeopleDAO:
public class PeopleDAO{
#Override
public void save(People entity) {
try {
getEntityManager().persist(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("save failed", Level.SEVERE, re);
throw re;
}
}
#Override
public void delete(People entity) {
try {
entity = getEntityManager().getReference(People.class, entity.getId());
getEntityManager().remove(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("delete failed", Level.SEVERE, re);
throw re;
}
}
#Override
public People update(People entity) {
try {
People result = getEntityManager().merge(entity);
return result;
} catch (RuntimeException re) {
EntityManagerHelper.log("update failed", Level.SEVERE, re);
throw re;
}
}
#Override
public People findById(Integer id) {
try {
People instance = getEntityManager().find(People.class, id);
return instance;
} catch (RuntimeException re) {
EntityManagerHelper.log("find failed", Level.SEVERE, re);
throw re;
}
}
StoryDAO:
public class StoryDAO{
#Override
public void save(Story entity) {
try {
getEntityManager().persist(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("save failed", Level.SEVERE, re);
throw re;
}
entity.People.stories.add(0, entity);
}
#Override
public void delete(Story entity) {
try {
entity = getEntityManager().getReference(Story.class, entity.getId());
getEntityManager().remove(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("delete failed", Level.SEVERE, re);
throw re;
}
entity.People.stories.remove(entity);
}
#Override
public Story update(Story entity) {
try {
Story result = getEntityManager().merge(entity);
return result;
} catch (RuntimeException re) {
EntityManagerHelper.log("update failed", Level.SEVERE, re);
throw re;
}
}
#Override
public Story findById(Integer id) {
try {
Story instance = getEntityManager().find(Story.class, id);
return instance;
} catch (RuntimeException re) {
EntityManagerHelper.log("find failed", Level.SEVERE, re);
throw re;
}
}
EntityManagerHelper:
public class EntityManagerHelper {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
private static final Logger logger;
static {
emf = Persistence.createEntityManagerFactory("db");
threadLocal = new ThreadLocal<EntityManager>();
logger = Logger.getLogger("db");
logger.setLevel(Level.ALL);
}
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
threadLocal.set(null);
if (em != null)
em.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
Thanks a lot for any response
Here's your problem
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
EntityManager's are supposed to be short-lived objects. They're cheap to make and cheap to destroy. It also explains why you are getting inconsistent results. EntityManagers have an internal cache which is surprisingly aggressive.
The rule for working with EM's is "One EntityManager per transaction."
Change your code to get a new EM every time and your problems will go away.
I am trying to put a listfield in the pop up screen. The list is coming properly. But when i am clicking a particular row of the list, it is not firing any event. itried with showing a dialog. but it is also not working. Here is my code:
public class AttachmentListPopup extends PopupScreen implements FieldChangeListener{
private ListField _listField;
private Vector _listElements;
public AttachmentListPopup()
{
super(new VerticalFieldManager());
_listElements = new Vector();
_listField = new ListField();
ListCallback _callback = new ListCallback()
{
public boolean navigationClick(int status, int time)
{
int index = _listField.getSelectedIndex();
if(index == 0)
{
Dialog.alert("Grocery Clicked");
}
else if(index == 1)
{
Dialog.alert("To Do's Clicked");
}
return true;
}
};
_listField.setCallback(_callback);
initializeList();
add(_listField);
}
private void initializeList()
{
String itemOne = "Grocery";
String itemTwo = "To Do's";
_listElements.addElement(itemOne);
_listElements.addElement(itemTwo);
_listField.setSize(_listElements.size());
_listField.setRowHeight(Display.getHeight()/6);
}
private class ListCallback implements ListFieldCallback
{
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
y = y +20;
String text = (String)_listElements.elementAt(index);
g.drawText(text, (Display.getWidth() - getFont().getAdvance(text))/2, y, 0 , w);
}
public Object get(ListField list, int index)
{
return _listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return _listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}
It will be great help if you find out the issue..
Thanks.
Have a look at this, this is a good example of ListField implementation, since I am on Mac, I can't run your code. Hope it might help you.
Finally i am able to fix the issue. I am writing the navigation click for the list view. And now it is working properly..
Here is my updated code:
public class AttachmentListPopup extends PopupScreen implements FieldChangeListener{
private ListField _listField;
private Vector _listElements;
public AttachmentListPopup()
{
super(new VerticalFieldManager());
_listElements = new Vector();
_listField = new ListField();
ListCallback _callback = new ListCallback();
_listField.setCallback(_callback);
initializeList();
add(_listField);
}
protected boolean navigationClick(int arg0, int arg1) {
// TODO Auto-generated method stub
int index = _listField.getSelectedIndex();
if(index == 0)
{
UiApplication.getUiApplication().popScreen(this);
Logger.out("AttachmnentList", "first row clicked");
Dialog.alert("Grocery Clicked");
}
else if(index == 1)
{
Dialog.alert("To Do's Clicked");
}
return super.navigationClick(arg0, arg1);
}
private void initializeList()
{
String itemOne = "Grocery";
String itemTwo = "To Do's";
_listElements.addElement(itemOne);
_listElements.addElement(itemTwo);
_listField.setSize(_listElements.size());
_listField.setRowHeight(Display.getHeight()/6);
}
private class ListCallback implements ListFieldCallback
{
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
y = y +20;
String text = (String)_listElements.elementAt(index);
g.drawText(text, (Display.getWidth() - getFont().getAdvance(text))/2, y, 0 , w);
}
public Object get(ListField list, int index)
{
return _listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return _listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}
I am usling IList List property to get a list of students class in University class .. as i try to access this list in department Class which is a part of university class .. the List is Null .. can anyone tell the reason?
namespace UniversitySystem
{
class University : CollectionBase
{
private string _uniName;
Departments _depart = new Departments();
public University(string un, string dn, string cp, List<Student> Slist)
{
this._uniName = un;
this.CED.DepartName = dn;
this.CED.ChairPerson = cp;
foreach (Student s in Slist)
{
List.Add(s);
}
}
#region properties
public string UniName
{
get { return _uniName; }
set { _uniName = value; }
}
public Departments CED
{
get { return _depart; }
set { _depart = value; }
}
#endregion
public class Departments : CollectionBase
{
private string _departName;
public string DepartName
{
get { return _departName; }
set { _departName = value; }
}
private string _chairPerson;
public string ChairPerson
{
get { return _chairPerson; }
set { _chairPerson = value; }
}
public List<Student> StudentListForCED = new List<Student>();
public Departments()
{
_departName = null;
_chairPerson = null;
StudentListForCED = null;
}
public Departments(string dn, string cp, List<Student> Slist)
{
this._departName = dn;
this._chairPerson = cp;
foreach (Student s in Slist)
{
List.Add(s);
}
}
public void showDetails()
{
Console.WriteLine("Departmental Info");
Console.WriteLine("DepartmentName: " + _departName);
Console.WriteLine("Chairperson Name: " + _chairPerson);
Console.WriteLine("Student Info:");
foreach (Student item in List)
{
Console.WriteLine("Name: " + item.Name);
Console.WriteLine("deptName: " + item.RegNo);
Console.WriteLine("total marks: " + item.TotalMarksObtained);
Console.WriteLine("percentage: " + item.GetPercentage());
}
}
}
}
}
THE main() part is
namespace UniversitySystem
{
class Program
{
static void Main(string[] args)
{
List<Student> slist = new List<Student>();
slist.Add(new Student("sana", 1234, "CIS", 650));
slist.Add(new Student("anam", 2345, "BCIT", 400));
slist.Add(new Student("fizzza", 2670, "Electrical", 670));
University u1 = new University("NED", "computer", "UKP", slist);
Console.WriteLine(u1.CED.DepartName);
u1.CED.showDetails();
}
}
}
The initializing code for University does not store the list you give it as a parameter.
try storing the list in a variable in either the department or the university object itself, and when you are showing the details for either of those object you can reference that list, the one you stored upon creating the object.
Hope that helps!
I made a couple changes that should work.
public Departments(string dn, string cp, List<Student> Slist)
{
this._departName = dn;
this._chairPerson = cp;
foreach (Student s in Slist)
{
StudentListForCED.Add(s);
}
}
public void showDetails()
{
Console.WriteLine("Departmental Info");
Console.WriteLine("DepartmentName: " + _departName);
Console.WriteLine("Chairperson Name: " + _chairPerson);
Console.WriteLine("Student Info:");
foreach (Student item in StudentListForCED)
{
Console.WriteLine("Name: " + item.Name);
Console.WriteLine("deptName: " + item.RegNo);
Console.WriteLine("total marks: " + item.TotalMarksObtained);
Console.WriteLine("percentage: " + item.GetPercentage());
}
}
Please read this a little more thoroughly.
I have a Person class with get set for FirstName, LastName
A TestClass to execute TestCase1
Can we just only mock a specific method (getLastName) and leave every thing else (other internal fields, functions ... as-is)?
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
import static org.powermock.api.easymock.PowerMock.*;
import static org.easymock.EasyMock.expect;
#RunWith(PowerMockRunner.class)
#PrepareForTest ( {Person.class} )
public class TestClass {
#Test
public void TestCase1() {
Person person = createNiceMock(Person.class);
person.setFirstName = "First name";
expect(person.getLastName()).andReturn("Fixed value").anyTimes();
replayAll();
String ln = person.getLastName(); //will return "Fixed value";
String fn = person.getFirstName();
// Currently it returns null because of createNiceMock
// but I want it to return "First name" (value has been set to mock object)
// Is it possible?
verifyAll();
}
}
You can use spy to mock individual (including private) methods:
Person classUnderTest = PowerMockito.spy(new Person());
// use PowerMockito to set up your expectation
PowerMockito.doReturn("Fixed value").when(classUnderTest, "getLastName");