当我们在开发SpringBoot项目的过程中,想要在我们开发的SpringBoot应用环境中进行单元测试时,我们可以新建一个Test类并在类上面加上@RunWith(SpringRunner.class)或者@RunWith(SpringJUnit4ClassRunner.class)注解(SpringRunner 继承了SpringJUnit4ClassRunner,没有扩展任何功能,只是前者名字较为简短)。此外我们还要在类上面加上@SpringBootTest(classes = xx.class),其中xx为你的SpringBoot项目中的应用启动类(就是那个含有main方法的类),我们就可以在Test类中注入Spring容器管理的Bean进行测试了,以下为示范代码:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TopicServiceApplication.class)
public class SpringBootApplicationTest {
@Autowired
private FastFileStorageClient fastFileStorageClient;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void uploadTest() throws FileNotFoundException {
File file = new File("d:\\humanImgs\\1.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
String extName = file.getName().substring(file.getName().lastIndexOf(".") + 1);
StorePath storePath = fastFileStorageClient.uploadFile(fileInputStream, file.length(), extName, null);
System.out.println("full path" + storePath.getFullPath());
System.out.println("path" + storePath.getPath());
}
@Test
public void redisTest(){
String commentLikeKey = RedisKeyFormatConsts.POST_USER_KRY_FORMAT + 11 + "::" + 22;
stringRedisTemplate.opsForSet().add(commentLikeKey, "11");
stringRedisTemplate.opsForSet().add(commentLikeKey, "22");
Set<String> userLikedCommentIds = stringRedisTemplate.opsForSet().members(commentLikeKey);
System.out.println(userLikedCommentIds);
}
}