How to parcel cascading classes with Parceler? - parceler

I can parcel some models using Parceler like this:
#Parcel(Serialization.BEAN)
public class PasswordSetModel {
private String mPassword;
private String mRepetition;
/* Getter & Setter */
...
But if this class is part of another class, the mechanism does not work. I am getting an NPE for mPasswordSetModel. Creating an instance in an constructor did not work, because the members mPassword and mRepetition were null after unparcelling.
#Parcel
public class RegistrationModel {
private PasswordSetModel mPasswordSetModel;
/* Getter & Setter */
...
So how can I parcel this using Parceler?

okay, the problem was that I uses "wrong" setter methods. In order to use fluent interface style I made it this way:
public String getPassword() {
return mPassword;
}
public PasswordSetModel setPassword(String password) {
mPassword = password;
return this;
}
public String getRepetition() {
return mRepetition;
}
public PasswordSetModel setRepetition(String repetition) {
mRepetition = repetition;
return this;
}
It seems that the setters were now found and therefor the model was NULL

Related

Mockito test when(repository.findById()).thenReturn(object with custom attributes)

So I was writing a couple of unit tests, some of them were made for testing missing attributes of Document. When using of when(repository.findOne(id)).thenReturn(DOCUMENT_WITHOUT_SOMETHING), those DOCUMENT_WITHOUT_SOMETHING were final objects with predefined attributes, depending on test cases.
Let's say, there could be a document without name, so when loading document by id the method was returning null with some log message. So I created a class of test data DocumentServiceTestData, where those necessary objects and attributes were declared. Is it a good approach or you suggest something more clear, without need of making new class?
I will try to write a simplified code of what I did.
Document
public class Document {
private String name;
private String applicant;
private String sign;
private boolean signed;
public boolean isSigned() {return signed;}
public String getApplicant() {return applicant;}
public String getName() {return name;}
public String getSign() {return sign;}
public void setSigned(boolean signed) {this.signed = signed;}
public void setApplicant(String applicant) {this.applicant = applicant;}
public void setName(String name) {this.name = name;}
public void setSign(String sign) {this.sign = sign;}
}
DocumentService
#Service
public class DocumentService {
private static final Logger LOG = LoggerFactory.getLogger(DocumentService.class);
private DocumentRepository documentRepository;
public Document loadDocument(Long docId) {
Document document = documentRepository.findByIdOrFail(docId);
if(document.getName() == null) {
LOG.info("There is no name for document, returning null");
return null;
}
if(document.getSign() == null) {
LOG.info("The document is not signed, returning null");
return null;
}
return document;
}
}
DocumentServiceTestData
public class DocumentServiceTestData {
public static final Long DOC_ID = 1L;
public static final String APPLICANT = "Applicant";
public static final String DOC_NAME = "Document";
public static final String SIGN = "Sign";
public static final Document DOCUMENT_WITHOUT_NAME;
public static final Document DOCUMENT_WITHOUT_SIGN;
static {
DOCUMENT_WITHOUT_NAME = makeDocument(null, APPLICANT, SIGN, true);
DOCUMENT_WITHOUT_SIGN = makeDocument(DOC_NAME, APPLICANT, null, false);
}
private static Document makeDocument(String name, String applicant, String sign, boolean signed) {
Document document = new Document();
document.setName(name);
document.setApplicant(applicant);
document.setSign(sign);
document.setSigned(signed);
return document;
}
}
DocumentServiceTest
#RunWith(MockitoJUnitRunner.class)
#Category(MockTest.class)
public class DocumentServiceUnitTest {
#InjectMocks
private DocumentService service;
#Mock
private DocumentRepository documentRepository;
#Test
public void testLoadDocument_notSigned(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_SIGN);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
#Test
public void testLoadDocument_notNamed(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_NAME);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
}
To sum up, I would like to know - if there is another way to test those cases, when I need to return specified objects while calling repository.findById(id).
PS: keep in mind that this is very simplified, those tests I've made were much more complex. If there is any information missing please let me know, I will try to clarify things. Thanks

PowerMock calls real method

I am trying to spy private method with PowerMock but on the line when I define the what should be returned when the private method is called, it calls the method and I am getting and Null Pointer Exception. What PowerMock is calling real method on this line ?
myService= PowerMockito.spy(new MyService(myParam));
.....
PowerMockito.when(myService, "getCLientBy", anyString(), anyString(), anyString()).thenRetur`n(Client.of(setName, new HashSet<>())); // here it calls real method
Ensure that you prepare your class to be used in spy by adding #PrepareForTest(MyService.class)
#RunWith(PowerMockRunner.class)
// We prepare MyService for test because it's final
// or we need to mock private or static methods
#PrepareForTest(MyService.class)
public class YourTestCase {
//...
#Test
public void spyingWithPowerMock() {
MyService classUnderTest = PowerMockito.spy(new MyService(myParam));
//.....
// use PowerMockito to set up your expectation
PowerMockito.doReturn(Client.of(setName, new HashSet<>()))
.when(classUnderTest, "getClientBy", anyString(), anyString(), anyString());
//...
Also make sure provide the correct method name to be invoked.
#user1474111 and #Nkosi
I've built a small simulation of your example.
Maybe you also need to add the Client class in the PrepareForTest annotation.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ MyService.class, Client.class })
public class Example1Test {
#Test
public void testPowerMockito() throws Exception {
MyService myService = PowerMockito.spy(new MyService("myParam"));
PowerMockito.when(myService, "getClientBy", ArgumentMatchers.anyString(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString()).thenReturn(Client.of("setName", new HashSet<String>()));
myService.run();
Assert.assertEquals("setName", myService.getClient().getName());
}
}
public class MyService {
private Client client;
public MyService(String param) { }
private Client getClientBy(String a, String b, String c) {
return new Client(a + b + c);
}
public Client getClient() {
return this.client;
}
public void setClient(Client client) {
this.client = client;
}
public void run() {
setClient(getClientBy("A", "B", "C"));
}
}
public class Client {
private final String name;
public Client(String name) {
this.name = name;
}
public static Client of(String name, HashSet<String> hashSet) {
return new Client(name);
}
public String getName() {
return name;
}
}

Mock object is not being returned

There is a Adapter class which calls another legacyService and legacyService calls legacyDao and I want to mock the Legacy service calls.
In the below code SomeBean is returned as null instead of one the one that i created and passed in thenReturn. What could be the issue here?Please help I am new to mocking framework.
public class AdapterImpl implements Adpater{
//Injected through setter or constructor injection
private LegacyService legacy;
public SomeBean myMethod(){
CommonUtils.someStaticMethod()
return legacy.legacyService();
}
}
public class LegacyServiceImpl implements LegacyService{
//Injected through setter or constructor injection
private LegacyDAO ldao;//LegacyDAO is an interface
public SomeBean legacyService(){
return ldao.legacyDAO();
}
}
Test class
#RunWith(PowerMockRunner.class)
#PrepareForTest({CommonUtils.class})
public class AdapterImplTest{
#Mock private LegacyServiceImpl legacyService;
private LegacyDAO legacyDAO;
#Before
public void before(){
MockitoAnnotations.initMocks(this);
}
#Test
public void myMethodTest(){
PowerMockito.mockStatic(CommonUtils.class);
PowerMockito.when(CommonUtils.someStaticMethod()).thenReturn(someString());
legacyDAO = PowerMockito.mock(LegacyDAO.class);
SomeBean bean = new SomeBean(sometring1,somestring2);
PowerMockito.when(legacyDAO.legacyDAO().thenReturn(bean);//I am mocking interface method implementation
legacyService.setLegacyDAO(legacyDAO);
PowerMockito.when(legacyService.legacyService().thenReturn(bean);//same bean as above
AdapterImpl impl = new AdapterImpl();
impl.setLegacyService(legacyService)
//Below method call is not returning the bean that I constructed above it is being returned as null
impl.myMethod();
}
}
The original code posted in the question has many typos like missing parentheses and semi-colons. When I correct them, and fill in some of the methods like AdapterImpl.setLegacyService(), the test passes.
Then, as suggested in my comment, I removed the mocking of LegacyDAO. That mock object should not be needed if LegacyServiceImpl.legacyService() is properly mocked. When I rerun the test, it again passes.
All of which leads me to believe that there is an issue with the injection of the mock LegacyService object into AdapterImpl
FYI here is my passing test code, showing my typo fixes and assumptions about methods not shown in the original question. Hope this helps!
#RunWith(PowerMockRunner.class)
#PrepareForTest({ AdapterImplTest.CommonUtils.class })
public class AdapterImplTest {
#Mock
private LegacyServiceImpl legacyService;
// private LegacyDAO legacyDAO; // removed, no need to mock
#Before
public void before() {
MockitoAnnotations.initMocks(this);
}
#Test
public void myMethodTest() {
PowerMockito.mockStatic(CommonUtils.class);
PowerMockito.when(CommonUtils.someStaticMethod()).thenReturn(someString());
// legacyDAO = PowerMockito.mock(LegacyDAO.class);
SomeBean bean = new SomeBean("sometring1", "somestring2");
// I am mocking interface method implementation
// PowerMockito.when(legacyDAO.legacyDAO()).thenReturn(bean);
// legacyService.setLegacyDAO(legacyDAO);
// same bean as above
PowerMockito.when(legacyService.legacyService()).thenReturn(bean);
AdapterImpl impl = new AdapterImpl();
impl.setLegacyService(legacyService);
// Below method call is not returning the bean that I constructed above
// it is being returned as null
impl.myMethod();
}
private String someString() {
return "hello";
}
public class SomeBean {
public SomeBean(String string, String string2) {
}
}
public interface LegacyService {
public SomeBean legacyService();
}
public interface Adpater {
}
public class AdapterImpl implements Adpater {
// Injected through setter or constructor injection
private LegacyService legacy;
public SomeBean myMethod() {
CommonUtils.someStaticMethod();
return legacy.legacyService();
}
public void setLegacyService(LegacyServiceImpl legacyService) {
legacy = legacyService;
}
}
public class LegacyServiceImpl implements LegacyService {
// Injected through setter or constructor injection
private LegacyDAO ldao;// LegacyDAO is an interface
public SomeBean legacyService() {
return ldao.legacyDAO();
}
public void setLegacyDAO(LegacyDAO legacyDAO) {
ldao = legacyDAO;
}
}
public class LegacyDAO {
public SomeBean legacyDAO() {
return null;
}
}
public static class CommonUtils {
public static String someStaticMethod() {
return "in CommonUtils.someStaticMethod()";
}
}
}

how to create a mock in a model test case

Maybe I am doing this wrong.
I'd like to test the beforeSave method of a model (Antibody). A part of this method calls a method on an associated model (Species). I'd like to mock the Species model but don't find how.
Is it possible or am I doing something that goes against the MVC pattern and thus trying to do something that I shouldn't?
class Antibody extends AppModel {
public function beforeSave() {
// some processing ...
// retreive species_id based on the input
$this->data['Antibody']['species_id']
= isset($this->data['Species']['name'])
? $this->Species->getIdByName($this->data['Species']['name'])
: null;
return true;
}
}
Assuming your Species model in created by cake due to relations, you can simply do something like this:
public function setUp()
{
parent::setUp();
$this->Antibody = ClassRegistry::init('Antibody');
$this->Antibody->Species = $this->getMock('Species');
// now you can set your expectations here
$this->Antibody->Species->expects($this->any())
->method('getIdByName')
->will($this->returnValue(/*your value here*/));
}
public function testBeforeFilter()
{
// or here
$this->Antibody->Species->expects($this->once())
->method('getIdByName')
->will($this->returnValue(/*your value here*/));
}
Well, it depends on the way your 'Species' object is injected.
Is it injected via the constructor ? Via a setter ? Is it inherited ?
Here is an example with a constructor injected object :
class Foo
{
/** #var Bar */
protected $bar;
public function __construct($bar)
{
$this->bar = $bar;
}
public function foo() {
if ($this->bar->isOk()) {
return true;
} else {
return false;
}
}
}
Then your test would be something like this:
public function test_foo()
{
$barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
$barStub->expects($this->once())
->method('isOk')
->will($this->returnValue(false));
$foo = new Foo($barStub);
$this->assertFalse($foo->foo());
}
The process is quite the same with setter injected objects :
public function test_foo()
{
$barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
$barStub->expects($this->once())
->method('isOk')
->will($this->returnValue(false));
$foo = new Foo();
$foo->setBar($barStub);
$this->assertFalse($foo->foo());
}

How to verify that method argument's property values are set when mocking methods with Moq?

Not sure if it has been asked before, here is the question.
Code first:
public class Customer {
public string Password { get; set; }
public string PasswordHash { get; set; }
}
public class CustomerService {
private ICustomerRepository _repo;
public CustomerService(ICustomerRepository repo) {
_repo = repo;
}
public int? AddCustomer(Customer customer) {
customer.PasswordHash = SHA1Hasher.ComputeHash(customer.Password);
return _repo.Add(customer);
}
}
public interface ICustomerRepository {
int? Add(Customer c);
}
public class CustomerRepository : ICustomerRepository {
int? AddCustomer(Customer customer) {
// call db and return identity
return 1;
}
}
[TestClass]
public class CustomerServiceTest {
[TestMethod]
public void Add_Should_Compute_Password_Hash_Before_Saving() {
var repoMock = new Mock<ICustomerRepository>();
//how do I make sure the password hash was calculated before passing the customer to repository???
}
}
How do I verify that CustomerService assigned the PasswordHash before passing the customer to repository?
There are several approaches you could take. Although not necessarily the best solution, here's one that doesn't require you to change your existing API. It assumes that SHA1Hasher.ComputeHash is a public method.
[TestClass]
public class CustomerServiceTest
{
[TestMethod]
public void Add_Should_Compute_Password_Hash_Before_Saving()
{
var customer = new Customer { Password = "Foo" };
var expectedHash = SHA1Hasher.ComputeHash(customer.Password);
var repoMock = new Mock<ICustomerRepository>();
repoMock
.Setup(r => r.Add(It.Is<Customer>(c => c.PasswordHash == expectedHash)))
.Returns(1)
.Verifiable();
// invoke service with customer and repoMock.Object here...
repoMock.Verify();
}
}
A slightly better solution would be to turn the SHA1Hasher into an injected service (such as IHasher) so that you can confirm that the PasswordHash property was assigned the value created by the IHasher instance.
Opening op your API even more, you could make the PasswordHash property virtual, so that you could pass a Mock Customer to the AddCustomer method to verify that the property was correctly set.
You could make SHA1Hasher non-static and virtual or wrap it in a ISHA1Hasher interface which can then be mocked. Wrapping static methods and objects in mockable classes is a classic way to increase testability.