Reputation: 99
Hello I'm trying to make a unit test for a class which constructor looks like this:
public Background(Form mainForm, Form optionMenu, bool startMinimized, string server)
So in my unit test I will need to have access to a windows Form of some sort (Instantiate a new one or access an existing one.)
But as I can see there is no way to use windows Forms in unit testing (Unless I have missed something)
anyway to come around this without creating a second constructor for the unit test?
Upvotes: 2
Views: 7948
Reputation: 99
Okay I found out how to fix my problem..
I needed to add a reference to System.Windows.Forms
Then I could use Using System.Windows.Forms
and initiate a new Form to pass to my class.
Many thanks for your time everyone!
Upvotes: 1
Reputation: 1044
I'm not sure that what you're doing is a unit test, because if your test needs to instantiate a Window, then you're also testing the framework as well.
If, for example, you're running your tests on a Build machine that due to a lightning strike fails to create .net WinForms forms, the test will fail, even though your code works perfectly.
If possible, try to separate the dependencies, and use some kind of Mocking technique (hand-written, or with a framework such as MoQ or RhinoMocks).
Read more about it in Roy Oshorov's blog.
You said that you're testing a "Notify Icon" class - it's something that is very hard to unit test without being dependent on Windows. I would consider abstracting it from your real business logic (I would consider creating a system-wide service, an INotificationService or something), and test how your business logic code reacts with this service - you can easily place a mocked service and test your code without bashing heads with the .net Framework.
Regarding the comment "I'm going to test a ping function inside Background which only need the string server" - Can you pass null
to the constructor? (could throw an exception), or perhaps just new Form()?
(This technique is called faking - providing irrelevant objects just to have the arrangement step of the test pass without errors - see here for more details)
Upvotes: 2