Java Spring引导单元测试运行整个程序
我想用Spring Boot实现一个集成测试。我从Java Spring引导单元测试运行整个程序,java,spring,spring-boot,junit,spring-boot-test,Java,Spring,Spring Boot,Junit,Spring Boot Test,我想用Spring Boot实现一个集成测试。我从springbootstarter测试开始依赖项,版本2.2.5.发布版 我有以下组成部分: @Component public class MyMath { public int add(int a, int b) { return a + b; } } 主程序如下所示: @SpringBootApplication public class Main implements CommandLineRunne
springbootstarter测试开始
依赖项,版本2.2.5.发布版
我有以下组成部分:
@Component
public class MyMath {
public int add(int a, int b) {
return a + b;
}
}
主程序如下所示:
@SpringBootApplication
public class Main implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Autowired
private MyMath myMath;
@Override
public void run(String... args) throws Exception {
System.out.println(myMath.add(2, 3));
}
}
正如预期的那样——到目前为止,一切都很好。我想添加一个单元测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyMathTest {
@Autowired
private MyMath myMath;
@Test
public void testSaveAndList() {
assertEquals(5, myMath.add(2, 3));
}
}
这也可以,但根据日志,它执行整个程序。我不想运行程序本身,只想运行MyMath.add()
函数。我该怎么做
到目前为止,我尝试了以下方法:
提供了相同的结果@RunWith(SpringJUnit4ClassRunner.class)
- 省略
结果@SpringBootTest
NoSuchBeanDefinitionException
- 将代码重新格式化为使用bean而不是像下面这样的组件是可行的
MyMath
无注释:
public class MyMath {
public int add(int a, int b) {
return a + b;
}
}
Main
保持不变
@Configuration
public class AppConfig {
@Bean
public MyMath getMyMath() {
return new MyMath();
}
}
以及测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class MyMathTest {
@Autowired
private MyMath myMath;
@Test
public void testSaveAndList() {
assertEquals(5, myMath.add(2, 3));
}
}
所以我不能做的是在不运行整个程序的情况下测试一个组件。有什么能帮我的吗?谢谢 您不需要重构代码。让我的数学课保持原样
@Component
public class MyMath {
public int add(int a, int b) {
return a + b;
}
}
像这样改变你的测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyMath.class)
public class MyMathTest {
@Autowired
private MyMath myMath;
@Test
public void testSaveAndList() {
assertEquals(5, myMath.add(2, 3));
}
}
如果MyMath类有其他自动连接的依赖项,那么这就有点复杂了。然后你必须使用mock。如果你的MyMath类很简单,我不会用Spring来初始化它。没有必要,更重要的是,junit应该是快速的。因此,不要使用Spring上下文运行测试,而是将其更改为简单JUnit并创建类似于普通对象的MyMath:
public class MyMathTest {
private MyMath myMath = new MyMath();
@Test
public void testSaveAndList() {
assertEquals(5, myMath.add(2, 3));
}
}
我认为您不需要Spring提供的任何东西来运行此测试。尝试从测试类中删除所有与Spring相关的注释,不要注入MyMath,而是在测试类中的某个地方用
new
实例化它。只要@Test注释仍然存在,JUnit就应该把它取起来。尝试使用非Spring测试运行程序,更多信息。是的,测试add函数实际上不需要任何Spring的东西。但是,如果我有一个具有自动连接依赖项的组件,并且我想要测试它呢?我故意不想把这个例子复杂化。谢谢你,这就是我想要的!谢谢你的回答。事实上,我故意创造了这样一个简单的例子。这里的重点不是加法器,而是如何在Spring中创建单元测试。如果您真的需要Spring来创建JUnit测试,您应该始终提出这个问题。大多数情况下,您可以使用简单的构造函数创建对象,以便测试运行得更快。用SpringBootTest注释的测试被认为是集成测试。