Is it possible to unit test a private class? I have something like
public class ClassA: ClassB
{
private class ClassX: ClassY
{
public static int TestMethod(int numberA, int numberB)
{
return numberA + numberB
}
}
}
I'd like to test the "TestMethod" but can't access it. I tried to create new instance for the private ClassX using Class A and Class Y but it won't let me access the "TestMethod"
It is not a good practice to test private members. They should be tested using pubic exposed members.
However, If you are using MSTest, You can use accessors.
If you are using other test frameworks, you can leverage reflection.
The above are applicable in .NET. I have no idea how to achieve the same in other languages (in case you are asking for java/other language).
There should be a public method somewhere that calls the method in your private class. You should unit test that method. If you can't get to your private method through a public interface, then there is probably no need for the private method to begin with.
Related
I want to create a spy using NSubstitute, but can't find out how after a lot of googling and reading the docs.
The idea would be to have the substitute with an overriden method that I could use to monitor received calls, etc. as usual with mocking. But how to achieve this with NSubstitute?
I would prefer not to relax neither protected nor abstract modifiers.
Here's what I would like to do:
[Test]
public void Items_Add_shouldCall_ItemAddedMethod()
{
var sut = Substitute.For<ItemsRepository>();
// how to configure???
sut.Items.Add(Substitute.For<IItem>());
sut.Received().ItemAdded(); // currently cannot do this
// ...
public abstract class ItemsRepository
{
public ObservableCollection<IItem> Items { get; set; }
= new ObservableCollection<IItem>();
// ...
protected abstract void ItemAdded();
}
The NSubstitute API relies on calling a method to configure it with Returns or check Received() calls, which means for standard use we can only work with calls that can be invoked via the public API (which excludes protected and private members). There is no problem with the abstract part of your question; it is fine to use NSubstitute with accessible abstract members.
Even though C#, by design, prevents us from interacting directly with protected members, NSubstitute still records calls made to these members. We can check these by using the "unofficial" .ReceivedCalls() extension:
public abstract class ItemsRepository {
public virtual void Add(int i) { ItemAdded(); }
protected abstract void ItemAdded();
}
public class Fixture {
[Fact]
public void CheckProtectedCall() {
var sub = Substitute.For<ItemsRepository>();
sub.When(x => x.Add(Arg.Any<int>())).CallBase();
sub.Add(42);
var called = sub.ReceivedCalls().Select(x => x.GetMethodInfo().Name);
Assert.Contains("ItemAdded", called);
}
}
Other options include creating a derived class (as #Nkosi pointed out), or making the member internal instead of protected and using InternalsVisibleTo to make the member accessible to your test code (if you do the latter I recommend installing NSubstitute.Analyzer to help ensure this is configured correctly).
I have a singleton class "Fake"
public class Fake{
private static Fake instance;
private Fake(){
}
public static Fake getInstance(){
if(instance == null)
instance = new Fake();
return instance;
}
public String getTestString(String s){
return s;
}
}
I want to create a mock Fake object so I can mock method calls to non-static method getTestString(String s). I have used both Mockito and PowerMock (Mockito extension) in the way that comes below.
//using Mockito
Fake fake = Mockito.mock(Fake.class);
//using PowerMock
Fake fake = mock(Fake.class);
In both cases, as the code is attempting to mock a singleton (with a private constructor) I expect an exception to occur, but it just normally works. I suspect that there is something wrong with it and maybe it is not working actually.
Mocking doesn't instantiate a class, it creates a proxy for it. Having a private constructor or a constructor with parameters doesn't make a difference.
The behavior you're seeing is normal and expected.
By using mocking, it means you are not testing the class itself, but want to dictate the behavior of the class so that it performs in an arbitrary way you want.
The mock is only useful when you are trying to test some other class which has a dependency on the class being mocked.
In your case, if you want to test the class being a Singleton, you should test on an REAL instance rather than a mock of the class.
Moreover, your method:
public String getTestString(String s){
return s;
}
always returns the String you passed in, this does not look right to me and not sure what you are trying to do here.
Because you're not ever creating an actual instance of Fake, only an instance of a proxy that fulfills Fake's interface, the mock is succeeding.
Separately, regardless of whether Fake's constructor is private, Mockito cannot stub or verify static methods. If your real goal is to override getInstance, you'll need to do so with PowerMock.
However, by adjusting your system-under-test, you can skip Powermock and test your method with Mockito directly:
public class YourSystemUnderTest {
public int yourMethodUnderTest() {
return yourMethodUnderTest(Fake.getInstance());
}
/** Visible for testing. */
int yourMethodUnderTest(Fake fake) {
// ...
}
}
public class YourTest {
#Test
public void yourMethodShouldReturn42() {
Fake fake = mock(Fake.class);
YourSystemUnderTest systemUnderTest = new YourSystemUnderTest();
assertEquals(42, systemUnderTest.yourMethodUnderTest(fake));
}
}
It's even easier if YourSystemUnderTest takes a Fake instance in its constructor, because then you can set up the reference to the Fake instance once in a setUp() or #Before method.
I'm confused regarding inheritance when googletesting. I have a class A that has protected attributes. If I want to access those i have to extend that class, but at the same time i also need to extend public ::testing::Test for the sole purpose of gtest.
What is the most elegant solution to this problem?
Also I'm trying to avoid #define protected public
To avoid leaving traces of tests in the tested class use multiple-inheritance with a fixture:
class ToBeTested
{
protected:
bool SensitiveInternal(int p1, int p2); // Still needs testing
}
// Google-test:
class ToBeTestedFixture : public ToBeTested, public testing::Test
{
// Empty - bridge to protected members for unit-testing
}
TEST_F(ToBeTestedFixture, TestSensitive)
{
ASSERT_TRUE(SensitiveInternal(1, 1));
ASSERT_FALSE(SensitiveInternal(-1, -1));
}
There is a FRIEND_TEST declaration, which is used in the header of tested class. Basically it defines the test as a friend of the class. In my use case, we disable all test includes when compiling in RELEASE mode, so it doesn't do any harm the real executable.
Have a look at this
This question already has answers here:
Unit testing accessors (getters and setters)
(3 answers)
Closed 8 years ago.
Are there best practices for testing classes that use inheritance?
For example if I have a class BaseNode
public class BaseNode
{
int testInt;//attribute
//assume getters and setters and constructor
public function somethingComplicated()
{
//put complex code here
}
}
and another class called InputNode that inherits from BaseNode.
public class InputNode extends BaseNode
{
int secondTest;//attribute
//assume getters and setters and constructor
}
If I write getters and setters for both classes, what would I need to test?
Do you really have to write tests for getTestInt() in both the BaseNode and the InputNode classes?
If you write a test for getTestInt() in the InputNode class does that automatically count as a test for the BaseNode class as well?
Edited question to make it more specific. I'm not just asking about getters and setters.
If you write a test for somethingComplicated() in the Base class do you automatically assume that the test is valid for the InputNode class?
I originally used getters and setters as a simple example to try and illustrate the concept. I didn't mean that I only wanted to test the getters and setters.
First of all, setters are a code smell, in no small part because they increase the complexity of testing. They do this because they potentially increase number of possible states an object can be in.
The best practices are:
Minimize setters
Every derived object has to pass every base class test, so make sure you set your tests up to do just that. If they don't pass, then that means that base instances are not liskov substitutable. The upside of this is that you shouldn't need to write a complete set of new tests for every derived class.
You'll need tests to specifically ensure that your new setters and behaviours don't interact incorrectly with base class behaviour.
The full suite of tests for the base class needs to pass for each derived class in order to demonstrate Liskov substitutability. In addition, tests for the specialization provided by the derived class need to exist. Many folks choose to organize the test classes in a way that mirrors the classes under test for just this reason.
Given a class InputNode that subclasses BaseNode, we might have test classes that look like this
[corrections to my Java syntax are welcome]:
public class BaseNodeTest {
protected BaseNode getBaseNode () {
return new BaseNode();
}
public void test_complicated_BaseNode_behavior () {
BaseNode bn = getBaseNode();
// actual test code...
}
}
public class InputNodeTest extends BaseNodeTest {
protected BaseNode getBaseNode () {
return new InputNode();
}
public void test_InputNode_specific_behavior () {
InputNode in = getBaseNode();
// actual test code...
}
}
The key point is that InputNodeTest will run all of the tests in BaseNodeTest against InputNode and add its own tests. This assures that InputNode could be used wherever a BaseNode is expected.
You have to test the base class too, because the base node's method/getter could be affected by code in the base class that is:
overriden by derived classes
code in derived classes may cause side effects (by changing base class fields, etc.)
I want to do make a public member in a base class private in a derived class, like this:
class A {
public:
int x;
int y;
};
class B : public A {
// x is still public
private:
// y is now private
using y;
};
But apparently "using" can't be used that way. Is there any way to do this in C++?
(I can't use private inheritance because there are other members and functions of A that must still be public.)
Yes, using declaration technically allows you to do so.
You have to use using A::y instead of using y
However please seriously evaluate if doing this makes a design sense.
Few observations:
Your class should not have public data. That should be avoided as far as possible. If you stick to this design principle, you may not have a need to make it private in derived class.
Stick to LSP. If a base class has public method, and unless you are doing private inheritance, clients will be confused if the derived class makes the base class method private with such using declarations.
Short answer: no. Liskov substitution and the nature of public inheritance demands that everything that you can do with an A (i.e. its public members) can also be done by B. That means you can't hide a public method.
If you're trying to hide public fields, there isn't much you can do. To "hide" public methods, you could do something like:
class B {
// x is still public
int x() { return a.x(); }
private:
A a;
// y is now private since you didn't add a forwarding method for it
};