What I need is to have some specific methods (toString()) on my entities in order to be able to use them on my WebService Client (so I don't have to re-write them every time I Refresh my Webservice from Glassfish).
I ask this because I noticed that the only methods that are generated on my Client are the getters and setters of my fields, even if I write toString() on the Server side of the Webservice.
I guess the question is there a way to force customized methods to be deployed to the Application Server, so that those entities can reply to a toString(), for instance, on the Client?
package entities;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Auxiliarfiles implements Serializable {
#Column(unique=false,updatable=true,insertable=true,nullable=false,length=38,scale=0,precision=0)
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(unique=false,updatable=true,insertable=true,nullable=true,length=255,scale=0,precision=0)
#Basic
private String description;
#Column(unique=false,updatable=true,insertable=true,nullable=true,length=255,scale=0,precision=0)
#Basic
private String name;
public Auxiliarfiles(){}
public Long getId() {
return this.id;
}
public void setId (Long id) {
this.id = id;
}
public String getDescription() {
return this.description;
}
public void setDescription (String description) {
this.description = description;
}
public String getName() {
return this.name;
}
public void setName (String name) {
this.name = name;
}
public String toString() {
return this.getId() + " - " + this.getName();
}
}
Thanks in advance!
Related
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
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;
}
}
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
I have two POJOs
#XmlRootElement
public class PojoBase {
}
#XmlRootElement
public class PojoRequest extends PojoBase {
private String strTemplate;
public void setTemplate(String strTemplate) {
this.strTemplate = strTemplate;
}
public String getTemplate() {
return strTemplate;
}
}
#XmlRootElement
public class PojoResponse extends PojoBase {
private String strName;
public void setName(String strName) {
this.strName = strName;
}
public String getName() {
return strName;
}
}
I have service which accepts the base class and returns the base class as response.
#POST
#Path("/start")
#Produces({MediaType.APPLICATION_JSON})
#Consumes(MediaType.APPLICATION_JSON)
public PojoBase registerNumber(JAXBElement<PojoBase> theRequest) {
//does some work with theRequest.
//here the theRequest object doesn't has pojoRequest data.
PojoResponse pojoResponse = new PojoResponse();
pojoResponse.setName("Sample");
return pojoResponse;
}
From client I am sending pojo base object but not sure why Restful doesn't get actual theRequest object.
Here is the client code:
public class HttpClient {
static String _strServiceURL = "http://127.0.0.1:8080/middleware/rest/service/start";
public static void main(String[] args) throws Exception {
PojoRequest pojoRequest = new PojoRequest();
pojoRequest.setTemplate("Somedata");
PojoBase response = getResponse(pojoRequest);
PojoResponse pojoresponse = (PojoResponse) response;
System.out.println(response);
}
private static PojoBase getResponse(PojoBase request) {
try {
Client client = Client.create();
WebResource webResource = client.resource(_strServiceURL);
ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, request);
System.out.println(response.getStatus());
if(response.getStatus() == 200){
PojoBase response = response.getEntity(PojoBase.class);
return response;
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
Can you please tell me how to get the PojoRequest at Service end?
Any help is appreciated.
Thanks
I don't think you can pass a superclass to jersey like this. I believe, though I may be wrong, that as registerNumber() has a parameter JAXBElement<PojoBase> it will do something like:
instantiate a PojoBase
do reflection on PojoBase (which has no properties), therefore nothing to set.
call registerNumber() with the practically empty PojoBase object
So why not try changing the signature to:
public PojoBase registerNumber(JAXBElement< PojoRequest > theRequest)
or even (with com.sun.jersey.api.json.POJOMappingFeature = true):
public PojoBase registerNumber(PojoRequest theRequest)
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.