标题翻译
How to test a maven service which needs another service in java?
问题
我已经搜索了两天以寻找答案。我尝试了@Mock、@InjectMock和@Spy,并尝试了不同的附加操作,但是没有任何一个按照教程中描述的那样工作。我找到的许多问题都涉及Angular中的问题,这是我第一个spring-boot/maven项目,以前从未使用过Angular。
我有一个基本的服务用于一些我希望只能在那里更改的值,但是需要在多个其他服务中使用它们。我已经编写了一个缩短版的示例,展示了我想要测试的基本结构,并且我包含了我目前找到的解决方法,但我很想知道有经验的程序员会如何处理这个问题。
我有一个配置服务:
@Service
public class ConfigService {
private final int initialLength = 4;
public int getInitialLength() {
return initialLength;
}
public double getInitialSquared() {
return Math.pow(4, 2);
}
}
还有另一个使用它的服务:
@Service
public class OtherService {
@Autowired
ConfigService configService;
// 目前我如何绕过它是通过重载,只测试第二个函数
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();
}
}
以及我的目前的测试:
class OtherServiceTest {
@InjectMocks
OtherService otherService = new OtherService();
@Test
void printLine() {
AssertEquals("----", OtherService.printLine(4));
}
}
英文翻译
I have searched two days for an answer. I tried @Mock, @InjectMock 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));
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论