1

I am having a Java class A. A's constructor calls few methods m1,m2.

class A{ public A(){ m1(); m2(); ...... } public void m1(){...}; public void m2(){...}; } 

How to write tests for these methods? I generally write them as

class TestClass{ static A a = null; public TestClass(){ a = new A(); } @Test public testm1(){ A.m1(); //Some logic } 

However, these functions are called in the constructor itself. It looks like I am executing the method twice to check, and the constructor itself fails if the method is incorrectly written. What is the proper way of testing it?

2
  • 2
    Importantly; don't test methods, test behaviour Commented Dec 2, 2016 at 12:31
  • Also helpful: just avoid inner (especially non static) classes. In eclipse you would do that by putting the cursor on the inner class name, hitting "Alt+Shift+T" and than hitting "V". That would move your inner class to outside where you can test ist how you wish. Especially you can mock the outter A-class Commented Dec 2, 2016 at 14:23

1 Answer 1

5

First of all, your interface looks strange.

You see, there is not much point in having one public method that calls another public method. So the real issue here is exactly what you described: the fact that your constructor is calling that m1 and m2 methods.

Either the constructor calls those methods, then they should ideally be private; or they are public, but then it shouldn't be the responsibility of the constructor to call them.

In that sense: the answer is to step back and look carefully into this aspect of your design; and if possible, change that!

In any case: when you keep your current design; there is no other way but testing that stuff "multiple" times. You see: your tests have to make sure that your constructor works (no matter if that ctor is calling some m1(), m2(), or m3(); or none of those); but then you have to make sure that calling all your public methods on an existing instance of your class works, too!

In the end: you don't call your methods because "they exist". Each method should have a clear purpose (aka contract); and you write test cases to ensure that those contracts are held up.

Sign up to request clarification or add additional context in comments.

2 Comments

If I make m1, m2 as public, there's no way of testing those individual functions apart from testing the complete constructor at once. I feel this is a common case that comes many times where constructor might call many functions like initializeVariables() etc etc.. How do we test those?
Again: the problem is: your constructor should probably not call public methods. Why would you want to make something like "initializeVariables" a public method that could be called later on ... again?!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.