Question

For a test I like to create a new instance of ComplicatedClass . In reality it's very complicated to crate this instance, but I don't need the real constructor to run nor any of it's data. All I need is an object of ComplicatedClass. How can I do that?

public class ComplicatedClass {

    public ComplicatedClass(/* lots of dependencies */) {
  }


}


@Test
public class SomeTest {

    public void test1() {

        ComplicatedClass complicatedInstance = /* new ComplicatedClass(); /*

        AnotherClass ac = new AnotherClass(complicatedInstance);

        /* ... */
    }

}
Was it helpful?

Solution

@Tested annotation does this:

@Tested ComplicatedClass complicatedInstance;

That's it. Please note that the above won't do any mocking. It is just convenient way of creating instances without calling consturctors, etc.

If you want ComplicatedClass to be mocked, use @Mocked annotation:

@Mocked ComplicatedClass complicatedInstance;

In this case, you also get your instance automatically created, but the instance is mocked.

OTHER TIPS

@Tested internally instantiates the class object.

But in case of Junit test case writing of singleton class how @Tested internally creates instance because for singleton private constructor is there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top