jeudi 30 janvier 2020

How to test a maven service wich needs another service in java?

I have searched two days for an answer. I tried @Mock, @InjecktMock and @Spy with different additional things, but nothing worked how it was described in tutorials. Many Questions I found dealt with a Problem in Angular, this is my first spring-boot/maven project and have never worked with Angular.

I have a Basic Service for some values I want to be able to change only there but need them in multiple other services. I have written a shortened example of the base structure I want to test and I included the workaround I found for the moment, but would love to know how experienced programmers would go about this.

I have my configuration Service:

@Service
public class ConfigService {
    private final int initialLength = 4;

    public int getInitialLength() {
        return initialLength;
    }

    public double getInitialSquared() {
        return Math.pow(4,2);
    }

}

And another Service using it:

@Service
public class OtherService {

    @Autowired
    ConfigService configService;

    // How I surpassed it for now is overloading and only testing the second function
    String printLine() {
        return printLine(configService.getInitialLength());
    }

    String printLine(int length) {
        StringBuilder output = new StringBuilder();
        for (int i = 0; i < configService.getInitialLength(); i++) {
            output.append("-");
        }
        return output.toString();
    }

}

And my Test for now:

class OtherServiceTest {

    @injectMocks
    OtherService otherService = new OtherService();

    @Test
    void printLine() {
        AssertEquals("----", OtherService.printLine(4));
    }

}

Aucun commentaire:

Enregistrer un commentaire