Miller
Miller

Reputation: 744

Junit testing for a function

I have a confusion regarding Junit testing.For some functions(add function) with closed business logic we can make unit testing by asserting the function.

For example

public int add(int a,int b){
  int c = a+b;
  return c;
}

But for some function(as below example) in a route what methodology we have to do.

For example

public int foo(int totalnum){
  Zoo soo = new Zoo();
  int giraffNumber = soo.giraffe(totalnum);//here we are calling another method
  return giraffNumber;
}

For these kind of methods what approach we have to do.Does we need to write another class.

Can anybody please advise me with an example.

Upvotes: 2

Views: 353

Answers (2)

GhostCat
GhostCat

Reputation: 140457

Ideally you turn that local variable into a field of your class. Or, probably not a Zoo object, but a factory for Zoo objects.

This factor gets inserted via dependency injection. And now you can use a mocking framework such as Mockito to have the factory instance return a mocked Zoo object.

That is you gain control over such objects. The key thing is to not call new for business logic objects.

Upvotes: 2

Mike Nakis
Mike Nakis

Reputation: 61993

The dogmatic approach to unit testing is that you have to test only one thing at a time, which means that you are not allowed to use new in code to be tested, because this necessarily creates one more thing in addition to the thing that you have set out to test.

The way around this problem is Dependency Injection. This means that instead of your code reaching out there to fetch its dependencies, (an example of which is using new to create a class that your code wants to use,) your code is supplied its dependencies from the outside.

So, in the case of foo(), that would mean either passing an instance of Zoo as a parameter to foo(), or, better yet, passing a Zoo factory as a constructor parameter to the class that contains foo(), so that then foo() can invoke the factory to obtain an instance of Zoo.

This way, you can pass a specially made implementation of Zoo to use for testing, such as one created with the help of mockito.

Of course, there is also the non-dogmatic approach to unit testing, which says that you should view each thing to be tested as a black box, and not worry about how it is implemented, and instead only worry about obtaining the correct result for a certain input. And then there are those who point out that this is not unit testing, but integration testing. And then there is the realization that there is no such thing as unit testing, only integration testing. But by now we have entered the realm of philosophy.

Upvotes: 1

Related Questions