I'm writing unit test for my application which has a following function
std:: string getHandler(HTTPServerRequest& request){
}
I'm facing the problem in creating HTTPServerRequest object as it is Abstract class & its subclasd needs HTTPServerRequestImpl requires creation of HTTP Server & a request.
Any help towards simplifying creation of HTTPServerRequest object would be highly appreciated
Related
I have a number of classes that consume API services and whose constructors follow the pattern below:
public class SomeClass
{
public SomeClass(IHttpClientFactory factory, ILogger<SomeClass> logger = null)
{
// ...
}
public SomeClass(HttpClient client, ILogger<SomeClass> logger = null)
{
// ...
}
}
The first constructor is the one used by .NET Core's built-in dependency injection (by calling IServicesCollection.AddHttpClient() from the Startup.ConfigureServices() method, and then calling IHttpClientFactory.CreateClient() in the constructor); the second constructor is mostly used for unit testing, to allow a HttpClient (or mock) to be passed in. This has worked fine until now, but this morning I started getting errors like the one below:
An unhandled exception has occurred
System.InvalidOperationException:
Unable to activate type
'Service'.
The following constructors are ambiguous:Void
.ctor(System.Net.Http.IHttpClientFactory,
Microsoft.Extensions.Logging.ILogger`1[Service])Void
.ctor(System.Net.Http.HttpClient,
Microsoft.Extensions.Logging.ILogger`1[Service])
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache
lifetime, Type serviceType, Type implementationType, CallSiteChain
callSiteChain)
... long stack trace elided...
This was working up till now. It seems strange that the dependency injection mechanism considers the constructors to be ambiguous when IHttpClientFactory and HttpClient do not share any common interfaces.
I updated both Visual Studio 19 to the latest version (16.8.2) and all NuGet packages in the solution at the weekend. The Microsoft.Extensions.DependencyInjection package is now version 5.0.0; previously it was version 3.1.9. I have worked around the issue for now by removing the constructors that take the HttpClient argument and replaced the code in my tests to use a mock IHttpClientFactory instead, so the actual impact was low. However, it would be help my peace of mind, if nothing else, to understand why this broke in the first place. Is there some aspect of configuring .NET Core dependency injection that I have overlooked? Or has the strategy to resolve dependencies changed subtly between versions 3.1.9 and 5.0.0?
Written the Integration test case for testing Corda Flows through API class as:
val api=ProjectApi(mockNode1.rpcOps)
val message = "some input message"
val resp: Response=api.publishSSI(message)
assertEquals(resp.status, 201,"Failed to publish SSI")
But getting CURRENT_RPC_CONTEXT.get() must not be null exception while starting corda flow inside api.publishSSI() method.
what could be the cause?
You need to use the RPC client API to connect to the node. You can find more details here: https://docs.corda.net/tutorial-clientrpc-api.html
You can't test the API by manually constructing it in this way. When the API is set up, some additional context is passed in, which is lacking here.
I have created a web application in .Net which will be used to consume multiple wcf service. The end points will be specified at runtime using below code:
ServiceWCFTest3.Service1Client client1 = new Service1Client();
client1.Endpoint.Address = new EndpointAddress("http://localhost:55473/Service1.svc");
Also please refer below one of the web methods exposed by the service:
EmployeeDetails empDtl= new EmployeeDetails("John");
ResultObject result = channel.ADMSAccess_Entry("Test",empDtl );
These classes are marked as DataContract in the specific wcf service.
Now, when the application is executed to access multiple wcf services by changing end point at runtime, it points to correct service and correct web methods. But the value of object EmployeeDetails and ResultObject is passed and received as null. I need to use these class objects to communicate. Can anybody please suggest how can I pass the values using these objects?
I'll explain what I've done so far. I'm using VS2010.
Firstly I've created a ASP.NET Web Service Application (framewkork 3.5) with a service with these operations:
[WebMethod]
public Boolean ShoppingTripNeeded(DateTime d)
{
DBConnection db = new DBConnection();
return db.ShoppingTripNeeded(d);
}
[WebMethod]
public String[] ShopsToVisit(DateTime d)
{
DBConnection db = new DBConnection();
return db.ShopsToVisit(d);
}
[WebMethod]
public Item[] ItemsToBuy(DateTime d, String shop)
{
DBConnection db = new DBConnection();
return db.ItemsToBuy(d, shop);
}
And now I'm creating a WCF Workflow Service Application, in which I want to call sequently the 3 methods above, so I've added a Service Reference to my service wsdl here:
http://awtassignment3-shoppinglistservice1.cloudapp.net/Service1.asmx?WSDL
This referencing adds the 3 operations. The first one "ShoppingTripNeeded" seems to be fine (receiving a DateTime and returning a Boolean), but for the other operations, the parameters have changed in a strange way...
For example the operation ShopsToVisit now ask for a ShopsToVisitRequestBody and returns a ShopsToVisitResponseBody... I don't know why this happens! because the first operation is fine...
Moreover, as I'm working with a workflow, I can't "play" with this types to find out what's going on...
Have you any guess? any help will be fine...
Thanks very much!
Is there a reason you are using ASMX? WCF has replaced Web Services as far more superior service communication technology. See SO: Web Services — WCF vs. Standard, SO: Web Service vs WCF Service
To answer your question:
WF 3.5 will wrap any operation with Request/Response message pattern that is not a primitive (e.g. bool, int). String[] is not a primitive type hence it will be wrapped.
WF 4.0 adding service reference (dialog) will wrap all operations in Request/Response message pair by default regardless if this is primitive or complex type. On top of that, it will create Activity for each operation that it discovers.
Using Request/Response message pattern allows for controlling the message shape specifically message headers.
For Reference:
SO: When should I use Message Contracts instead of DataContract and why?
MSDN: Message Contracts
I'm trying to create a bunch of MS visual studio unit tests for my n-tiered web app but for some reason I can't run those tests and I get the following error -
"Object reference not set to an
instance of an object"
What I'm trying to do is testing of my data access layer where I use LINQ data context class to execute a certain function and return a result,however during the debugging process I found out that all the tests fail as soon as they get to the LINQ data context class and it has something to do with the connection string but I cant figure out what is the problem.
The debugging of tests fails here(the second line):
public EICDataClassesDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["EICDatabaseConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
And my test is as follows:
TestMethod()]
public void OnGetCustomerIDTest()
{
FrontLineStaffDataAccess target = new FrontLineStaffDataAccess(); // TODO: Initialize to an appropriate value
string regNo = "jonh"; // TODO: Initialize to an appropriate value
int expected = 10; // TODO: Initialize to an appropriate value
int actual;
actual = target.OnGetCustomerID(regNo);
Assert.AreEqual(expected, actual);
}
The method which I call from DAL is:
public int OnGetCustomerID(string regNo)
{
using (LINQDataAccess.EICDataClassesDataContext dataContext = new LINQDataAccess.EICDataClassesDataContext())
{
IEnumerable<LINQDataAccess.GetCustomerIDResult> sProcCustomerIDResult = dataContext.GetCustomerID(regNo);
int customerID = sProcCustomerIDResult.First().CustomerID;
return customerID;
}
}
So basically everything fails after it reaches the 1st line of DA layer method and when it tries to instantiate the LINQ data access class...
I've spent around 10 hours trying to troubleshoot the problem but no result...I would really appreciate any help!
UPDATE:
Finally I've fixed this!!!!:) I dont know why but for some reasons in the app.config file the connection to my database was as follows:
AttachDbFilename=|DataDirectory|\EICDatabase.MDF
So what I did is I just changed the path and instead of |DataDirectory| I put the actual path where my MDF file sits,i.e
C:\Users\1\Documents\Visual Studio 2008\Projects\EICWebSystem\EICWebSystem\App_Data\EICDatabase.mdf
After I had done that it worked out!But still it's a bit not clear what was the problem...probably incorrect path to the database?My web.config of ASP.NET project contains the |DataDirectory|\EICDatabase.MDF path though..
Is LINQDataAccess.EICDataClassesDataContext looking to the web.config or some other outside source of data for its setup?
I can tell you for a fact that you must jump thru hoops to get web.config accessible to your test code.
Update
Ah, yes. I see that you're using ConfigurationManager on the line where your test fails... ConfigurationManager looks to web.config for configuration. This has been a sticking point for me when I write my tests.
You need to either change the code so that the class can be instantiated without web.config, or you need to make it so that your tests can access web.config.
Does your test project have it's own configuration file? This type of behavior usually means the app can't find the connection string. Test projects require their own file since they are not running in the context of the client app.
UPDATE The error you describe after adding an app.config is common when testing web applications built on SQLExpress and attaching an .mdf. SQLExpress cannot be run in more than one process at a time. So if you have previously run your web application it may still be active and will conflict with the attempt to attach the database.
You can use SQL Management Studio to attach the database permanently and then use a more traditional connection string like:
Server=myServer;Database=EICDatabase;Trusted_Connection=True;
For me it seems like your problem is the connection string, which is not set.
I assume your unit test is in a different project than the DAL.
You call the 'new' command on the datacontext constructor without a connection string. So it should usually use its default, when set. But since this setting normally is stored in the web.config of the other project there is no connection string set and you get the error.
If its right, what i assume, you have to get the settings from the DAL project into the unit-testing project. Simplest solution should be to copy web.config connection string to app.config of unit test project.
There are other possibilities for sure, but i think its not easy to get the web.config configuration into your unit-testing project.