In JMockIt, what is a #Mock final parameter - jmockit

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.

Related

Active Objects: Cannot handle method. It is not a valid getter or setter and does not have an implementation supplied

I am getting the error:
java.lang.IllegalArgumentException: Cannot handle method. It is not a valid getter or setter and does not have an implementation supplied. Signature: public abstract ...
in a unit test run with ActiveObjectsJUnitRunner.
The project is an Atlassian Jira plugin with Active Objects.
The problem was that some my colleague wrote the getter as:
import net.java.ao.0neToMany;
#OneToMany
Collection<NdaProtectedItem> getNdaProtectedItems();
while it should have been:
#OneToMany
NdaProtectedItem[] getNdaProtectedItems();
The result must be a plain array, ActiveObjects do not support collection getters!

How to get 100% test coverage over a DTO object class's getters when asserting function returns expected DTO object?

I'm unit testing an ASP.Net Core API by asserting that my repo layer returns a DTO object. As I'm testing behavior, I don't exactly care what values my DTO object has, so I'm autogenerating them using AutoFixture. I'm also trying to satisfy my company's code smell check, which requires our PRs to have a near 100% test coverage. When I mock my ORM to return my DTO object when called and in turn the function under test returns that object, I end up with my actual being the same object as my expected. When asserting with fluent assertion, it sees the object reference are equal and passes my test. However for test coverage, I will not see a coverage over the DTO's properties' getters. If the object reference where different, fluent assertion calls the getters. How do I force fluent assertion to always check the value of all properties by calling all the getters?
I've tried using ComparingByValue<T> and ComparingByMember<T>. I've also tried IncludingProperties(), IncludingMembers(), IncludingAllDeclaredProperties(), and IncludingAllRuntimeProperties().
[Fact]
public void GivenObjectReferenceIsTheSame_FluentAssertionDoesntCallTheGetters()
{
var someDTO = _fixture.Create<SomeDTO>();
var otherDTO = someDTO;
otherDTO.Should().BeEquivalentTo(someDTO);
}
[Fact]
public void GivenObjectReferenceIsDifferent_FluentAssertionCallsTheGetters()
{
var someDTO = _fixture.Create<SomeDTO>();
var otherDTO = JsonConvert.DeserializeObject<SomeDTO>(JsonConvert.SerializeObject(someDTO));
otherDTO.Should().BeEquivalentTo(someDTO);
}
I would like a way to always force fluent assertion to call the getters in order to get test coverage over the DTOs without having to explicitly write useless tests over the DTOs
The short answer is that you can't. You've asked FA to assert that the objects are equivalent, and in fact, they are the same. This satisfies what FA tries to do. The only alternative is to to pass in another instance which has its properties set to the values of the expectation. This can even be an anonymous object. ComparingByValue is only useful to force FA to ignore the Equals implementation and compare the individual fields and properties.

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)

How to make Mockito do something every time the method on the mock is called?

I'm trying to achieve this behavior with Mockito:
When object of type O is applied to a method M, the mock should execute another method on the object of type O passing itself as a parameter.
Is it possible after all?
You can probably use some combination of doAnswer and the when combined with Mockito.any. doAnswer is a part of PowerMockito, which helps extend a lot of the mocking you may want to do.
NOTE, doAnswer is used as an example for void functions. For a non-void you can use your standard Mockito.when(MOCK.call).then(RESULT)
PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
//Do whatever to Object O here.
return null;
}).when(MOCKOBJECT.methodCall(Mockito.any(O.class)));
This then does the helpful doAnswer functionality on a mock object, and using the when you can assign it to catch for any specific class of object (instead of having to specify an exact object it should be expecting). Using the Mockito.any(Class.class)) as part of the parameters lets Mockito know to fire off your doWhatever, when it hits a method call with ANY object of the specified type passed in.

Why Does This Groovy MetaClass Statement Work with Sql class?

Why does this line of unit test code work? groovy.sql.Sql doesn't have a no argument constructor.
Sql.metaClass.constructor = { dataSource -> return new Sql(); }
That line is amongst some others in a grails app which mocks out a Sql object's constructor and one of its methods. It works great.
Looking at the API for the Sql object, I do not see a no argument constructor: http://groovy.codehaus.org/api/groovy/sql/Sql.html
This style of overriding the constructor using Sql.metaClass.constructor is something I found at:
http://manuel-palacio.blogspot.com/2010/07/groovy-tip-metaprogramming-1.html
Thanks!
groovy.sql.Sql has no public no-args constructor, but as can be seen in the source, it does have a private no-args constructor -- I guess in order to support the syntax new Sql(connection: connection)?.
I'm kind of surprised, though, that that technique for stubbing doesn't generate an exception, e.g., when running sql.execute or the like.