I have a private method like below:
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
how to write the unit test case for this method.
I have a private method like below:
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
how to write the unit test case for this method.
Seems a bit pointless that a method is void but takes a ref
parameter. It would probably make sense to make it return a string:
public class FooBar {
internal string SomeMethod(ref string theStr) {
// Some Implementation
return theStr;
}
}
We also make it internal
and specify InternalVisibleTo
attribute in AssemblyInfo.cs file:
[assembly: InternalsVisibleTo("Test.Assembly")]
This way SomeMethod
will behave as though it's internal (i.e. not visible outside its assembly) except for Test.Assembly, which will see it as public
.
The unit test is pretty trivial (regardless of whether or not it takes a ref
parameter).
[Test]
public void SomeMethodShouldReturnSomething() {
Foobar foobar = new Foobar();
string actual;
foobar.SomeMethod(ref actual);
Assert.AreEqual("I'm the test your tests could smell like", actual);
}
I usually make the method protected and provide a testable class that inherits. For example:
class Foo
{
protected void SomeMethod(ref string theStr) { ... }
...
}
class TestableFoo
{
public void TestableSomeMethod(ref string theStr)
{
base.SomeMethod(...);
}
...
I think you'll find answers that say "you shouldn't test private methods", but there are cases where I've found it to be useful to get at some tricky functionality. But then, I've also found that in these situations it's better to extract the function into it's own separate testable class. ymmv.
Hi Guys,
My Question was how to write the unit test case for the private method which is having the ref parameter.
Some of says that change the implementation, it is not possible. might be i have given some wrong implementation in code snipt but that was not my intension.
Some says that no need to test the private method. but in some scenario, it is required to test those method such as in some safety code.
Answer is: I need to use the reflection and set the setnamedparameterAction from the nunit. i need to specify explicitly that perticular parameter is ref.
If it's that important to test it, maybe you should just make it public and be done with it. (Although I realise that doesn't exactly answer your question).
Not everyone would agree with making something public just for testing, but I think it's better than some of the alternatives.