I'm currently studying a JUnit 5 book and I need assistance in understanding this line:
A test method can be either protected or package protected.
The preferred is to use package protected as that leads to less typing.
If the citation is accurate, it is wrong. A Jupiter test method (there’s no such thing as a JUnit 5 test method) can be anything but private, so it can be public, protected or package private. Package private means that it has no accessibility modifier.
That means that running the following test class:
import org.junit.jupiter.api.Test;
class MyTests {
#Test
public void test1() {
}
#Test
protected void test2() {
}
#Test
void test3() {
}
#Test
private void test4() {
}
}
will execute test1, test2 and test3, but not test4.
test3 being the preferred one.
Mind that the same holds for the class' accessibility modifier: package private and public are possible. Private classes are not being executed, protected classes do not exist in Java.
In the book I'm currently studying, the first line was explained. But the second statement which wasn't was my major concern.
After other searches, I've figured out it means that the developer gets to type less, as the method is defined with less words.
Related
I use Boost Test for unit tests. I typically have a fixture struct:
class ClassBeingTested
{
protected:
int _x; // Want to access this directly in my unit tests
};
struct TestFixture : public ClassBeingTested
{
// I can access ClassBeingTested::_x here but it means i have to add getters for each test to call
ClassBeingTested _bla;
};
However, even if my fixture inherits from ClassBeingTested or uses a friend relationship I cannot access private/protected methods/state from each individual test:
BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
_bla.doSomething();
BOOST_REQUIRE_EQUAL(_bla.x, 10); // Compiler error. I cannot access ClassBeingTested::_x here
}
only the fixture, which means I have to add a new getter (or test) for each access I wish to make.
Is there any way to achieve this? I have to add public getter methods to ClassBeingTested which are only used by tests, which isn't ideal.
(Please no replies of 'test using the public interface', that's not always possible).
You can make a friend test buddy, struct ClassBeingTestedBuddy; with friend struct ClassBeingTestedBuddy; in the class ClassBeingTested.
Have the test buddy class expose all the protected or private variables or methods that you need for all your tests.
It'd look like...
struct ClassBeingTestedBuddy {
ClassBeingTested* obj;
ClassBeingTestedBuddy(ClassBeingTested* obj_)
: obj{obj_} {}
};
...plus anything else you'd want to expose.
This is but one way of allowing the tests a bridge to the protected and private data and methods. But since it is all code in your project, for your testing use, it is a reasonable way of getting the test code access without too much instrumenting your actual code.
I'm writing a junit test for a particular method. The method contains calls to other methods in a DAO class which I am mocking with EasyMock.
I want to assert that one of these DAO class methods is called once, which is what I assume expectLastCall().once() is for. The method in question returns void.
The test I have currently passes, I just want to make sure my logic is correct as I haven't used EasyMock before. I used this question as a reference: EasyMock expectations with void methods
So, here is the code:
#Before
public void setUp() throws Exception{
this.fooService = new FooService();
this.fooMock = createStrictMock(FooDAO.class);
}
#Test
public void test_fooTest(){
String arg1 = "arg1";
String arg2 = "arg2";
this.fooService.setFooDAO(fooMock);
expect(this.fooMock.someMethod(arg1, arg2)).andReturn(something);
fooMock.methodThatShouldBeCalledOnce(EasyMock.<Object>anyObject());
EasyMock.expectLastCall().once();
replay(this.fooMock);
this.fooService.methodUnderTest(someArg, someArg2);
verify(this.fooMock);
}
What I think this does is assert that there is a call to methodThatShouldBeCalledOnce and that it only happens once. I don't really care about someMethod but of course EasyMock complains if it's not told to expect it.
Thank you!
That looks correct to me. You could easily check by yourself by removing the call to the void method and verify that the test fails, or by adding a second call to the void method and see that the test also fails.
If you don't care about some methods, you should create a nice mock. Then, indeed, there's no need to call expectLastCall. It is implicit but can be a good practice to make it obvious you are mocking a method. once() is also not needed since it is the default.
So, if a rephrase it, using a nice mick, removing implicit calls, adding static imports and not adding redundant "this", you should get:
#Before
public void setUp() throws Exception{
fooService = new FooService();
fooMock = createNiceMock(FooDAO.class);
fooService.setFooDAO(fooMock);
}
#Test
public void test_fooTest(){
fooMock.methodThatShouldBeCalledOnce(anyObject());
replay(fooMock); // or replayAll() if you extend EasyMockSupport
fooService.methodUnderTest(someArg, someArg2);
verify(fooMock); // or verifyAll() if you extend EasyMockSupport
}
All right, do not get angry now, I know there are several questions about this topic, but I still have some doubts.
I think I totally agree about not testing private functions, I find it reasonable, but how can I test public methods that set private variables?
Let's say that the constructor set some private variables and I want to test that those variable are correctly set after the constructor is called. Is it a valid test? How should I check the value of the private variables without adding public getters?
I add a not real scenario example to try to be clearer:
public class ClassToTest
{
private bool _isOn;
public void SwitchOn() { _isOn = true; }
public void SwitchOff(){ _isOn = false; }
public void update()
{
if (_isOn)
DoSomething();
}
private void DoSomething()
{
//this could also execute a function of an external dependency. But still the dependency could not have a public function to test if the behavior actually ran.
}
}
how can I test that SwitchOn and SwitchOff work properly if I cannot test against the _isOn value? (this is an example, it implies that I will not write a public getter and the functions do not return a value because they do not need to)
Tests should use the Assemble/Activate/Assert pattern:
test switch on {
x = new ClassToTest();
x.SwitchOn(); // <-- Assemble an on switch
EmptyMailQueue(); // <-- Assemble nothing in the Q
PossiblySendUserEmail(); // <-- Activate the feature
assert(mailQueue.count() == 1);
}
test switch on {
x = new ClassToTest();
x.SwitchOff();
EmptyMailQueue();
PossiblySendUserEmail();
assert(mailQueue.count() == 0); // <-- Assert switch is off so no mails sent
}
You assert the actual reason you have a switch. Testing the switch itself breaks the rule "Don't TDD getters and setters".
You need to test private members, because they might have bugs in them.
"Private" is not a magic barrier, it's simply a convention advising production-code clients not to call that member directly.
Prepending all such member with an _underbar would be just as useful as C++ protecting such methods with hardware.
Your car engine has plugs inside that should not be used while driving, only when a mechanic tests things. Software should be the same. Test your private members, and disable private if you need to.
However...
The point of an object is to expose behavior. If your private variable is set correctly, then your object should behave correctly. Your tests should request this behavior.
Look up "Test-Driven Development" (and start using it yesterday), and look up "Intentional Programming". Your test cases should start by requesting that behavior, and should not worry about implementation details. If you upgrade an object to use different internals, you don't need too many tests breaking for no reason.
(Go not to elves, or software methodologists, for advice, for they will say both Yes and No!;)
What is the proper way with JUnit 4 to create test cases to use common functionality: e.g. setup that is common to several unit test classes? What I did was create a test case and put the common functionality in the #Before method, then any test case that needs this would extend the base class. However, this seems to require doing: super.setUp() in every subclass.
Is there a better way?
EDIT
Actually my proposed solution is not working. Sometimes JUnit will call the base class TWICE. Once if it happens to run the test on the base class first, and again when it reaches a child class (at least I think this is whats happening). So a better way of "inheriting" common test case functionality would be great.
You don't need to invoker super.setup() if you use the #Before annotation:
When writing tests, it is common to find that several tests need
similar objects created before they
can run. Annotating a public void
method with #Before causes that method
to be run before the Test method. The
#Before methods of superclasses will
be run before those of the current
class.
I'd suggest something like this:
#Before
public void initForAll() {}
In the super/Main class
and any
#Before
public void initTest() {...}
In your Testcases.
EDIT:
To answer your questions in the edit.
You could use #BeforeClass which will be invoked once per TestClass.
But I Think you are looking for something like a lazy /static Initialisation.
I do this like this:
private boolean initialized = false;
#BeforeClass
public static void init()
{
if(initialized)
{
return;
}
//Initialize everything
initialized = true;
}
thats a pretty good way to do it. If you have a setUp() on the subclass, then yes, you have to invoke super.setUp(), but really, how hard is that?
Have you tried other approach.
Instead of creating a base class with a common functionality, make an util class with static methods which will the common functionality. Then just call util methods in #Before annotated method of each test case.
If your base class has a method public void setUp(), and so does your sub-class, then the sub-class's setUp method overrides the base class's method of the same name and signature, so only the sub-class's method will be called (and it may be called when the base class's method should have been called; not sure about this).
The solution is to call your base class setup method something else, e.g. baseSetup(). Then they will both be called automatically. Joachim's answer does address the naming, but I wanted to be clearer about the effects of method override.
Say I have an interface IFoo which I am mocking. There are 3 methods on this interface. I need to test that the system under test calls at least one of the three methods. I don't care how many times, or with what arguments it does call, but the case where it ignores all the methods and does not touch the IFoo mock is the failure case.
I've been looking through the Expect.Call documentation but can't see an easy way to do it.
Any ideas?
You can give rhino mocks a lambda to run when a function get's called. This lambda can then increment a counter. Assert the counter > 1 and you're done.
Commented by Don Kirkby:
I believe Mendelt is referring to the Do method.
Not sure this answers your question but I've found that if I need to do anything like that with Rhino (or any similiar framework/library), anything that I didn't know how to do upfront, then I'm better just creating a manual mock.
Creating a class that implements the interface and sets a public boolean field to true if any of the methods is called will be trivially easy, you can give the class a descriptive name which means that (most importantly) the next person viewing the code will immediately understand it.
If I understood you correctly you want to check that the interface is called at least once on any of three specified methods. Looking through the quick reference I don't think you can do that in Rhino Mocks.
Intuitively I think you're trying to write a test that is brittle, which is a bad thing. This implies incomplete specification of the class under test. I urge you to think the design through so that the class under test and the test can have a known behavior.
However, to be useful with an example, you could always do it like this (but don't).
[TestFixture]
public class MyTest {
// The mocked interface
public class MockedInterface implements MyInterface {
int counter = 0;
public method1() { counter++; }
public method2() { counter++; }
public method3() { counter++; }
}
// The actual test, I assume you have the ClassUnderTest
// inject the interface through the constructor and
// the methodToTest calls either of the three methods on
// the interface.
[TestMethod]
public void testCallingAnyOfTheThreeMethods() {
MockedInterface mockery = new MockedInterface();
ClassUnderTest classToTest = new ClassUnderTest(mockery);
classToTest.methodToTest();
Assert.That(mockery.counter, Is.GreaterThan(1));
}
}
(Somebody check my code, I've written this from my head now and haven't written a C# stuff for about a year now)
I'm interested to know why you're doing this though.