I've been trying to look for examples on the internet or anywhere of how to implement gRPC unit testing in c# but can't for the love of me find anything, or I could just be over seeing things.
If someone could point me in the right direction I would be very grateful.
S
For simple unary services, as long as you're not doing anything interesting with gRPC headers, cancellation, etc - you should be able to treat your server type just as the service type - create an instance, call the simple unary method(s), check the results. However, this won't validate marshalling or the gRPC layer, etc. For that, you really need an integration test. Likewise, anything involving streaming probably needs an integration test, because there's a lot of background plumbing. If this was me, I would simply create a server as a test-fixture, and write my tests by creating a genuine client that can talk to those services.
If you're using the Google server code, something like the fixture I'm using here should do (don't worry about the AddCodeFirst - that's some protobuf-net.Grpc additions; just use the same registration code that you would have used in the real server). If you need to test with the Microsoft server code, you'd need to host Kestrel in process as the fixture; but fortunately: they're mostly completely interchangeable, so if in doubt: use whichever is simpler. Note that on the client side: again, since the idea of gRPC is to be transparently interoperable between languages/runtimes/frameworks, it shouldn't matter whether the client uses the Microsoft or Google transport. Historically there have been some minor differences, but these are a: pretty niche, and b: get fixed when found.
I usually do something like this
1: I create an interface for the service to test the DI system and or to be able to mock it. I do this as registering the gRPC service with the framework kinde-does-that as well as it's created similar to a controller
Then I write my Test like so:
[TestMethod]
public async Task Call_Grpc_Method_Test()
{
var grpcService = _service.GetRequiredService<IMyService>();
var request = new MyRequest {When=DateTime.Now.AddDays(30)};
var context = TestServerCallContext.Create(
method: nameof(IMyService.WinningLotteryNumbers)
, host: "localhost"
, deadline: DateTime.Now.AddMinutes(30)
, requestHeaders: new Metadata()
, cancellationToken: CancellationToken.None
, peer: "10.0.0.25:5001"
, authContext: null
, contextPropagationToken: null
, writeHeadersFunc: (metadata) => Task.CompletedTask
, writeOptionsGetter: () => new WriteOptions()
, writeOptionsSetter: (writeOptions) => { }
) ;
var answer= await grpcService.WinningLotteryNumbers(request, context);
Assert.IsNotNull(answer);
}
IMyService is the gRPC service I want to test and I just create an IServiceProvider that can build one for me via the actual implementations making it an integration test or via mocked objects making it a unit test.
The TestServerCallContext class is located in the NuGet package Grpc.Core.Testing, you would need to add that to your test project.
as to the constructor, well you can use hard coded sample data as I demonstrated or go fancy and add meta data for headers and authcontex as well as the stuff when you need it...
As you can see, not that hard to do once you get started ;-)
Related
Using WCF, .NET 4.5, Visual Studio 2015, and want to use per-session instancing, not singleton. The services provided are to be full-duplex, over tcp.net.
Suppose I have two machines, A & B...
B as a client, connects to a "service" provided as a WCF service on same machine B, and starts talking to it, call it object “X”. It ALSO connects to another instance of the same service, call it object “Y”
A as a client, wants to connect to, and use, exact same objects B is talking to, objects “X” and “Y”, except now it’s remote-remote, not local-remote.
“X” and “Y” are actually a video servers, and both have “state”.
Can I do this? How, when I’m a client, do I specify WHICH service instance I want to connect to?
Obviously, on machine "B", I could kludge this by having the services just be front-ends with no "state", which communicate with some processes running on "B", but that would require I write a bunch of interprocess code, which I hate.
Machine B is expected to be running 100's of these "video server" instances, each one being talked to by a local master (singleton) service, AND being talked to by end-user machines.
I realize this question is a bit generic, but it also addresses a question I could not find asked, or answered, on the Internets.
I just thought of one possible, but kludge-y solution: since the master service is a singleton, when service instance "X" is created by the end-user, it could connect to the singleton master service, through a proxy to the singleton. Then, the singleton can talk back to instance "X" over a callback channel. Yeah, that would work! messy, but possible.
I'd still like to know if end user A and end user B can both talk to the same (non-singleton) service instance on machine C through some funky channel manipulation or something. As I understand the rules of WCF, this simply isn't possible. Perhaps maybe if you're hosting the service yourself, instead of IIS, but even then, I don't think it's possible?
I've faced the same problem and solved it by creating two service references, one for the local one for the remote. Let's call it LocalServiceClient and RemoteServiceClient.
In a class, create a property called Client (or whatever you like to call it):
public LocalServiceClient Client {
get {
return new LocalServiceClient();
}
}
Okay this is for only one of them. Just create another now, and set which one to use with a compiler flag:
#if DEBUG
public LocalServiceClient Client {
get {
return new LocalServiceClient();
}
}
#else
public RemoteServiceClient Client {
get {
return new RemoteServiceClient();
}
}
#endif
Instantiate any instances of your Client using var keyword, so it will be implicitly-typed, or just use Client directly:
var client = Client;
client.DoSomething...
//or
Client.DoSomething...
This way, when you are working locally, it will connect to the local service, and on release configuration (make sure you are on Release when publishing) it will compile for the remote one. Make sure you have the exact same signature/code for both services though at the WCF-side.
There are also methods that you can dynamically do it in code, or like in web.config, they would also work for sure, but they are usually an overkill. You probably need to connect to local one in debugging, and the remote one in production, and this is going to give you exactly what you need.
I'm trying to test my WCF Service Endpoints using IntelliTest I've created the IntelliTest units in a test project, but I need to specify the Server address and port in order for the test to remotely even to work.
This is one of the PexMethods
public ICredentials CredentialsTest()
{
ICredentials result = Service.Credentials();
return result;
// TODO: add assertions to method ServiceTest.CredentialsTest()
}
I've added
Service.ServiceEndPointAddress = "net.tcp://localhost:51010/WCFService";
but when I run the test I get an InvalidProgramException.
What I would like to do is assign the ServiceEndPointAddress once as it is a static property in Service. Anybody that can give some guidance?
There are a couple of issues here:
Getting an InvalidProgramException indicates that IntelliTest has instrumented your code in such a manner as to cause the underlying CLR to raise the exception. That would be a bug in IntelliTest. I request you to file this using the Send a Smile in Visual Studio.
You should not use IntelliTest to directly explore your WCF code. Instead, you should isolate the WCF related external dependencies using mocks (much as you would do if you were writing unit tests by hand), and then run IntelliTest to explore the resultant code. For mocking you can consider using Fakes.
I want to host WCF service inside unit Test using ServiceHost.
And then running them in on a build machine.
Is it possible to host web services like this ? if yes how it's done ?
Thanks
Sure, you just use a ServiceHost like you would if it was a self-hosted wcf service. I typically do this in a test fixture/class setup/teardown.
For example with NUnit:
[TestFixture]
public class MyTests
{
private ServiceHost service;
[TestFixtureSetUp]
public void FixtureSetUp()
{
service = new ServiceHost(typeof(MyService));
service.Open();
}
[Test]
public void ThisIsATest()
{
using (var client = new MyServiceClient())
client.DoStuff(); // test whatever
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
if (service != null)
{
if (service.State == CommunicationState.Opened)
service.Close();
else if (service.State == CommunicationState.Faulted)
service.Abort();
}
}
}
You will also need to copy any WCF XML configuration into the test assembly's app.config.
One thing to note however is the threading model of your unit test framework. If it is possible for your test runner to run multiple test classes simultaneously, then you might try to open the same service on the same port more than once, and it might fail.
On a final note, I would typically separate tests that do and don't fire up the actual WCF service. Put tests that don't hit WCF into a separate "Unit Tests" assembly, that runs without dependencies and runs fast, and put ones that do use WCF into an "Integration Tests" assembly instead. That is just a recommendation of course, not a rule.
It is indeed possible and actually is the same as hosting a WCf service in a console application!
Add your app.config to the UT assembly and proceed as always.
(You can also configure programatically of course).
Similarly, you create a client for the host in code.
Instantiate and open your host and client on the set-up method, you can do this per test or per class, depending on the level of isolation you seek.
So you see, you don't have to have a separate deployment stage.
Having said all the above, I would actually discourage you from working with services in your Unit tests. One of the best practices concerning unit tests is that they should be very fast to run. Making calls to web services (even local) is very costly in UT.
Moreover, this kind of contradicts the semantics of a UNIT test. You should be testing small bits of functionality. And strive to mock out external dependencies such as Database access, External services and even other classes. I would be happy to elaborate and refer to more information if you feel like it.
I think the problem here is that UnitTests are usually just a set of binaries that are executed by some other framework (NUnit, xUnit,...).
You can try on the TestSuite setup start another Thread and run WCF on that Thread, but I believe it is much more involved into this approach and Test suites may no like it as well.
What I would do is to setup a deployment step on your build machine of the WCF service to IIS or redeployment to the Windows Service hosted WCF before running UnitTests.
I am trying to test some async methods involving the HttpClient work with vs 2012 express for win 8 and it's test framework. No matter how I try I always get the same exception.
For example this test code:
[TestMethod]
public async Task Connect()
{
HttpClient client = new HttpClient();
string reply = await client.GetStringAsync("http://google.com");
Assert.AreNotEqual(0, reply.Length);
}
Which should probably work considering this: http://www.richard-banks.org/2012/03/how-to-unit-test-async-methods-with.html
Throws
System.Net.WebException: The remote name could not be resolved: 'google.com'
The same code works just fine when called from an actual program (not a test case).
Any help is appreciated.
Please refer to my comments and I can include this as an answer to your question.
"Are you are using the metro style Unit Testing template? If yes you need to enable the Internet Client (I think) in the app manifest file -> capabilities to allow this behaviour?. Also since you are testing an external call, this is not a Unit Test. It is more of an integration test."
I have used exactly the same code you have and I get exactly the same error. As I said if you just tick the the Package.appxmanifest -> Capabilities - > Internet (Client) check box, you test should pass.
I need to change my unit test from local to remote tests and so far I thought that all I had to do is change UrlToTest to point to another server... But VS keeps on insisting to create a Development Web Server instead of using the one that is already running.
So after reading some docs my question actually is do I have install Test Controller and Test Agent on both remote and local computer or what? What if the WebService is on Linux...
Note that I don't want to debug the application that I'm testing. I simply want tests to be executed for a WebService that is already running, that is deployed.
I probably should mention that all my tests consists of WebService calls and some checks like this:
[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("MainProjectName", "/")]
[UrlToTest("http://servername:port/websitename/TestingOnlyWebForm.aspx")]
public void LoginEmptyDataTest()
{
IUserService userService = CreateIUserService();
string email = "";
string password = "";
ReturnMessage<User> actual;
actual = userService.Login(email, password);
Assert.AreNotEqual(true, actual.Status);
Assert.AreNotEqual("db_error", actual.Info);
}
But I have also more complicated tests in which I change some data and send it to another WebService and so on.
Note that UrlToTest previously was pointing to localhost at which point it works but starts a developer server which is not what I want.
What you are trying to is not possible. All that generated unit test is trying to do is to run the test locally on the machine either using the development server by specifying AspNetDevelopmentServerHost or by using local IIS, when AspNetDevelopmentServerHost is not present.
If you want to test remote services right click your unit test project and add a service reference. Point to your service give it a namespace, say Services, and generate the proxies. Once you have the proxies generated just instantiate them and call the methods. Also remove all the unneeded attributes from your test. Your test should roughly look like this:
[TestMethod]
public void LoginEmptyDataTest()
{
using (var userServiceClient = new Services.UserServiceClient(
"BasicHttpBinding_IUserService",
"http://someremotehost/userservice.svc"))
{
var result = userServiceClient.Login("user", "password");
// asserts go here
}
}
This may solve your immediate problem however you should re-think what you are doing as #eglasius said. what happens if the code you call changes state internally? Next test might fail because of that so you need clean-up strategies otherwise your tests will be very brittle and you'll end up ignoring them.
Update: passing an address at run-time. Change the first parameter to whatever enpoint configuration name you have in your config file.
I'll take a stab in the dark at this one because I did something similar recently.
In my case my test project referenced the service project to provide visibility of the service and data contracts the Web Service implements and consumes.
To resolve this - though it can be ignored - move the contracts to a new project. Then have the service and test projects reference the new project, and remove the test projects' reference to the service.
Hope that makes sense!
Once the reference is removed, VS will no longer feel the need to start up your service when you run your tests.
You can disable the startup of the Service Host in the Project settings of your WCF Service Project. Right Click - WCF Options - Uncheck "Start WCF Service Host when debugging another project in the same solution".
You really have to consider the nature of what you're trying to achieve here.
It's hard to tell exactly what you're hitting of the code. I have the impression, you have is a website that calls a web service. You're testing the client code in that context, instead of just testing the service.
If that's the case, remove the attributes and point the url to the correct service like UrbaEsc guided you to. If you don't remove the attributes, you're running the calling code in the context of the site.
Even if the above is not the scenario, and based on what you replied to UrbanEsc in the comments, you'd then be testing an external call to the webservice initiated from the same site process.
You said:
"Found it, but VS still starts something on localhost and then trys to reach external server... Seems like VS is just not designed for real remote testing of webservices"
Read the above. I'd say you need to better understand what you're enabling. You can certainly test remote web services, like you can do pretty much anything you can code. You do that from client code that knows nothing different that what any other external client of the service would know. Support doesn't stop there, as you can do load testing of the service.
Note that what you're doing aren't unit tests, these are integration tests. Or depending on the scope of your system, full system tests.