Unit testing private methods in C#
Visual Studio allows unit testing of private methods via an automatically generated accessor class. I have written a test of a private method that compiles successfully, but it fails at runtime. A fairly minimal version of the code and the test is:
//in project MyProj
class TypeA
{
private List<TypeB> myList = new List<TypeB>();
private class TypeB
{
public TypeB()
{
}
}
public TypeA()
{
}
private void MyFunc()
{
//processing of myList that changes state of instance
}
}
//in project TestMyProj
public void MyFuncTest()
{
TypeA_Accessor target = new TypeA_Accessor();
//following line is the one that throws exception
target.myList.Add(new TypeA_Accessor.TypeB());
target.MyFunc();
//check changed state of target
}
The runtime error is:
Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'.
According to intellisense - and hence I guess the compiler - target is of type TypeA_Accessor. But at runtime it is of type TypeA, and hence the list add fails.
Is there any way I can stop this error? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").
c# unit-testing
add a comment |
Visual Studio allows unit testing of private methods via an automatically generated accessor class. I have written a test of a private method that compiles successfully, but it fails at runtime. A fairly minimal version of the code and the test is:
//in project MyProj
class TypeA
{
private List<TypeB> myList = new List<TypeB>();
private class TypeB
{
public TypeB()
{
}
}
public TypeA()
{
}
private void MyFunc()
{
//processing of myList that changes state of instance
}
}
//in project TestMyProj
public void MyFuncTest()
{
TypeA_Accessor target = new TypeA_Accessor();
//following line is the one that throws exception
target.myList.Add(new TypeA_Accessor.TypeB());
target.MyFunc();
//check changed state of target
}
The runtime error is:
Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'.
According to intellisense - and hence I guess the compiler - target is of type TypeA_Accessor. But at runtime it is of type TypeA, and hence the list add fails.
Is there any way I can stop this error? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").
c# unit-testing
You need an accessor for private class TypeB. Accessor TypeA_Accessor provides access to private and protected methods of TypeA. However TypeB is not a method. It is a class.
– Dima
Apr 8 '13 at 22:13
Accessor provides access to private/protected methods, members, properties, and events. It does not provide access to private/protected classes within your class. And private/protected classes (TypeB) are intended to be used only by methods of owning class (TypeA). So basically you are trying to add private class (TypeB) from outside of TypeA to "myList" which is private. Since you are using accessor, there is no problem to access myList. However you can not use TypeB through accessor. Posiible solution would be to move TypeB outside of TypeA. But it can break your design.
– Dima
Apr 8 '13 at 22:23
Feel that testing private methods should be done by the following stackoverflow.com/questions/250692/…
– nate_weldon
Aug 30 '17 at 17:26
add a comment |
Visual Studio allows unit testing of private methods via an automatically generated accessor class. I have written a test of a private method that compiles successfully, but it fails at runtime. A fairly minimal version of the code and the test is:
//in project MyProj
class TypeA
{
private List<TypeB> myList = new List<TypeB>();
private class TypeB
{
public TypeB()
{
}
}
public TypeA()
{
}
private void MyFunc()
{
//processing of myList that changes state of instance
}
}
//in project TestMyProj
public void MyFuncTest()
{
TypeA_Accessor target = new TypeA_Accessor();
//following line is the one that throws exception
target.myList.Add(new TypeA_Accessor.TypeB());
target.MyFunc();
//check changed state of target
}
The runtime error is:
Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'.
According to intellisense - and hence I guess the compiler - target is of type TypeA_Accessor. But at runtime it is of type TypeA, and hence the list add fails.
Is there any way I can stop this error? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").
c# unit-testing
Visual Studio allows unit testing of private methods via an automatically generated accessor class. I have written a test of a private method that compiles successfully, but it fails at runtime. A fairly minimal version of the code and the test is:
//in project MyProj
class TypeA
{
private List<TypeB> myList = new List<TypeB>();
private class TypeB
{
public TypeB()
{
}
}
public TypeA()
{
}
private void MyFunc()
{
//processing of myList that changes state of instance
}
}
//in project TestMyProj
public void MyFuncTest()
{
TypeA_Accessor target = new TypeA_Accessor();
//following line is the one that throws exception
target.myList.Add(new TypeA_Accessor.TypeB());
target.MyFunc();
//check changed state of target
}
The runtime error is:
Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'.
According to intellisense - and hence I guess the compiler - target is of type TypeA_Accessor. But at runtime it is of type TypeA, and hence the list add fails.
Is there any way I can stop this error? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").
c# unit-testing
c# unit-testing
asked Feb 3 '12 at 1:50
junichirojunichiro
1,60021122
1,60021122
You need an accessor for private class TypeB. Accessor TypeA_Accessor provides access to private and protected methods of TypeA. However TypeB is not a method. It is a class.
– Dima
Apr 8 '13 at 22:13
Accessor provides access to private/protected methods, members, properties, and events. It does not provide access to private/protected classes within your class. And private/protected classes (TypeB) are intended to be used only by methods of owning class (TypeA). So basically you are trying to add private class (TypeB) from outside of TypeA to "myList" which is private. Since you are using accessor, there is no problem to access myList. However you can not use TypeB through accessor. Posiible solution would be to move TypeB outside of TypeA. But it can break your design.
– Dima
Apr 8 '13 at 22:23
Feel that testing private methods should be done by the following stackoverflow.com/questions/250692/…
– nate_weldon
Aug 30 '17 at 17:26
add a comment |
You need an accessor for private class TypeB. Accessor TypeA_Accessor provides access to private and protected methods of TypeA. However TypeB is not a method. It is a class.
– Dima
Apr 8 '13 at 22:13
Accessor provides access to private/protected methods, members, properties, and events. It does not provide access to private/protected classes within your class. And private/protected classes (TypeB) are intended to be used only by methods of owning class (TypeA). So basically you are trying to add private class (TypeB) from outside of TypeA to "myList" which is private. Since you are using accessor, there is no problem to access myList. However you can not use TypeB through accessor. Posiible solution would be to move TypeB outside of TypeA. But it can break your design.
– Dima
Apr 8 '13 at 22:23
Feel that testing private methods should be done by the following stackoverflow.com/questions/250692/…
– nate_weldon
Aug 30 '17 at 17:26
You need an accessor for private class TypeB. Accessor TypeA_Accessor provides access to private and protected methods of TypeA. However TypeB is not a method. It is a class.
– Dima
Apr 8 '13 at 22:13
You need an accessor for private class TypeB. Accessor TypeA_Accessor provides access to private and protected methods of TypeA. However TypeB is not a method. It is a class.
– Dima
Apr 8 '13 at 22:13
Accessor provides access to private/protected methods, members, properties, and events. It does not provide access to private/protected classes within your class. And private/protected classes (TypeB) are intended to be used only by methods of owning class (TypeA). So basically you are trying to add private class (TypeB) from outside of TypeA to "myList" which is private. Since you are using accessor, there is no problem to access myList. However you can not use TypeB through accessor. Posiible solution would be to move TypeB outside of TypeA. But it can break your design.
– Dima
Apr 8 '13 at 22:23
Accessor provides access to private/protected methods, members, properties, and events. It does not provide access to private/protected classes within your class. And private/protected classes (TypeB) are intended to be used only by methods of owning class (TypeA). So basically you are trying to add private class (TypeB) from outside of TypeA to "myList" which is private. Since you are using accessor, there is no problem to access myList. However you can not use TypeB through accessor. Posiible solution would be to move TypeB outside of TypeA. But it can break your design.
– Dima
Apr 8 '13 at 22:23
Feel that testing private methods should be done by the following stackoverflow.com/questions/250692/…
– nate_weldon
Aug 30 '17 at 17:26
Feel that testing private methods should be done by the following stackoverflow.com/questions/250692/…
– nate_weldon
Aug 30 '17 at 17:26
add a comment |
9 Answers
9
active
oldest
votes
Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.
If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.
One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.
This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.
198
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
7
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
6
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
12
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
16
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
|
show 22 more comments
You can use PrivateObject Class
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal, expectedVal);
18
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
4
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
16
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
8
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
2
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
|
show 13 more comments
“There is nothing called as standard or best practice, probably they are just popular opinions”.
Same holds true for this discussion as well.

It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.
If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.
add a comment |
Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.
In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.
[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
#pragma warning disable CS0628 //invalid because of InternalsVisibleTo
public sealed class MyWatch
{
Func<DateTime> _getNow = delegate () { return DateTime.Now; };
//construktor for testing purposes where you "can change DateTime.Now"
internal protected MyWatch(Func<DateTime> getNow)
{
_getNow = getNow;
}
public MyWatch()
{
}
}
}
And unit test:
namespace MyCode.UnitTests
{
[TestMethod]
public void TestminuteChanged()
{
//watch for traviling in time
DateTime baseTime = DateTime.Now;
DateTime nowforTesting = baseTime;
Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };
MyWatch myWatch= new MyWatch(_getNowForTesting );
nowforTesting = baseTime.AddMinute(1); //skip minute
//TODO check myWatch
}
[TestMethod]
public void TestStabilityOnFebruary29()
{
Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
MyWatch myWatch= new MyWatch(_getNowForTesting );
//component does not crash in overlap year
}
}
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
1
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
21
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
4
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
add a comment |
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
call methodsstatic and non static ?
– Kiquenet
Jun 13 '18 at 13:35
1
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
add a comment |
You can make a wrapper class around the class that contains the private method you want to test.
This wrapper class contains a public method called Call_MyPrivateFunction and which in turn calls the private function of its base class.
Please note that the access level of the method schould change to [protected]
Code Example:
public class Order
{
public int Quantity { get; set; }
protected bool OrderIsBig ()
{
//This is the method we want to test. It needs to be protected in stead of private. Else... no cigar
return Quantity > 100;
}
}
//Use this wrapper class in your unit test.
public class FakeOrder : Order
{
public bool Call_OrderIsBig()
{
//This makes the actual call to the protected method "OrderIsBig"
return OrderIsBig();
}
}
The unit test code could look like:
FakeOrder order = new FakeOrder();
order.Quantity = 200;
bool isBig = order.Call_OrderIsBig(); //Make a call to a public method of the FakeOrder class which in turn makes a call to the protected method.
5
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
add a comment |
TL;DR: Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)
It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.
We has the following scenario:
Class A
+ outputFile: Stream
- _someLogic(arg1, arg2)
We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes
Class A1
+ A1(logicHandler: A2) # take A2 for handle logic
+ outputFile: Stream
Class A2
+ someLogic(arg1, arg2)
In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.
add a comment |
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
add a comment |
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9122708%2funit-testing-private-methods-in-c-sharp%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.
If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.
One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.
This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.
198
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
7
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
6
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
12
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
16
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
|
show 22 more comments
Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.
If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.
One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.
This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.
198
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
7
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
6
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
12
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
16
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
|
show 22 more comments
Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.
If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.
One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.
This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.
Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.
If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.
One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.
This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.
edited May 10 '17 at 21:52
answered Feb 3 '12 at 1:53
Keith NicholasKeith Nicholas
33.8k1470131
33.8k1470131
198
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
7
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
6
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
12
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
16
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
|
show 22 more comments
198
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
7
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
6
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
12
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
16
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
198
198
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
I disagree. In OOD, private methods and properties are an intrinsic way to not repeat yourself (en.wikipedia.org/wiki/Don%27t_repeat_yourself). The idea behind black box programming and encapsulation is to hide technical details from the subscriber. So it is indeed necessary to have non-trivial private methods and properties in your code. And if it's non-trivial, it needs to be tested.
– AxD
Aug 25 '16 at 23:48
7
7
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
its not intrinsic, some OO languages don't have private methods, private properties can contain objects with public interfaces which can be tested.
– Keith Nicholas
Aug 26 '16 at 0:28
6
6
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
The point of this advice, is if you your object do one thing, and are DRY, then there's often little reason to have private methods. Often private methods do something the object isn't really responsible for but is quite useful, if non trivial, then it generally is another object as its likely violating SRP
– Keith Nicholas
Aug 26 '16 at 0:31
12
12
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
Wrong. You may want to use private methods to avoid code duplication. Or for validation. Or for many other purposes which the Public world should not know about.
– Jorj
Mar 8 '17 at 6:46
16
16
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
When you've been dumped on an OO codebase so horrifically designed and asked to "incrementally improve it", it was a disappointment to find I couldn't had some first tests for private methods. Yeh, perhaps in the textbooks these methods wouldn't be here, but in the real world we have users who have product requirements. I can't just do a massive "Look at ma clean code" refactoring without getting some tests in the project to build off. Feels like another instance of forcing practising programmers into avenues that naively seem good, but fail to take account of real messy shit.
– dune.rocks
Apr 24 '17 at 9:51
|
show 22 more comments
You can use PrivateObject Class
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal, expectedVal);
18
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
4
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
16
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
8
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
2
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
|
show 13 more comments
You can use PrivateObject Class
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal, expectedVal);
18
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
4
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
16
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
8
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
2
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
|
show 13 more comments
You can use PrivateObject Class
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal, expectedVal);
You can use PrivateObject Class
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal, expectedVal);
edited Jan 17 '18 at 14:39
DaveInCaz
3,02631635
3,02631635
answered Mar 25 '13 at 4:10
ScuttleScuttle
4,954289
4,954289
18
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
4
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
16
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
8
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
2
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
|
show 13 more comments
18
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
4
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
16
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
8
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
2
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
18
18
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
This is the correct answer, now that Microsoft has added PrivateObject.
– Zoey
Jan 27 '14 at 11:57
4
4
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
Good answer but please note that the PrivateMethod needs to be "protected" in stead of "private".
– HerbalMart
Mar 13 '14 at 11:54
16
16
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
@HerbalMart: Perhaps I misunderstand you, but if you are suggesting that PrivateObject can only access protected members and not private ones, you are mistaken.
– kmote
Jun 18 '14 at 18:37
8
8
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
@JeffPearce For static methods you can use "PrivateType pt = new PrivateType(typeof(MyClass));", and then call InvokeStatic on the pt object as you would call Invoke on a private object.
– Steve Hibbert
May 2 '17 at 9:45
2
2
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
@Kiquenet obj.Invoke("TestMethod", toPassIn); The method takes an array of objects as params
– R2D2
Jun 27 '18 at 7:04
|
show 13 more comments
“There is nothing called as standard or best practice, probably they are just popular opinions”.
Same holds true for this discussion as well.

It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.
If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.
add a comment |
“There is nothing called as standard or best practice, probably they are just popular opinions”.
Same holds true for this discussion as well.

It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.
If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.
add a comment |
“There is nothing called as standard or best practice, probably they are just popular opinions”.
Same holds true for this discussion as well.

It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.
If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.
“There is nothing called as standard or best practice, probably they are just popular opinions”.
Same holds true for this discussion as well.

It all depends on what you think is a unit , if you think UNIT is a class then you will only hit the public method. If you think UNIT is lines of code hitting private methods will not make you feel guilty.
If you want to invoke private methods you can use "PrivateObject" class and call the invoke method. You can watch this indepth youtube video ( http://www.youtube.com/watch?v=Vq6Gcs9LrPQ ) which shows how to use "PrivateObject" and also discusses if testing of private methods are logical or not.
answered Aug 4 '13 at 14:09
Shivprasad KoiralaShivprasad Koirala
16.4k65956
16.4k65956
add a comment |
add a comment |
Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.
In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.
[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
#pragma warning disable CS0628 //invalid because of InternalsVisibleTo
public sealed class MyWatch
{
Func<DateTime> _getNow = delegate () { return DateTime.Now; };
//construktor for testing purposes where you "can change DateTime.Now"
internal protected MyWatch(Func<DateTime> getNow)
{
_getNow = getNow;
}
public MyWatch()
{
}
}
}
And unit test:
namespace MyCode.UnitTests
{
[TestMethod]
public void TestminuteChanged()
{
//watch for traviling in time
DateTime baseTime = DateTime.Now;
DateTime nowforTesting = baseTime;
Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };
MyWatch myWatch= new MyWatch(_getNowForTesting );
nowforTesting = baseTime.AddMinute(1); //skip minute
//TODO check myWatch
}
[TestMethod]
public void TestStabilityOnFebruary29()
{
Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
MyWatch myWatch= new MyWatch(_getNowForTesting );
//component does not crash in overlap year
}
}
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
1
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
21
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
4
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
add a comment |
Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.
In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.
[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
#pragma warning disable CS0628 //invalid because of InternalsVisibleTo
public sealed class MyWatch
{
Func<DateTime> _getNow = delegate () { return DateTime.Now; };
//construktor for testing purposes where you "can change DateTime.Now"
internal protected MyWatch(Func<DateTime> getNow)
{
_getNow = getNow;
}
public MyWatch()
{
}
}
}
And unit test:
namespace MyCode.UnitTests
{
[TestMethod]
public void TestminuteChanged()
{
//watch for traviling in time
DateTime baseTime = DateTime.Now;
DateTime nowforTesting = baseTime;
Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };
MyWatch myWatch= new MyWatch(_getNowForTesting );
nowforTesting = baseTime.AddMinute(1); //skip minute
//TODO check myWatch
}
[TestMethod]
public void TestStabilityOnFebruary29()
{
Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
MyWatch myWatch= new MyWatch(_getNowForTesting );
//component does not crash in overlap year
}
}
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
1
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
21
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
4
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
add a comment |
Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.
In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.
[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
#pragma warning disable CS0628 //invalid because of InternalsVisibleTo
public sealed class MyWatch
{
Func<DateTime> _getNow = delegate () { return DateTime.Now; };
//construktor for testing purposes where you "can change DateTime.Now"
internal protected MyWatch(Func<DateTime> getNow)
{
_getNow = getNow;
}
public MyWatch()
{
}
}
}
And unit test:
namespace MyCode.UnitTests
{
[TestMethod]
public void TestminuteChanged()
{
//watch for traviling in time
DateTime baseTime = DateTime.Now;
DateTime nowforTesting = baseTime;
Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };
MyWatch myWatch= new MyWatch(_getNowForTesting );
nowforTesting = baseTime.AddMinute(1); //skip minute
//TODO check myWatch
}
[TestMethod]
public void TestStabilityOnFebruary29()
{
Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
MyWatch myWatch= new MyWatch(_getNowForTesting );
//component does not crash in overlap year
}
}
Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.
In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.
[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
#pragma warning disable CS0628 //invalid because of InternalsVisibleTo
public sealed class MyWatch
{
Func<DateTime> _getNow = delegate () { return DateTime.Now; };
//construktor for testing purposes where you "can change DateTime.Now"
internal protected MyWatch(Func<DateTime> getNow)
{
_getNow = getNow;
}
public MyWatch()
{
}
}
}
And unit test:
namespace MyCode.UnitTests
{
[TestMethod]
public void TestminuteChanged()
{
//watch for traviling in time
DateTime baseTime = DateTime.Now;
DateTime nowforTesting = baseTime;
Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };
MyWatch myWatch= new MyWatch(_getNowForTesting );
nowforTesting = baseTime.AddMinute(1); //skip minute
//TODO check myWatch
}
[TestMethod]
public void TestStabilityOnFebruary29()
{
Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
MyWatch myWatch= new MyWatch(_getNowForTesting );
//component does not crash in overlap year
}
}
edited Jul 27 '18 at 10:40
Tomas Kubes
12.1k1271103
12.1k1271103
answered Feb 3 '12 at 2:05
JeffJeff
75368
75368
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
1
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
21
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
4
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
add a comment |
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
1
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
21
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
4
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
I'm not sure I understand. InternalsVisibleToAttribute makes methods and attributes which are marked as "internal" accessible, but my fields and methods are "private". Are you suggesting I change things from being private to internal? I think I misunderstand.
– junichiro
Feb 3 '12 at 2:36
1
1
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
Yes, that's what I'm suggesting. It's a little bit "hacky", but at least they're not "public".
– Jeff
Mar 15 '12 at 1:04
21
21
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
This is a wonderful answer just because it doesn't say "don't test private methods" but yes, it's quite "hacky". I wish there was a solution. IMO it's bad to say "private methods shouldn't be tested" because the way I see it: it's equivalent to "private methods shouldn't be correct".
– MasterMastic
Jun 6 '13 at 17:25
4
4
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
ya ken, I also confused by those who claim that private methods shouldn't be tested in unit test. Public API are the output, but sometimes wrong implementation also give the right output. Or the implementation made some bad side effects, e.g. holding resources that are not necessary, referencing objects preventing it from being collected by gc...etc. Unless they provide other test that can cover the private methods rather than unit test, otherwise I would consider that they can't maintain a 100% tested code.
– mr.Pony
Jun 10 '13 at 9:59
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
I agree with MasterMastic. This should be the accepted answer.
– XDS
Nov 6 '18 at 12:21
add a comment |
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
call methodsstatic and non static ?
– Kiquenet
Jun 13 '18 at 13:35
1
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
add a comment |
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
call methodsstatic and non static ?
– Kiquenet
Jun 13 '18 at 13:35
1
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
add a comment |
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
answered May 23 '17 at 1:49
Jack DavidsonJack Davidson
1,33111017
1,33111017
call methodsstatic and non static ?
– Kiquenet
Jun 13 '18 at 13:35
1
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
add a comment |
call methodsstatic and non static ?
– Kiquenet
Jun 13 '18 at 13:35
1
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
call methods static and non static ?– Kiquenet
Jun 13 '18 at 13:35
call methods static and non static ?– Kiquenet
Jun 13 '18 at 13:35
1
1
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
The downside of reflection-reliant methods is that they tend to break when you rename methods using R#. It might not be a big problem on small projects but on huge code-bases it becomes kinda nagging to have unit tests breaking in such a fashion and then having to go around and quick-fix them. In this sense I my money goes to Jeff's answer.
– XDS
Nov 6 '18 at 12:23
add a comment |
You can make a wrapper class around the class that contains the private method you want to test.
This wrapper class contains a public method called Call_MyPrivateFunction and which in turn calls the private function of its base class.
Please note that the access level of the method schould change to [protected]
Code Example:
public class Order
{
public int Quantity { get; set; }
protected bool OrderIsBig ()
{
//This is the method we want to test. It needs to be protected in stead of private. Else... no cigar
return Quantity > 100;
}
}
//Use this wrapper class in your unit test.
public class FakeOrder : Order
{
public bool Call_OrderIsBig()
{
//This makes the actual call to the protected method "OrderIsBig"
return OrderIsBig();
}
}
The unit test code could look like:
FakeOrder order = new FakeOrder();
order.Quantity = 200;
bool isBig = order.Call_OrderIsBig(); //Make a call to a public method of the FakeOrder class which in turn makes a call to the protected method.
5
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
add a comment |
You can make a wrapper class around the class that contains the private method you want to test.
This wrapper class contains a public method called Call_MyPrivateFunction and which in turn calls the private function of its base class.
Please note that the access level of the method schould change to [protected]
Code Example:
public class Order
{
public int Quantity { get; set; }
protected bool OrderIsBig ()
{
//This is the method we want to test. It needs to be protected in stead of private. Else... no cigar
return Quantity > 100;
}
}
//Use this wrapper class in your unit test.
public class FakeOrder : Order
{
public bool Call_OrderIsBig()
{
//This makes the actual call to the protected method "OrderIsBig"
return OrderIsBig();
}
}
The unit test code could look like:
FakeOrder order = new FakeOrder();
order.Quantity = 200;
bool isBig = order.Call_OrderIsBig(); //Make a call to a public method of the FakeOrder class which in turn makes a call to the protected method.
5
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
add a comment |
You can make a wrapper class around the class that contains the private method you want to test.
This wrapper class contains a public method called Call_MyPrivateFunction and which in turn calls the private function of its base class.
Please note that the access level of the method schould change to [protected]
Code Example:
public class Order
{
public int Quantity { get; set; }
protected bool OrderIsBig ()
{
//This is the method we want to test. It needs to be protected in stead of private. Else... no cigar
return Quantity > 100;
}
}
//Use this wrapper class in your unit test.
public class FakeOrder : Order
{
public bool Call_OrderIsBig()
{
//This makes the actual call to the protected method "OrderIsBig"
return OrderIsBig();
}
}
The unit test code could look like:
FakeOrder order = new FakeOrder();
order.Quantity = 200;
bool isBig = order.Call_OrderIsBig(); //Make a call to a public method of the FakeOrder class which in turn makes a call to the protected method.
You can make a wrapper class around the class that contains the private method you want to test.
This wrapper class contains a public method called Call_MyPrivateFunction and which in turn calls the private function of its base class.
Please note that the access level of the method schould change to [protected]
Code Example:
public class Order
{
public int Quantity { get; set; }
protected bool OrderIsBig ()
{
//This is the method we want to test. It needs to be protected in stead of private. Else... no cigar
return Quantity > 100;
}
}
//Use this wrapper class in your unit test.
public class FakeOrder : Order
{
public bool Call_OrderIsBig()
{
//This makes the actual call to the protected method "OrderIsBig"
return OrderIsBig();
}
}
The unit test code could look like:
FakeOrder order = new FakeOrder();
order.Quantity = 200;
bool isBig = order.Call_OrderIsBig(); //Make a call to a public method of the FakeOrder class which in turn makes a call to the protected method.
answered Mar 13 '14 at 12:06
HerbalMartHerbalMart
91921546
91921546
5
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
add a comment |
5
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
5
5
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
There is a difference between private and protected
– Przemysław Wrzesiński
Mar 27 '17 at 14:54
add a comment |
TL;DR: Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)
It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.
We has the following scenario:
Class A
+ outputFile: Stream
- _someLogic(arg1, arg2)
We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes
Class A1
+ A1(logicHandler: A2) # take A2 for handle logic
+ outputFile: Stream
Class A2
+ someLogic(arg1, arg2)
In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.
add a comment |
TL;DR: Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)
It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.
We has the following scenario:
Class A
+ outputFile: Stream
- _someLogic(arg1, arg2)
We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes
Class A1
+ A1(logicHandler: A2) # take A2 for handle logic
+ outputFile: Stream
Class A2
+ someLogic(arg1, arg2)
In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.
add a comment |
TL;DR: Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)
It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.
We has the following scenario:
Class A
+ outputFile: Stream
- _someLogic(arg1, arg2)
We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes
Class A1
+ A1(logicHandler: A2) # take A2 for handle logic
+ outputFile: Stream
Class A2
+ someLogic(arg1, arg2)
In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.
TL;DR: Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)
It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.
We has the following scenario:
Class A
+ outputFile: Stream
- _someLogic(arg1, arg2)
We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes
Class A1
+ A1(logicHandler: A2) # take A2 for handle logic
+ outputFile: Stream
Class A2
+ someLogic(arg1, arg2)
In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.
answered Feb 1 '18 at 3:42
o0omycomputero0oo0omycomputero0o
1,27811525
1,27811525
add a comment |
add a comment |
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
add a comment |
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
add a comment |
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
answered Jan 1 at 20:32
CP70CP70
111
111
add a comment |
add a comment |
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
add a comment |
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
add a comment |
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
answered Aug 20 '16 at 2:46
AllenAllen
411614
411614
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9122708%2funit-testing-private-methods-in-c-sharp%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You need an accessor for private class TypeB. Accessor TypeA_Accessor provides access to private and protected methods of TypeA. However TypeB is not a method. It is a class.
– Dima
Apr 8 '13 at 22:13
Accessor provides access to private/protected methods, members, properties, and events. It does not provide access to private/protected classes within your class. And private/protected classes (TypeB) are intended to be used only by methods of owning class (TypeA). So basically you are trying to add private class (TypeB) from outside of TypeA to "myList" which is private. Since you are using accessor, there is no problem to access myList. However you can not use TypeB through accessor. Posiible solution would be to move TypeB outside of TypeA. But it can break your design.
– Dima
Apr 8 '13 at 22:23
Feel that testing private methods should be done by the following stackoverflow.com/questions/250692/…
– nate_weldon
Aug 30 '17 at 17:26