General questions on parameterized test in googletest - googletest

background:I am writing a Session table for incoming traffic. This table should hold all active UDP/TCP connections.
I am using googletest package to test my implementation.
I prepare a parameterised test based on fixture in the following format:
class SessionTest - initialize all staff.
struct ConnectionInfo - holds set of connection parameters (IPs, ports, etc..)
class SessionTestPrepare : SessionTest , testing::WithParamInterface<ConnectionInfo> - initialization.
TEST_P(SessionTestPrepare, test) - holds the test cases and logic.
INSTANTIATE_TEST_CASE_P(default, SessionTestPrepare_ testing::Values(
ConectionInfo{},
ConectionInfo{},
ConectionInfo{},
)
I noticed that each time new parameters are tested, the SessionTest constructor and Setup function are called (and of course destructor and TearDown).
Note: my sessionTable is declared and initialized here.
Is there a way to avoid calling to SetUp and TearDown after each set of parameter test?
Is there a way to keep the state of my Session Table after each test without make it global (i.e. when testing the second connection parameters, the first is still in table)?

To run set up and tear down only once in a test fixture, use SetUpTestCase and TearDownTestCase instead of SetUp and TearDown. And the shared resources can be stored in fixture with static member variables. For example:
class SessionTestPrepare : public ::testing::WithParamInterface<ConnectionInfo> //...
{
public:
static void SetUpTestCase();
static void TearDownTestCase();
static ConnectionInfo * shared_data;
//...
}
SetUpTestCase is called before the first parameter test begins and TearDownTestCase is called after the last parameter test ends. You can create/delete the shared resources in these functions.

Related

What does the JUnit 4 #Test Annotation actually do

What does the #Test actually do? I have some tests without it, and they run fine.
My class starts with
public class TransactionTest extends InstrumentationTestCase {
The test runs with either:
public void testGetDate() throws Exception {
or
#Test
public void testGetDate() throws Exception {
EDIT: It was pointed out that I may be using JUnit 3 tests, but I think I am using JUnit 4:
#Test
public void method()
#Test => annotation identifies a method as a test method.
#Test(expected = Exception.class) => Fails if the method does not throw the named exception.
#Test(timeout=100) => Fails if the method takes longer than 100 milliseconds.
#Before
public void method() =>This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class).
#After
public void method() => This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
#BeforeClass
public static void method() => This method is executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit.
#AfterClass
public static void method() => This method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
#Ignore => Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
It identifies a method as a test method. JUnit invokes the class, then it invokes the annotated methods.
If an exception occurs, the test fails; however, you can specify that an exception should occur. If it does not, the test will fail (testing for the exception - sort of inverse testing):
#Test(expected = Exception.class) - Fails if the method does not throw the named exception.
You can also set time limits and if the function does not finish with the allotted time it will fail:
#Test(timeout = 500) - Fails if the method takes longer than 500 milliseconds.
In JUnit 4 the #Test annotation is used to tell JUnit that a specific method is a test. In JUnit 3 in contrast every method is a test if its name starts with test and its class extends TestCase.
I assume that InstrumentationTestCase extends junit.framework.TestCase. This means that you're using a JUnit 4 annotation within a JUnit 3 test. In this case the tool that runs the tests (your IDE or build tool like Ant or Maven) decides whether is recognizes the #Test annotation or not. You can verify this by renaming testGetDate() to something that doesn't start with test, e.g. shouldReturnDate(). If your tool still runs 17 tests than you know that it supports JUnit 4 annotations within JUnit 3 tests. If it runs 16 tests than you know that the #Test annotation is just a flashbang that does nothing.
JUnit 4 still provides the classes of JUnit 3 (the junit.framework package). This means you can use JUnit 3 style tests with JUnit 4.
In JUnit Annotations are used to give a meaning to a method or class as per test execution point of view. Once you use #Test annotation with a method then that method is not longer an ordinary method it is a Test Case and it will be Executed as Test Case by IDE and JUnit will diplay its execution results as per test case passed or mail on the basis of your assertions.
In case you are starting with JUnit as a beginner do check out simple Junit Tutorial here - http://qaautomated.blogspot.in/p/junit.html

Why do we need a constructor in OOP?

I am new to OOP. I am still in a learning phase.
Why do we need constructors, When we can initialize the values of the properties (variables) by writing a "Initialize function"?
Basically why do we write a constructor when we can achieve the same results even by writing a function for initializing the variables?
The constructor IS the "Initialize function"
Rather than calling two functions
object = new Class;
object.initialize();
You just call
object = new Class();
The logic inside the constructor can be identical to the logic inside the initialize function, but it's much tidier and avoids you naming your function initialize(), me naming mine initialize_variables(), and someone else naming theirs init_vars()... consistency is useful.
If your constructor is very large, you may still wish to split variable initialisation into a separate function and calling that function from your constructor, but that's a specific exception to the scenario.
So answer is simple
Why do we write Constructor?
Because in C you can write,
int i;
if write like this In above case data type and variable defines if you define like this memory allocated for i variable.So simple here we define class name and variable name(object name) we can create memory allocated for class name.
Example
myClass objectName;
But in C++ new keyword is used for dynamic memory allocation, so this dynamic memory which we can allocate to our class but here my example myClass is our class and we want to allocate to dynamic memory allocated.
So
myClass objectName = new myClass();
and simply constructor is memory allocation for class variable is called the constructor.`
the role of the constructor is to initialize the variables/values.it is the "initialization function".The only reason i find on why we use a constructor instead of a normal function to initialize the variables is to stop different people from using different function names and avoid ambiguity and it is much more easier to use a constructor which is instantiated automatically as soon as the class is run,instead of having to write a separate code for instantiation.this may seem small and like something that doesn't require much work,but only for a very small program,for larger ones the struggle is real.
It is usual to put mandatory things into the constructor and optional ones into the Initialise function.
For example, consider an amplifier that requires a power source so that would be supplied to its constructor. Logically, you may want to turn it on and set its power level but one could argue that you might not want to do that until later. In pseudo-code:
class Amplifier
{
public Amplifier(PowerSource powerSource)
{
// create amplifier...
}
public int PowerLevel;
public void Initialise()
{
// turn on...
}
}
The example, above, is rather puerile but it illustrates the concepts at play. It is always an issue of design, however, and opinions do vary.
Some classes of object, however, will have to perform obvious set-up operations during their construction phase. In these cases, the requirement to have a constructor is very easy to understand. For example, if your object might require a variable amount of memory, the constructor would be a logical place to allocate it and the destructor or finaliser would be a logical place to free it up again.
Even if you don't use constructor it will call implicitly by your language translator whenever you create object.Why?
The reason is that it is used for object initialization means the variable(instance) which we declare inside our class get initialized to their default value.
class Person {
//Class have two parts
//1.Data(instance variable)
//2.Methods(Sub-routine)
String name;
int age;
}
public class Stack{
public static void main(String[] args){
Person person1 = new Person();
System.out.println("Name: "+person1.name);
System.out.println("Age: " + person1.age);
}
}
Output- Name: null
Age: 0
"null" and "0" are default values which are impicitly set by default constructor.
When we initialize a class by creating an instance or object the constructor is called automatically. This is very helpful when we need a huge amount of code to be executed every time we create an object.
The best use of constructor can be seen when we create a " graphical user interface". While building a GUI for an application we need to separate the code for designing the GUI and the business logic of the application. In such a case we can write the code for designing GUI, in a constructor and business logic in respective methods. This make the code tidy and neat too.
Also when an object is created the global variables can be initialized to their default values using constructor. If we don't initialize the global variables, then the compiler will do it implicitly by using the default constructor.
So constructor is a very wise concept which appears to be an idiosyncrasy at first but as you code further and more and more you will realize it's importance.
Because constructors are exactly for that: to avoid using an "initialize function"
Plus you can have have as many constructors as you want: you juste feed them some parameters, depending how you want to inialize your object.
Constructor is a special member function which has same name as class name and called whenever object of that class is created. They are used to initialize data field in object.
Constructor has following properties:
It has same name as class name.
It is called whenever object of a class is created.
It does not have return type not even void.
It can have parameters.
Constructor can be overloaded.
Default constructor is automatically created when compiler does not find any constructor in a class.
Parameterized constructor can call default constructor using this() method.
A constructor can be static for static data field initialization.
It is not implicitly inherited.
For More Info
https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)

In JMockIt, what is a #Mock final parameter

I'm completely new to JMockIt. In the tutorial I see example codes that uses the final modifier for a #Mocked parameter e.g.
#Test
public void doSomethingHandlesSomeCheckedException(#Mocked final DependencyAbc abc) throws Exception
{
...
}
What does final mocked parameter mean here? Sometimes, "final" is not used. What is the difference?
This is merely a Java language issue, nothing to do with JMockit itself. For a method parameter or local variable to be used inside an inner class (anonymous or not), the Java compiler requires it to be declared as final.
From the JMockit tutorial:
"For a mock parameter declared in a test method, an instance of the declared type will be automatically created by JMockit and passed by the JUnit/TestNG test runner when calling the test method. Therefore, the parameter value will never be null.
For a mock field, an instance of the declared type will be automatically created by JMockit and assigned to the field, unless it's a final field. In such case, a value should be created and assigned to the field explicitly in test code. This value can be null, though, which is perfectly valid for a mocked class if only constructors and static methods are going to be called on it."
http://jmockit.googlecode.com/svn/trunk/www/tutorial/BehaviorBasedTesting.html#declaration
Keep in mind that a mock parameter/field is any annotated with #Mocked or #Injectable.

Design pattern to ensure that a method A is called before method B

I have a sample(incomplete) class like
class ABC{
public:
void login();
void query_users();
//other methods
private:
//member data
}
This class should be used in a way that login needs to be called first and then only other methods like query_users, etc., can be called. Login sets some private member data for the other methods to use. Is there any simpler way to achieve this other than calling a function that checks if the member data is set at the start of every other method in the class?
There are two general approach I know of, and they differ a good bit. You'll have to pick the appropriate mechanism for the task - in standard class-based OO languages (e.g. Java/C++/C#/Python), they are the only two approaches I know of. (There may be other approaches in different paradigms that I am unfamiliar with.)
1. Check the state.
This is done in many classes already that have to track the state of the system/backing resource. Two common examples are (file) stream and database connections.
A "template" might look like:
void Logon(credentials) { ..; loggedOn = true }
void DieUnlessLoggedIn { if (!loggedOn) { throw .. } }
void DoStuff () { DieUnlessLoggedIn(); .. }
While the above approach is pretty generic, some languages may support invariants (Eiffel), decorations (Python), annotations, AOP, or other assertion mechanisms.
This approach is useful for dynamic state in a mutable world: e.g. what happens after "Logout"? The state for DoStuff is invalid again until a re-logon (if it's allowed). However, this approach cannot be used for compile-time checks in general in mainstream OOP languages because the run-time state simply is not available at compile-time.
2. Use multiple types to represent state.
Create two separate types, such that type ServiceLogon (method Logon) creates ServiceAccess (method DoStuff). Thus DoStuff can only be called (on type ServiceAccess) after created from Logon (on ServiceLogon). This works well to enforce calling order semantics in static languages with member hiding - because programs won't compile if it's wrong.
login = new ServiceLogon(credentials)
access = login.Logon();
access.DoStuff(); // can't be called before obtained via Logon
Using the type to encode additional state can be overly complex as it can fracture a class-based type system, but is useful in "builder" and "repository" patterns and such; basically, ask if the type warrants being split to maintain SRP, then considering this approach.
This approach cannot handle things like "logout" entirely without incorporating state checking as type ServiceAccess would (in the clean sense) always represent the same state due to it being encoded in the type.
1. & 2. Use state checking and state/role-specific types.
A hybrid is totally acceptable, of course, and the above two approaches are not mutually exclusive. It may make sense to separate the roles making one type (and thus methods invoked upon it) dependent upon another method while still checking runtime state as appropriate. As per above, #1 is really good for runtime guards (which can be highly dynamic) while #2 can enforce certain rules at compile-time.
What you can do is to create instances of ABC form a static factory method that returns the instance you can use. In pseudo-code:
abc = ABC.login(); //sets all the state
users = abc.query_users();
I am not sure this is the best way but you can make login() private and call it as part of the constructor, which would ensure that login() is called at time of object creation itself and after that only any other functions can be called (unless you have static functions)
class ABC{
public ABC(credentials){
login(credentails);
}
public:
void query_users();
//other methods
private:
void login();
//member data
}
It will already work first when it goes from the top down. If you want to make sure that login is successful then call the other methods from inside the login() method.
like:
public void login(){
//do login code
if(//code for login check){
//run other methods
}
else{
login(); //re-run login workings
}
}
If you really want to follow good patterns you might try making as many of your classes immutable as possible.
This would imply that your constructor sets the total state (does the entire login) and then the order of the method calls is totally irrelevant.

Is it better to test with mock or without?

A method can be tested either with mock object or without. I prefer the solution without mock when they are not necessary because:
They make tests more difficult to understand.
After refactoring it is a pain to fix junit tests if they have been implemented with mocks.
But I would like to ask your opinion. Here the method under test:
public class OndemandBuilder {
....
private LinksBuilder linksBuilder;
....
public OndemandBuilder buildLink(String pid) {
broadcastOfBuilder = new LinksBuilder(pipsBeanFactory);
broadcastOfBuilder.type(XXX).pid(pid);
return this;
}
Test with mocks:
#Test
public void testbuildLink() throws Exception {
String type = "XXX";
String pid = "test_pid";
LinksBuilder linkBuilder = mock(LinksBuilder.class);
given(linkBuilder.type(type)).willReturn(linkBuilder);
//builderFactory replace the new call in order to mock it
given(builderFactory.createLinksBuilder(pipsBeanFactory)).willReturn(linkBuilder);
OndemandBuilder returnedBuilder = builder.buildLink(pid);
assertEquals(builder, returnedBuilder); //they point to the same obj
verify(linkBuilder, times(1)).type(type);
verify(linkBuilder, times(1)).pid(pid);
verifyNoMoreInteractions(linkBuilder);
}
The returnedBuilder obj within the method buildLink is 'this' that means that builder and returnedBuilder can't be different because they point to the same object in memory so the assertEquals is not really testing that it contains the expected field set by the method buildLink (which is the pid).
I have changed that test as below, without using mocks. The below test asserts what we want to test which is that the builder contains a LinkBuilder not null and the LinkBuilder pid is the one expected.
#Test
public void testbuildLink() throws Exception {
String pid = "test_pid";
OndemandBuilder returnedBuilder = builder.buildLink(pid);
assertNotNull(returnedBuilder.getLinkBuilder());
assertEquals(pid, returnedBuilder.getLinkBuilder().getPid());
}
I wouldn't use mock unless they are necessary, but I wonder if this makes sense or I misunderstand the mock way of testing.
Mocking is a very powerful tool when writing unit tests, in a nut shell where you have dependencies between classes, and you want to test one class that depends on another, you can use mock objects to limit the scope of your tests so that you are only testing the code in the class that you want to test, and not those classes it depends on. There is no point me explaining further, I would highly recommend you read the brilliant Martin Fowler work Mocks Aren't Stubs for a full introduction into the topic.
In your example, the test without mocks is definitely cleaner, but you will notice that your test exercises code in both the OndemandBuilder and LinksBuilder classes. It may be that this is what you want to do, but the 'problem' here is that should the test fail, it could be due to issues in either of those two classes. In your case, because the code in OndemandBuilder.buildLink is minimal, I would say your approach is OK. However, if the logic in this function was more complex, then I would suggest that you would want to unit test this method in a way that didn't depend on the behavior of the LinksBuilder.type method. This is where mock objects can help you.
Lets say we do want to test OndemandBuilder.buildLink independent of the LinksBuilder implementation. To do this, we want to be able to replace the linksBuilder object in OndemandBuilder with a mock object - by doing this we can precisely control what is returned by calls to this mock object, breaking the dependency on the implementation of LinksBuilder. This is where the technique Dependency Injection can help you - the example below shows how we could modify OndemandBuilder to allow linksBuilder to be replaced with a mock object (by injecting the dependency in the constructor):
public class OndemandBuilder {
....
private LinksBuilder linksBuilder;
....
public class OndemandBuilder(LinksBuilder linksBuilder) {
this.linksBuilder = linksBuilder;
}
public OndemandBuilder buildLink(String pid) {
broadcastOfBuilder = new LinksBuilder(pipsBeanFactory);
broadcastOfBuilder.type(XXX).pid(pid);
return this;
}
}
Now, in your test, when you create your OndemandBuilder object, you can create a mock version of LinksBuilder, pass it into the constructor, and control how this behaves for the purpose of your test. By using mock objects and dependency injection, you can now properly unit test OndemandBuilder independent of the LinksBuilder implementation.
Hope this helps.
It all dependent upon what you understand by UNIT testing.
Because when you are trying to unit test a class , it means you are not worried about the underlying system/interface. You are assuming they are working correctly hence you just mock them. And when i say you are ASSUMING means you are unit testing the underlying interface separately.
So when you are writing your JUnits without mocks essentially you are doing a system or an integration test.
But to answer your question both ways have their advantages/disadvantages and ideally a system should have both.