Home > Software design >  Creating Unit Tests in VS only allowed in Public Classes?
Creating Unit Tests in VS only allowed in Public Classes?

Time:11-05

I am trying to clarify this notification message when trying to create a unit test for my method. The message clearly states that creating a unit test is only supported on a NON-Test project and within a public class OR a public method. I clearly have a public method but the class isn't. So is this just an incorrectly typed error message? Does it actually mean that you need to have both a public class and method?

Note: It works when I try this in a public class, just testing the notification.

Picture of notification message:

CodePudding user response:

To test your class/method, you have to create another project - Testing project. Look at this as it has been another application that uses your classes.

So for example you have 3 projects (for sake of simplicity):

  • Domain - project with models and domain services
  • Console application - application that uses domain project
  • Test... let's say "Testing application" that tests Domain project.

So it points that class that you want to test MUST be available from test project. So it has to be public. You can also use attribute InternalsVisibleTo to make this class available for test project.

CodePudding user response:

Your unit test project must be able to see (public visibility) the method you want to test in order to call it and execute it.

Here is a sample on a WinForm application:

enter image description here

You can clone the whole solution here: unit test on private method

Solution downloadable here: visual Studio solution on GitHub

  • Related