0

Suppose we have a class like this :-

class A {
internal val obj : Obj      
     get() = Application.getbean(Obj::class) 
fun method1(){
val result = obj.somefunc()
..../code/
  }
fun method2(){
...../code/
  }
}

I wan't to write unit test using the junit mockito framework to test the functionality of method1 and wan't to mock obj object . In some other threads on stackoverflow people has suggested to use constructor dependency injected but that is not possible in my case because of the issue of circular dependency . In some other answers people has suggested to move this object instantiation inside the method ,but i don't want to go that way .Is there any way to mock this obj object.

1 Answers1

0

It's very hard to unit test code, that is written in a non-testable way. That is why you should inject dependencies and not to hold them, that is why you should obtain objects and not to create them by yourself. If you're assume that your code might be tested, always think how first.

In your case it's a bit difficult to mock Obj, but not impossible since the actual creation (constructor calling) of the object is done with a different class (not the one being tested).

In your example you're using static method, maybe you can mock it's behavior with a PowerMockito? Please take a look at this answer.

Other than that, I just can suggest to change the code. To inject object creating class as a dependency or use some other approaches, which might involve some architectural changes.

Demigod
  • 5,073
  • 3
  • 31
  • 49