Why sonar(JaCoCo) is asking me to test my packages? - sonarqube

I am trying to close some test holes in my application and found that JaCoCo sonar plugin is giving me a smaller coverage in my enums because it thinks I should test the Package names.
Why is that?
It's showing me a 97% coverage in one of my enums and displaying a red line on top of the package declaration like this, telling me to test it... it does that in all Enums and on Enums only.

I came here looking for the answer to this, and after some more digging I discovered that it's due to some static methods that can be found in the bytecode of the compiled enum class which Jacoco is expecting to be covered. After some experimentation, I came up with the following superclass to use for unit tests which are focused on enums, with JUnit 4. This resolved my coverage problems with enums.
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
public abstract class EnumTest {
#Test
public void verifyEnumStatics() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class e = getEnumUnderTest();
Method valuesMethod = e.getMethod("values");
Object[] values = (Object[]) valuesMethod.invoke(null);
Method valueOfMethod = e.getMethod("valueOf", String.class);
assertEquals(values[0], valueOfMethod.invoke(null, ((Enum)values[0]).name()));
}
protected abstract Class getEnumUnderTest();
}
And then use it like this:
public class TravelTypeTest extends EnumTest {
#Override
protected Class getEnumUnderTest() {
return TravelType.class;
}
// other test methods if needed
}
This is a rough first attempt - it doesn't work on enums that for whatever reason don't have any entries, and doubtless there are better ways to get the same effect, but this will exercise the generated static methods by ensuring that you can retrieve the values of the enum, and that if you pass the name of the first enum entry to the valueOf() method you will get the first enum entry back.
Ideally we'd write a test that searches for all enums in the packages under test and exercise them in the same way automatically (and avoid having to remember to create a new test class for each new enum that inherits from EnumTest), but I don't have many enums so I haven't felt any pressure to attempt this yet.

Related

Is there any way to preserve unused classes in Dart?

I started developing my own dependency injection package in dart just for fun. The problem I came across is that when a class is in it's own file and is not imported anywhere, dart's tree shaking will remove it and make it inaccessible. This makes it impossible for me to map implementation of some interface to the interface so I cannot ask context to give me implementation when I supply the interface. Here is what I mean:
import 'context/context.dart';
void main() {
Context context = Context();
Interface interface = context.getInstance<Interface>();
interface.works();
}
abstract class Interface {
void works();
}
And here is the implementation of the "Interface" abstract class:
#Singleton()
class Implementation implements Interface {
#override
void works() {
print('works');
}
}
If I import the file that contains the "Implementation" class, context is able to find it and map it but I want to avoid doing that. Is there any way to turn off the tree shaking or preserve the class without importing it ?

How to perform Tests for DTOs?

I am creating a class to store the tests of all DTO classes, but currently I only manage to cover 10% of the coverage. I need to know how to do the #Tests for the DTOs.
My DTO:
#Data
#NoArgsConstructor
public class ActivityDTO {
private Integer id;
private Integer version;
#JsonProperty("working_days")
private MonthWorkingDays workingDays;
}
My Test class:
#Test
public void ActivityDTOTest() {
ActivityDTO obj = BeanBuilder.builder(ActivityDTO.class).createRandomBean();
}
This is the coverage:
My problem: I don't know how to test the DTO class, I'm testing with assertEquals but I don't know how to apply it. Can someone put what the Test class would be like for this DTO class and thus be able to replicate it in the other classes?
This might be subjective, but in general you should not test to increase the coverage, instead you should always think "what exactly" the test checks.
In a nutshell, there can be two things to be tested:
A state of the object
A behavior
Most of the tests usually (arguably, but at least this is what I usually do in my project) tend to check the behavior that is technically implemented as a business logic inside the methods.
Since the DTOs do not really have methods with the logic, you can only test the state of the object.
Another idea: there is no point in checking the code that you haven't written. So yes, following your example in the question, putting lombok annotations will generate some getters/setters/constructors - but its not your code, the proper handling of these annotations was supposed to be checked by lombok team itself.
What you can do if you really want to test DTOs is generate the one with some default values and check that its internal state indeed matches the expected. Something like this:
public class ActivityDTO {
private Integer id;
private Integer version;
// getters / setters maybe
}
#Test
public void test_state_is_correct() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest.getId(), equalTo(SAMPLE_ID));
assertThat(underTest.getVersion(), equalTo(SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_same_values() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, equalTo(new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_different_id() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, not(equalTo(new ActivityDTO(ANOTHER_SAMPLE_ID, SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_different_version() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, not(equalTo(new ActivityDTO(SAMPLE_ID, ANOTHER_SAMPLE_VERSION));
}
... test for toString()... and hashCode maybe, etc.
This will make the coverage tool happy for sure, but the real question is will it make your code better (more robust and less buggy, etc)?
One thing for sure - these tests are time consuming, boring, and probably give less value to the project. To overcome the frustration of the programmers who absolutely need to write these tests there are even tools for automatic testing of these simple java beans (DTO can be viewed as a java bean), to name a few:
https://github.com/codebox/javabean-tester
https://code.google.com/archive/p/junit-javabean-runner/
http://javabeantester.sourceforge.net/
Now the entirely different story is if you test the behavior of some service or DAO that, say, generates the DTO - these tests whether they're unit or integration tests are really needed. They'll also increase the coverage of the project (and maybe even will cover the code of the DTO, although its not their primary goal), but I would suggest to start writing these tests first.
I don't know what is the best practice but AFAIK you should exclude the DTO classes from the configuration and you don't have to write unit test for them.
If you are using JaCoCo plugin, you better check this out: How to exclude certain classes from being included in the code coverage? (Java)

Test service from with dependencies in spock

I am working with a kotlin and spring project, Now I am trying to do the test of some service, which has some dependencies, I am having some problems, in order to get a success test. Maybe I my design is not good enough, moreover I have problems trying to call the method from the spy object, I am getting the issue: Cannot invoke real method 'getClubhouseFor' on interface based mock object. This is my code, Could you give me any idea about what I am doing bad.
Thanks in advance!!!!
This is my code:
import com.espn.csemobile.espnapp.models.UID
import com.espn.csemobile.espnapp.models.clubhouse.*
import com.espn.csemobile.espnapp.services.clubhouse.AutomatedClubhouseService
import com.espn.csemobile.espnapp.services.clubhouse.ClubhouseService
import com.espn.csemobile.espnapp.services.clubhouse.StaticClubhouseService
import com.espn.csemobile.espnapp.services.clubhouse.contexts.ClubhouseContext
import com.espn.csemobile.espnapp.services.core.CoreService
import rx.Single
import spock.lang.Specification
class ClubhouseServiceImplTest extends Specification {
StaticClubhouseService staticClubhouseService = GroovyStub()
AutomatedClubhouseService automatedClubhouseService = GroovyStub()
CoreService coreService = GroovyStub()
ClubhouseContext clubhouseContext = GroovyMock()
Clubhouse clubHouse
ClubhouseLogo clubhouseLogo
ClubhouseService spy = GroovySpy(ClubhouseService)
void setup() {
clubhouseLogo = new ClubhouseLogo("http://www.google.com", true)
clubHouse = new Clubhouse(new UID(), "summaryType", ClubhouseType.League, new ClubhouseLayout(), "summaryName", "MLB", clubhouseLogo, "http://www.google.com", "liveSportProp",new ArrayList<Integer>(), new ArrayList<ClubhouseSection>(),new ArrayList<ClubhouseAction>(), new HashMap<String, String>())
}
def "GetClubhouseFor"() {
given:
staticClubhouseService.getClubhouseFor(clubhouseContext) >> buildClubHouseMockService()
// The idea here is to get different responses it depends on the class of call.
automatedClubhouseService.getClubhouseFor(clubhouseContext ) >> buildClubHouseMockService()
spy.getClubhouseFor(clubhouseContext) >> spy.getClubhouseFor(clubhouseContext)
when:
def actual = spy.getClubhouseFor(clubhouseContext)
then:
actual != null
}
def buildClubHouseMockService(){
return Single.just(clubHouse)
}
}
The next are the classes involved in the test:
import com.espn.csemobile.espnapp.models.clubhouse.*
import com.espn.csemobile.espnapp.services.clubhouse.contexts.ClubhouseContext
import com.espn.csemobile.espnapp.services.core.CoreService
import org.springframework.context.annotation.Primary
import org.springframework.context.annotation.ScopedProxyMode
import org.springframework.stereotype.Service
import org.springframework.web.context.annotation.RequestScope
import rx.Single
interface ClubhouseService {
fun getClubhouseFor(context: ClubhouseContext): Single<Clubhouse?>
}
#Service
#RequestScope(proxyMode = ScopedProxyMode.NO)
#Primary
class ClubhouseServiceImpl(private val clubhouseContext: ClubhouseContext,
private var staticClubhouseService: StaticClubhouseService,
private var automatedClubhouseService: AutomatedClubhouseService,
private val coreService: CoreService?): ClubhouseService {
override fun getClubhouseFor(context: ClubhouseContext): Single<Clubhouse?> {
return staticClubhouseService.getClubhouseFor(clubhouseContext).flatMap { clubhouse ->
if (clubhouse != null) return#flatMap Single.just(clubhouse)
return#flatMap automatedClubhouseService.getClubhouseFor(clubhouseContext)
}
}
}
Well, first of all GroovySpy or GroovyStub do not make sense for Java or Kotlin classes because the special features of Groovy mocks are only available for Groovy classes. So don't expect to be able to mock constructors or static methods that way, if that was the reason for the usage. This is also documented here:
When Should Groovy Mocks be Favored over Regular Mocks? Groovy mocks should be used when the code under specification is written in Groovy and some of the unique Groovy mock features are needed. When called from Java code, Groovy mocks will behave like regular mocks. Note that it isn’t necessary to use a Groovy mock merely because the code under specification and/or mocked type is written in Groovy. Unless you have a concrete reason to use a Groovy mock, prefer a regular mock.
As for your problem with the spy, you cannot use a spy on an interface type. This is documented here:
A spy is always based on a real object. Hence you must provide a class type rather than an interface type, along with any constructor arguments for the type.
So either you just switch to Mock or Stub, both of which work on interface types, or you spy on the implementation class instead. In any case, my main suggestion is to read the documentation first and then try to use a new tool like Spock. My impression is that you have not used Spock before, but of course I could be wrong.

Inheriting default methods with the same name in the class without any compilation error

How a class can implement two interfaces with the same default method in Java 8.
I was not able to get the concept behind the same default method from different interfaces getting inherited in the sub class.Please explain the issue.
interface House {
default String getAddress() {
return "101 Main Str";
}
}
interface Bungalow extends House {
default String getAddress() {
return "101 Smart Str";
}
}
class MyHouse implements Bungalow, House {
}
public class TestClass {
public static void main(String[] args) {
House ci = new MyHouse(); //1
System.out.println(ci.getAddress()); //2
}
}
In the above code default method getAddress() in interface House is present.another method with the same name is declared as default in the extending interface Bungalow
How class MyHouse can implement both the interfaces without any compilation error(because it doesn't know which method has the preference in that case implementing should fail.)
If i call new MyHouse().getAddress(); gives compile error but it should give compilation error even without method calling from MyHouse class.
It seems that the answer is here, where there is a different example, but sort of makes sense and is really close to yours.
Ask me the exact same thing in 1/2 a year and I'll say it will fail at compile time and point me to this answer, so that I could read the JLS again. I guess this is how they decided to implement it. Without thinking too much, I, personally (may be wrong) think that this is at least counter intuitive...

list all Joinpoints in Spring's Aspect Oriented Programming

Is it somehow possible to list all Joinpoints that are matching a given Pointcut in Spring's Aspect Oriented Programming.
I guess spring has some kind of registry where all Joinpoints are in at runtime.
e.g. for
#Pointcut("execution(* transfer(..))")
there should be a list somewhere, containing all methods that are called "transfer"
I do not know how Spring exactly handles AOP internally, but I do know it creates dynamic proxies (JDK or CGLIB types) during runtime. So there might not be a complete list unless all target classes/interfaces are already loaded when you generate your report.
But I have an elegant workaround for you: Just for the purpose of generating the report, compile your aspects with pure AspectJ (AspectJ syntax is basically a superset of Spring AOP), using this option for the AspectJ compiler ajc:
-showWeaveInfo display information about weaving
It will list all woven joinpoints. For statically determined joinpoints like execution() this is ideal. Dynamic joinpoints like cflow(), cflowbelow() (both are not supported by Spring AOP anyway) and if() can only be evaluated during runtime, in those cases more joinpoints will be woven than might actually be used later during runtime, just to be on the safe side and not miss any possible joinpoints.
Besides, in Eclipse using AJDT (AspectJ Development Tools) you have nice cross-reference views in which you can list and dynamically navigate from pointcuts to affected joinpoints and vice versa.
Just give it a spin, good luck! But maybe someone knows a pure Spring solution for you. I do not because I never used Spring.
P.S.: Here is a little example in pure AspectJ:
Java classes:
package de.scrum_master.app;
public class Application {
public int transfer() { return 11; }
public void transfer(int number) { }
}
package de.scrum_master.app;
public class Whatever {
public String transfer(int number) { return "foo"; }
public void transfer(String text) { }
}
Aspect:
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
#Aspect
public class TransferInterceptor {
#Before("execution(* transfer(..))")
public void intercept(JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint);
}
}
Compiler output with -showWeaveInfo:
Join point 'method-execution(java.lang.String de.scrum_master.app.Whatever.transfer(int))' in Type 'de.scrum_master.app.Whatever' (Whatever.java:4) advised by before advice from 'de.scrum_master.aspect.TransferInterceptor' (TransferInterceptor.aj:10)
Join point 'method-execution(void de.scrum_master.app.Whatever.transfer(java.lang.String))' in Type 'de.scrum_master.app.Whatever' (Whatever.java:5) advised by before advice from 'de.scrum_master.aspect.TransferInterceptor' (TransferInterceptor.aj:10)
Join point 'method-execution(int de.scrum_master.app.Application.transfer())' in Type 'de.scrum_master.app.Application' (Application.java:4) advised by before advice from 'de.scrum_master.aspect.TransferInterceptor' (TransferInterceptor.aj:10)
Join point 'method-execution(void de.scrum_master.app.Application.transfer(int))' in Type 'de.scrum_master.app.Application' (Application.java:5) advised by before advice from 'de.scrum_master.aspect.TransferInterceptor' (TransferInterceptor.aj:10)

Resources