Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test a Windows Service?

.NET Framework: 2.0 Preferred Language: C#

I am new to TDD (Test Driven Development).

First of all, is it even possible to unit test Windows Service?

Windows service class is derived from ServiceBase, which has overridable methods,

  1. OnStart
  2. OnStop

How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?

At this point, am I even doing a Unit testing? or an Integration test?

I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.

like image 353
dance2die Avatar asked Sep 03 '08 17:09

dance2die


People also ask

How do I run a unit test in Visual Studio?

Run tests in Test Explorer If Test Explorer is not visible, choose Test on the Visual Studio menu, choose Windows, and then choose Test Explorer (or press Ctrl + E, T). As you run, write, and rerun your tests, the Test Explorer displays the results in a default grouping of Project, Namespace, and Class.

What is AAA unit testing?

Arrange/Act/Assert (AAA) is a pattern for organizing unit tests. It breaks tests down into three clear and distinct steps: Arrange: Perform the setup and initialization required for the test. Act: Take action(s) required for the test. Assert: Verify the outcome(s) of the test.

What is Microsoft unit testing?

Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in C#, Visual Basic, and C++ projects. The unit test tools include: Test Explorer—Run unit tests and see their results in Test Explorer.


2 Answers

I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service.

In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate.

like image 127
Guy Starbuck Avatar answered Oct 03 '22 07:10

Guy Starbuck


I have unit tested windows services by not testing the service directly, but rather testing what the service does.

Typically I create one assembly for the service and another for what the service does. Then I write unit tests against the second assembly.

The nice thing about this approach is that your service is very thin. Basically all it does is call methods to do the right work at the right time. Your other assembly contains all the meat of the work your service intends to do. This makes it very easy to test and easy to reuse or modify as needed.

like image 35
Kevin Berridge Avatar answered Oct 03 '22 08:10

Kevin Berridge