Unit testing private functions in Silverlight - c#

Does anyone know how to test private functions in a Silverlight Unit Test project? The *_Accessor objects don’t seem to be available that are their in a normal unit testing project.

You cannot unit-test private functions. You have 3 options:
You can make those functions 'public' and test them,
You make them 'internal' and add the InternalsVisibleTo attribute in the assembly file.
You create a public or internal method that calls your private methods, and test those.
Unit testing is usually done to test the interface of classes to the outside world. Unit testing private methods is not recommended.

The answer by #sbenderli is correct.
But, I have my reservations about making private methods internal just to unit test them. Making a method internal is like making it public for that assembly.
Instead a better way would be to make the method protected and create a dummy class in your test assembly by inheriting from the class under test and then creating a public method which calls the protected method. Now you test the public method of the fake class.

If you have a genuine need to test private methods, then your architecture is in some way broken.

The open source framework Impromptu-Interface is able to expose private members using the DLR. The unit test for this feature are passing on Silverlight.

Related

Unit test a singleton class with MSTest

I want to test my class EventTextsDB that is a singleton, using MSTest in .NET 6.
I first thought about using AppDomain, but they basically were removed in .NET 5+ (https://learn.microsoft.com/en-us/dotnet/core/porting/net-framework-tech-unavailable#application-domains)
Then I found Unit test singletons, but by calling the private constructor via reflection I still cannot test the static Create() and static Delete() methods in the class, because they set the static EventTextsDB Instance property.
I could use ordered unit tests, but this would require a lot of work because I would have to order all tests that used this class. Not many tests use or test this class yet, but many do with a similar class LanguageDB, at which I want to apply the same solution that I am looking for.
I have read somewhere on stackoverflow or MSDN, that each test assembly runs isolated (in different AppDomain, if they still exist?), but I don't want to create 10 new test assemblies just for 10 tests of this class.
How can I test my singleton class?

Skipping private methods during unit test C#

public bool A (UserRequest foo)
{
ClientRequest boo = B(foo); //Mapping local model to client model
C(boo);
return result;
}
I want to write an unit test for method A to test method B but I don't want my unit test to call method C. Method C is a private method but it makes calls to a third party client. I am unable to setup method C in my Unit Test since the type "ClientRequest" doesn't have a reference in the test case assembly. How can this be implemented without adding a reference of the client dll to my test assembly as well. How to skip calling method C ?
C is a private method
Things are private for a reason. They are implementation details to which consuming code shouldn't be coupled. And unit tests are consuming code.
it makes calls to a third party client
Therein lies the problem with your unit tests. Don't try to break apart the class being tested, digging into its internals and ultimately modifying what it's doing and as a result invalidating the tests in the first place.
Instead, isolate and mock the dependency. Somewhere in C() this class has an external dependency. Instead of obscuring that dependency deep within the class, wrap it in an interface/implementation and provide that implementation to the class. (This is called Dependency Injection. There are frameworks which provide rich functionality around the concept, but the concept itself can be achieved manually for simple cases as well.)
So when application code uses this class, instances are provided with an implementation of the dependency which calls the external service. And when unit tests use this class, instances are provided with a mock implementation that pretends to call the external service.
Then your tests can include mocking the results of that service as well, triggering controlled failure responses to test how the class handles them.

How to unit test methods dependent on static methods in C#?

A method in the service which I'm unit testing is calling a static method that is present in another service.
I'm new to unit testing and have no idea how to mock these kinda dependencies. Please suggest!
There is already a thread here about this topic.
In fact it is not possible to create a service facade (Mock) for static methods.
My suggestion here is to refactor your code in that way that you make your class non static and create an interface for it. Than you can inject your dependency class in the normal system via IOC and in the unit test you can create a mock with frameworks like Moq or Rhinomocks.

Moq how do you test internal methods?

Told by my boss to use Moq and that is it.
I like it but it seems that unlike MSTest or mbunit etc... you cannot test internal methods
So I am forced to make public some internal implementation in my interface so that i can test it.
Am I missing something?
Can you test internal methods using Moq?
Thanks a lot
You can use the InternalsVisibleTo attribute to make the methods visible to Moq.
http://geekswithblogs.net/MattRobertsBlog/archive/2008/12/16/how-to-make-a-quotprotectedquot-method-available-for-quotpartialquot-mocking-and-again.aspx
There is nothing wrong with making the internals visible to other classes for testing. If you need to test the internals of a class, by all means do so. Just because the methods are not public does not mean you should ignore them and test only the public ones. A well designed application actually will have a majority of the code encapsulated within your classes in such a way that they are not public. So ignoring the non-public methods in your testing is a big mistake IMHO. One of the beauties of unit testing is that you test all the parts of your code, no matter how small and when your tests are all up and running at 100% it is a very reasonable assumption that when all these parts are put together, your application will work properly for the end user. Of course verifying that latter part is where integration level tests come in - which is a different discussion. So test away!!!
If you have many code that isn't tested by the public methods, you probably have code that should be moved to another classes.
As said in another answer, you can use the InternalsVisibleTo attribute for that. But that doesn't mean you should do it.
From my point of view Mocking should be used to mock up some behavior that we are dependent on but are not setting out to test. Hence:
Q: Am I missing something?
- No you're not missing anything, MOQ is missing the ability to mock private behaviors.
Q: Can you test internal methods using Moq?
- If the result of the private behavior is visible publicly, then yes you can test the internal method but it's not because of Moq that you can test them. I would like to make a point here is that Mock is not the ability to test but rather the ability to similar behaviors that we are not testing but depend on.
C: A main benefit with TDD is that your code becomes easy to change. If you start testing internals, then the code becomes rigid and hard to change
- I don't agree with this comment for 2 main reasons:
1: It is not a beginner misconception, as TDD is not just about the ability to code faster but also better quality code. Hence the more test we can do the better.
2: It doesn't make the code anymore harder to change if you can somehow can test the internal methods.
Your initial presumption that it is necessary to test internal method is a common beginners misconception about unit testing.
Granted, there may exist cases where private methods should be tested in isolation, but the 99% common case is that the private methods are being tested implicitly because they make the public methods pass their tests. The public methods call the private methods.
Private methods are there for a reason. If they do not result in external testable behaviour, then you don't need them.
Do any of your public tests fail if you just flat out delete them? If yes, then they are already being tested. If not, then why do you need them? Find out what you need them for and then express that in a test against the public interface.
A main benefit with TDD is that your code becomes easy to change. If you start testing internals, then the code becomes rigid and hard to change.
InternalsVisibleTo is your friend for testing internals.
Remember to sign your assemblies and you're safe.

Accessing internal members via System.Reflection?

I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is:
FieldInfo[] _fields =
typeof(ButtonedForm.TitleButton).GetFields(
BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.DeclaredOnly);
Console.WriteLine("{0} fields:", _fields.Length);
foreach (FieldInfo fi in _fields)
{
Console.WriteLine(fi.Name);
}
This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?
It would be more appropriate to use the InternalsVisibleTo attribute to grant access to the internal members of the assembly to your unit test assembly.
Here is a link with some helpful additional info and a walk through:
The Wonders Of InternalsVisibleTo
To actually answer your question... Internal and protected are not recognized in the .NET Reflection API. Here is a quotation from MSDN:
The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.
Adding the InternalsVisibleTo assembly level attribute to your main project, with the Assembly name of thre test project should make internal members visible.
For example add the following to your assembly outside any class:
[assembly: InternalsVisibleTo("AssemblyB")]
Or for a more specific targeting:
[assembly:InternalsVisibleTo("AssemblyB, PublicKey=32ab4ba45e0a69a1")]
Note, if your application assembly has a strong name, your test assembly will also need to be strongly named.
Your code is only showing fields - so I'd hope it wouldn't show any internal members, as fields should always be private IMO. (With the potential exception of constants.)
Does ButtonedForm.TitleButton actually have any non-private fields? If you're trying to find internal methods then obviously you need to be calling GetMethods (or GetMembers) to get at them.
As others have suggested, InternalsVisibleTo is very handy for testing (and almost solely for testing!). As for whether you should be testing internal methods - I certainly find it useful to be able to do so. I don't regard unit testing as being exclusively black-box testing. Often when you know that public functionality is implemented using a few internal methods connected in a simple way, it's easier to do thorough testing of each of the internal methods and some "pseudo-integration" tests on the public method.
I think you need to ask whether you should write unit tests for private methods? If you write unit tests for your public methods, with a 'reasonable' code coverage, aren't you already testing any private methods that need to be called as a result?
Tying tests to private methods will make the tests more brittle. You should be able to change the implementation of any private methods without breaking any tests.
Refs:
http://weblogs.asp.net/tgraham/archive/2003/12/31/46984.aspx
http://richardsbraindump.blogspot.com/2008/08/should-i-unit-test-private-methods.html
http://junit.sourceforge.net/doc/faq/faq.htm#tests_11
Link
A justification for using the InternalsVisible is under my circumstances. We purchase the source code to a Chart Control. We have found where we need to make some modifications to that source control and compile our own version. Now to ensure we did not break anything, there are some unit tests I need to write that need access to some internal fields.
This is a perfect case where the InternalsVisible makes sense.
I was wondering, though, what do you do if you do not have access to the source? How could you get to an internal field? .Net Reflector can see that code, but I guess it is just looking at the IL.

Categories

Resources