I have problem with sending a object from my webservice.
I have created a diagram with a product Entity... then I generated the database... C# generates a few classes in a ...Designer.cs file.
In that file I have the class Product which with the following:
[EdmEntityTypeAttribute(NamespaceName="WinkelModel", Name="Product")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Product : EntityObject
I created a webservice with the following method:
public Product[] GetProducts()
{
using (WinkelModelContainer wmc = new WinkelModelContainer())
{
var products = from p in wmc.Products select p;
return products.ToArray();
}
}
But when I start the WCF Test Client to test my webservice I get the following when I want to test this method:
This operation is not supported in the WCF Test Client because it uses type Product
Does anyone has a solution for this problem?
Thanks in advance!
I solved it... This isn't possible in C#. I have to create a seperate class with the same information and send this class with my webservice.
Related
Trying to write some proper AEM integration tests using the aem-mocks framework. The goal is to try and test a servlet by calling its path,
E.g. an AEM servlet
#SlingServlet(
paths = {"/bin/utils/emailSignUp"},
methods = {"POST"},
selectors = {"form"}
)
public class EmailSignUpFormServlet extends SlingAllMethodsServlet {
#Reference
SubmissionAgent submissionAgent;
#Reference
XSSFilter xssFilter;
public EmailSignUpFormServlet(){
}
public EmailSignUpFormServlet(SubmissionAgent submissionAgent, XSSFilter xssFilter) {
this.submissionAgent = submissionAgent;
this.xssFilter = xssFilter;
}
#Override
public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
String email = request.getParameter("email");
submissionAgent.saveForm(xssFilter.filter(email));
}
}
Here is the corresponding test to try and do the integration testing. Notice how I've called the servlet's 'doPost' method, instead of 'POST'ing via some API.
public class EmailSignUpFormServletTest {
#Rule
public final AemContext context = new AemContext();
#Mock
SubmissionAgent submissionAgent;
#Mock
XSSFilter xssFilter;
private EmailSignUpFormServlet emailSignUpFormServlet;
#Before
public void setup(){
MockitoAnnotations.initMocks(this);
Map<String,String> report = new HashMap<>();
report.put("statusCode","302");
when(submissionAgent.saveForm(any(String.class)).thenReturn(report);
}
#Test
public void emailSignUpFormDoesNotRequireRecaptchaChallenge() throws IOException {
// Setup test email value
context.request().setQueryString("email=test.only#mail.com");
//===================================================================
/*
* WHAT I END UP DOING:
*/
// instantiate a new class of the servlet
emailSignUpFormServlet = new EmailSignUpFormServlet(submissionAgent, xssFilter);
// call the post method (Simulate the POST call)
emailSignUpFormServlet.doPost(context.request(),context.response());
/*
* WHAT I WOULD LIKE TO DO:
*/
// send request using some API that allows me to do post to the framework
// Example:
// context.request().POST("/bin/utils/emailSignUp") <--- doesn't exist!
//===================================================================
// assert response is internally redirected, hence expected status is a 302
assertEquals(302,context.response().getStatus());
}
}
I've done a lot of research on how this could be done (here) and (here), and these links show a lot about how you can set various parameters for context.request() object. However, they just don't show how to finally execute the 'post' call.
What you are trying to do is mix a UT with IT so this won't be easy at least with the aem-mocks framework. Let me explain why.
Assuming that you are able to call your required code
/*
* WHAT I WOULD LIKE TO DO:
*/
// send request using some API that allows me to do post to the framework
// Example:
// context.request().POST("/bin/utils/emailSignUp") <--- doesn't exist!
//===================================================================
Your test will end up executing all the logic in SlingAllMethodsServlet class and its parent classes. I am assuming that this is not what you want to test as these classes are not part of your logic and they already have other UT/IT (under respective Apache projects) to cater for testing requirements.
Also, looking at your code, bulk of your core logic resides in following snipper
String email = request.getParameter("email");
submissionAgent.saveForm(xssFilter.filter(email));
Your UT criteria is already met by the following line of your code:
emailSignUpFormServlet.doPost(context.request(),context.response());
as it covers most of that logic.
Now, if you are looking for proper IT for posting the parameters and parsing them all the way down to doPost method then aem-mocks is not the framework for that because it does not provide it in a simple way.
You can, in theory, mock all the layers from resource resolver, resource provider and sling servlet executors to pass the parameters all the way to your core logic. This can work but it won't benefit your cause because:
Most of the code is already tested via other UT
Too many internal mocking dependencies might make the tests flaky or version dependant.
If you really want to do pure IT, then it will be easier to host the servlet in an instance and access it via HttpClient. This will ensure that all the layers are hit. A lot of tests are done this way but it feels a bit heavy handed for the functionality you want to test and there are better ways of doing it.
Also the reason why context.request().POST doesn't exist is because context.request() for is a mocked state for the sake of testing. You want to actually bind and mock Http.Post operations which needs some way to resolve to your servlet and that is not supported by the framework.
Hope this helps.
I am new to api web services. I am working on a web service that should update a database table. I have decided to use put, but I am having trouble testing with my unit test.
CONTROLLER
static readonly ICarsRepository repository = new CarsRepository();
public void PutRejectRecord(int carId, int statusId)
{
if (!repository.RejectRecord(carId, statusId))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
MODEL
public class CarsRepository : ICarsRepository
{
public bool RejectRecord(int carId, int statusId)
{ ... }
I have been searching for a solution to no avail. I have tried but failed using
string uri = "api/Cars/Approve/{id}/{approveStatus}";
HttpClient client = new HttpClient();
var response = client.PostAsync(uri, new StringContent("2"));
which makes no sense.
How do I set the HttpClient to point to 'PUT api/Cars/Approve/{id}/{approveStatus}'? I am trying to get this right and I am yet to have the lightbulb moment which is frustrating... Please help!
It sounds like:
1) You're using C#, correct? With MVC3 or 4, correct?
2) You have a pre-existing REST web service (you're not writing the service yourself, correct)?
3) All you want to do is get your C# program to talk to the service, correct?
Here are a few links:
How to make a HTTP PUT request?
http://www.codeproject.com/Articles/426769/Creating-a-REST-service-using-ASP-NET-Web-API
http://www.asp.net/web-api/tutorials/hands-on-labs/build-restful-apis-with-aspnet-web-api
I'm developing an application to perform a series of tests on various web services. These web services consume and produce json, and for each of them we have a class to model the json request and response. For example:
If the json request for serviceX is something like this:
{
"name":"Alex",
"id":"123"
}
We have a class serviceXrequest like this:
public class serviceXrequest {
String name;
String id;
//Constructor, getters/setters, etc
...
}
With an object of that class as the starting point, we can perform a series of test on the web service. The idea is to make those test as generic as possible so they can be used with any web service by just writing a class that models it's request and a class to model the response.
For that reason, all of the test methods developed so far work with plain java objects. This is an example of what I want to have:
public class WebServiceTest {
String serviceURL;
String requestJson;
String requestClass;
String responseClass;
public WebServiceTest() {}
#Test
public static void Test1() { ... }
#Test
public static void Test2() { ... }
....
#Test
public static void TestN() { ... }
}
And then, from another class, invoke those tests with doing something like this:
public class LoginTest { //To test the login web service, for example
public static void main(String[] args) {
WebServiceTest loginTest = New WebServiceTest();
loginTest.setServiceURL("172.0.0.1/services/login");
loginTest.setRequestJson("{"user":"ale","pass":"1234"}");
...
loginTest.runTests();
}
}
I know it's not that simple, but any ideas on how to get there?
Thanks in advance!!
You might also look into REST-assured
One of the best tools for testing your webservices is SOAP UI, but this is more for functional testing
As well I integrated very well FitNesse tests
JMeter goes hand in hand with LoadUI ..kind of same things in terms of stress and load tests for webservices.
Junit...i never used directly applied to the webservice itself.
Most of the times I had a Spring service called by the implemetation of the WebService interface (Port) and I unit tested that one.
You should consider using http-matchers (https://github.com/valid4j/http-matchers) which let's you write JUnit-tests, using regular hamcrest-matchers (bundled with JUnit) to test your web-service via standard JAX-RS interface.
I am developing a WebService and Client for it using JBoss 5.1.0GA. The JBossWs stack was already preinstalled with the binary that I downloaded and as I understand it is JBossWs 3.1.2GA
I have developed a web service using this setup and have also created a client successfully. This is what I have.
A pojo web service deployed as a war file.
#WebService
public class Service{
#WebMethod
public CompleObj getConfiguration() {
CompleObj oConf = new CompleObj ();
for (int i = 0; i < 10; i++) {
NestObj oInst = new BOpRepoInstance("Val1", "Val2", "Val3", "Val4");
oConf.addRepoInstance(oInst);
}
return oConf;
}
}
Here,
CompleObj => is a Complex Object that has a list of type NestObj. Its
getter/setters, toString and some other methods.
NextObj => has 4 variables of Type String. Its getter/setters,
toString, hashCode, equals and some other methods.
Got this web service deployed successfully.
Later created a client using the eclipse wizard for generating Web Service Client using WSDL document. It also created a sample client file which would call the webservice and fetch the return value. This also worked like a charm.
Now my problem is, when eclipse generated stubs for clients it created classes for CompleObj and NestObj. These classes only has the variables and its getters/setters (this make sense as these are being generated from WSDL doc). Thus i loose a lot of other methods that includes toString, hasCode, equals etc, which I want to use at the Client side as well.
Now how can I make use of the actual class files defined in the WebService project directly and avoid the client to use the generated ones. I can provide the class files as .jar binary for the Client project, I cant really get how to achieve this.
Another question is, the web service location is embedded in the stubs directly, what can i do to have the webservice location passed as part of the argument to the invocation code?
The classes which are generated in the client side are just place
holders it is not deserilized version of your own classes,When you
invoke the service it is used to carry your object to server then
the JBOOSWS will do the JAXB mapping to the actual classes. So you
can not make the your own classes to be used in the client side
though they are look same.
URL will be fixed in the stub code, since in eclipse while generating WS client the first
thing you must provide is, the WSDL URL,then eclipse will generate the
client code accordingly,so generated code is specific to the WSDL
you provided. If you want to pass the WSDL dynamically,then you
need to have your own code to generate the client stubs by passed
WSDL URL using any WSDLtoJAVA or any other utility.
I am deploying a restful web services using Netbeans EE6 and jersey libraries with the tutorial http://netbeans.org/kb/docs/websvc/rest.html.
When I create a restful web services from entities that hold composite primary keys in the database, the project gives me an error when I try to test the web services:
SEVERE: Missing dependency for method public entities.RMSchedule service.RMScheduleFacadeREST.find(entities.RMSchedulePK) at parameter at index 0
SEVERE: Method, public entities.RMSchedule service.RMScheduleFacadeREST.find(entities.RMSchedulePK), annotated with GET of resource, class service.RMScheduleFacadeREST, is not recognized as valid resource method.
Is the error due to composite primary keys or is there a step that I should include?
Many thanks in advance.
I think this issue is related to Netbeans bug:
https://netbeans.org/bugzilla/show_bug.cgi?id=208375
When creating entity class which has composite primary keys,
two entity files are created. (ex CustomerEntity.jave, CustomerEntityPK.java)
Then if you choose to create the servlet from the entity class, the servlet comes with automatically generated code such as below:
#DELETE
#Path("{id}")
public void remove(#PathParam("id") CustomerEntityPK id) { //error
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public CustomerEntity find(#PathParam("id") CustomerEntityPK id) { //error
return super.find(id);
}
The issue is that argument being passed to the servlet methods is CustomerEntityPK which has composite primary key.
If you change the argument type to something like String then the error went away in my case.
#DELETE
#Path("{id}")
public void remove(#PathParam("id") String id) { //type set to String now
super.remove(super.find(id));
}
But in my project I did not need such auto generated code so I simply choose to create servlet class by hand and has no problem.
Hope that helps.