Amol Bais
Amol Bais

Reputation: 359

JUnit: No runnable methods

I am newbie in JUnit. I am fixing JUnit in SonarQube report and also increasing Junit code coverage. I came across of a class where there is no @Test annotation. The Exception thrown is as below:

No runnable methods java.lang.Exception: No runnable methods at java.lang.reflect.Constructor.newInstance(Constructor.java:526)

Test class below:

public class TestLimitPrice {

@BeforeClass
public static void setUpBeforeClass() {

    JndiDataManager.init();
}

private LimitPriceBean      limitPrice;
private LimitPriceValidator validator;

@Before
public void setUp() {

    limitPrice = new LimitPriceBean();
    validator = new LimitPriceValidator(limitPrice);
}}

My Question's are :

Update

Upvotes: 1

Views: 1735

Answers (1)

G. Ann - SonarSource Team
G. Ann - SonarSource Team

Reputation: 22804

My Question's are :

  • In Sonar Report is it necessary for every JUnit to have at least one @Test to pass ?

I don't understand the question.

  • Will empty @Test is good approach for increasing code coverage ?

No, for two reasons.

First, if the @Test method is truly empty, then there's no possibility to increase coverage. So let's assume that you have a @Test method that does execute some of your program code but that contains no assertions.

In this scenario, you've increased your test coverage by executing program code in a @Test but totally subverted the purpose of tests by not making any statements (assertions) about the expected outcome / outputs of that code. Let's say I've got

public int addTwoAndTwo() {
  return 2+2;
}

And a corresponding test

@Test public void testAddTwoAndTwo() {
   MyClass mc = new MyClass();   
   my.addTwoAndTwo();  // this method now "covered"
}

Now that addTwoAndTwo is "covered" I'm supposed to be able to maintain it with confidence that as long as the unit tests continue to pass, I haven't broken anything.

So let's do that. My new version is this:

public int addTwoAndTwo() {
  return 42;
}

After that change, my unit tests still succeed, so everything must be okay, right? Uhm... no. And that's why you need assertions:

@Test public void testAddTwoAndTwo() {
   MyClass mc = new MyClass();   
   assertThat(mc.addTwoAndTwo()).isEqualTo(4);  // this method now truly covered
}
  • If in case any test case is not executing, then assertEquals(true,true) is good practice or should be avoided ?

The answer to this question should by now be obvious, but to be explicit, DO NOT DO THIS.

Upvotes: 3

Related Questions