Jes*_*per 10 java testing spring spring-boot
起初,我的测试类上方有以下注释:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
Run Code Online (Sandbox Code Playgroud)
使用该配置,它会尝试连接到我的数据库,如果我的数据库未运行,则会出现此错误:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
Run Code Online (Sandbox Code Playgroud)
我希望我的测试在没有任何数据库连接的情况下运行,这就是我尝试更改注释的原因,所以我的测试类现在如下所示:
@RunWith(SpringRunner.class)
@DataJpaTest
@WebMvcTest(CitizenController.class)
@AutoConfigureMockMvc
public class CitizenControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CitizenRepository citizenRepository;
@MockBean
private WeeklyCareRepository weeklyCareRepository;
@MockBean
private SubCategoryCareRepository subCategoryCareRepository;
@Autowired
private ObjectMapper objectMapper;
private static List<Citizen> mockCitizenList;
private String citizenJson;
Run Code Online (Sandbox Code Playgroud)
但是,我现在收到另一个错误:
java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [controllers.CitizenControllerTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper)]
Run Code Online (Sandbox Code Playgroud)
是否可以在没有数据库连接的情况下运行我的测试?如果是这样,我做错了什么/错过了什么?
您可以在 @Test 方法中模拟将连接到存储库类中的数据库的方法。
@SpringBootTest
@AutoConfigureMockMvc
class StoreApplicationTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private CitizenRepository citizenRepository;
@Test
void contextLoads() {
}
@Test
public void test() {
Mockito.when(citizenRepository.getDataFromDB()).thenReturn("Something you'd like to Return");
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作后,citizenRepository.getDataFromDB() 在调用时将不会连接到数据库。
发表评论后更新:
然后你可以创建“src/test/resources”并将 application.properties 或 application.yml 从“src/main/resources”复制到该目录并注释 mysql 连接部分。
如果你没有“src/test/resources/application.properties”,那么 spring 将默认读取“src/main/resources/application.properties”并根据该文件配置项目,因为你有数据源配置spring会尝试连接数据库,如果数据库服务器宕机,就会失败。
归档时间: |
|
查看次数: |
23810 次 |
最近记录: |