Faking Unit Designers

I have a set of classes that have dependencies at instantiation, i.e. when creating an object of type A, it also creates another type B, which subsequently creates other types of C, etc.

For testing, I don’t need all the functionality of all levels to check the top ones, so I can use stubs or mocks, but since I have one explicit newin the constructors, I don’t see a direct path other than changing the code to use AbstractFactory and ensuring that it creates fakes during testing.

So, is there a way of “black magic” to crack the loader of Java classes to create fake test classes instead of the usual ones when creating objects with new?

Thank!

+3
source share
6 answers

Why not add a constructor that takes these dependencies as parameters, instead of creating them yourself in the constructor? Personally, I would add that one and delete the other :) Enabling dependencies makes the code easier to test and more flexible in the future (since you can easily add another implementation later without changing the code.)

+6
source

What you want is to use mock classes. Think about how to use any infrastructure for this. Here is a good one - https://jmockit.dev.java.net/

+2
source

, . . - .

, , .

+2

JMockit . , :

// In production code:
public final class ClassUnderTest
{
    private final SomeDependency dep;

    public ClassUnderTest(String someData)
    {
        dep = new SomeDependency(someData);
    }

    void methodToBeTested() { ... int i = dep.doSomething("xpto", true); ... }
}

final class SomeDependency
{
    int doSomething(String s, boolean b) { ... }
}

// In test code:
public final class MyTest
{
    @Test
    public void mockingInternalDependencies()
    {
        new Expectations()
        {
            SomeDependency mockedDep;

            {
                mockedDep.doSomething(anyString, anyBoolean); result = 123;
            }
        };

        new ClassUnderTest("blah blah").methodToBeTested();
    }
}
+1

, , DI, , , ( ), .

0

Source: https://habr.com/ru/post/1768187/


All Articles