Mockito+PowerMock+Junit单元测试
一、单元测试用途
1、日常开发团队要求规范,需要对开发需求代码进行单元测试并要求行覆盖率达到要求,DevOps流水线也会开设相关门禁阀值阻断代码提交,一般新增代码行覆盖率80%左右。
二、Mock测试介绍
1、Mock是为了解决不同的单元之间由于耦合而难于开发、测试的问题。所以,Mock既能出现在单元测试中,也会出现在集成测试、系统测试过程中。Mock 最大的功能是帮你把单元测试的耦合分解开,如果你的代码对另一个类或者接口有依赖,它能够帮你模拟这些依赖,并帮你验证所调用的依赖的行为。
2、Mock 测试就是在测试活动中,对于某些不容易构造或者不容易获取的比较复杂的数据/场景,用一个虚拟的对象(Mock对象)来创建用于测试的测试方法。
3、Mock重要作用
Mock是为了解决不同的单元之间由于耦合而难于开发、测试的问题。所以,Mock既能出现在单元测试中,也会出现在集成测试、系统测试过程中。
Mock 最大的功能是帮你把单元测试的耦合分解开,如果你的代码对另一个类或者接口有依赖,它能够帮你模拟这些依赖,并帮你验证所调用的依赖的行为。
三、Mock测试所需依赖
1、主要引入mockito-core/powermock-core
<dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>4.5.1</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-core</artifactId><version>2.0.9</version></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4</artifactId><version>2.0.9</version></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-api-mockito2</artifactId><version>2.0.9</version><scope>test</scope></dependency>
Mockito和PowerMock都是单元测试模拟框架,用于模拟被测试类的依赖项。Mockito基于动态代理的方式实现,而PowerMock在Mockito基础上增加了类加载器以及字节码篡改技术,使其可以实现对private/static/final方法的Mock
四、Mock的核心功能
1、Mock对象创建
Mockito.mock(List.class); // Mock对象创建
public class VerifyMockExample {@Testpublic void testVerifyMock() {List<String> mockList = Mockito.mock(List.class);// 调用Mock对象的方法mockList.add("testCode");mockList.size();// 验证mockList.add("test")是否被调用过一次Mockito.verify(mockList,Mockito.times(1)).add("testCode");// 验证size()方法是否被调用过Mockito.verify(mockList,Mockito.times(1)).size();Assert.assertFalse(mockList.size()==1);}
}
verify系列方法
Mockito.verify/Mockito.times()验证调用次数
·verify(mock).methodCall():验证方法被调用
· verify(mock, times(n)).methodCall():验证方法被调用n次
· verify(mock, never()).methodCall():验证方法从未被调用
或者是通过注解来实现创建
@Mockprivate UserInfoMapper mockUserInfoMapper;@InjectMocksprivate UserInfoServiceImpl userInfoServiceImplUnderTest;
@Testpublic void testVerifyMock2(){List<String> mockList = Mockito.mock(List.class);mockList.add("Code1");mockList.add("Code2");// 验证是否调用两次Mockito.verify(mockList,Mockito.times(2));}
// 验证这个方法从没有被调用过Mockito.verify(userMapper, Mockito.never()).getUserById(1);userMapper.getUserById(1);// 验证这个方法至少调用了1次Mockito.verify(userMapper, Mockito.atLeastOnce()).getUserById(1);userMapper.getUserById(1);// 验证当前方法调用了2次Mockito.verify(userMapper, Mockito.times(2)).getUserById(1);
Mockito.when()使用when和thenReturn方法配置Mock对象的行为
Mockito.when( 对象.方法名 ).thenReturn( 自定义结果) //当调用了某个 Mock 对象的方法时,就回传我们想要的自定义结果。
thenReturn系列方法
//当使用任何整数值调用 userService 的 getUserById 方法时,就回传一个名字为 I'm mock 3 的 User 对象。
Mockito.when(userService.getUserById(Mockito.anyInt)).thenReturn( newUser( 3, "I'm mock"));
//限制只有当参数的数字是 3 时,才会回传名字为 I'm mock 3 的 user 对象。
Mockito.when(userService.getUserById( 3)).thenReturn( newUser( 3, "I'm mock"));
//当调用 userService 的 insertUser 方法时,不管传进来的 user 是什么,都回传 100。
Mockito.when(userService.insertUser(Mockito.any(User.class))).thenReturn( 100);
thenThrow系列方法
//当调用 userService 的 getUserById 时的参数是 8 时,抛出一个 RuntimeException。
Mockito.when(userService.getUserById( 8)).thenThrow( new RuntimeException( "mock throw exception"));
//如果方法没有返回值的话(即方法定义为 public void myMethod {...}),要改用 doThrow 抛出 Exception。
Mockito.doThrow( new RuntimeException( "mock throw exception")).when(userService.print);
@Testpublic void testVerifyMock3(){List<String> mockList = Mockito.mock(List.class);// 设置Mock对象的预期行为Mockito.when(mockList.get(0)).thenReturn("mockedValue");// 断言验证返回值Assert.assertEquals("mockedValue",mockList.get(0));}
实战案例:测试一个UserInfoServiceImpl层saveUser()方法.
原始方法:
@Transactional@Overridepublic void saveUser(UserInfo userInfo){userInfoMapper.saveUser(userInfo);}
单元测试:
@Testpublic void testSaveUser() {// Setupfinal UserInfo userInfo = new UserInfo();userInfo.setId(0);userInfo.setUserName("userName");userInfo.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());// Run the testuserInfoServiceImplUnderTest.saveUser(userInfo);// Verify the resultsMockito.verify(mockUserInfoMapper).saveUser(new UserInfo());}
原始方法:
@Overridepublic List<UserInfo> queryListByUserName(String userName) {return userInfoMapper.queryListByUserName(userName);}
单元测试方法:
@Testpublic void testQueryListByUserName() {// Setupfinal UserInfo userInfo = new UserInfo();userInfo.setId(0);userInfo.setUserName("userName");userInfo.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> expectedResult = Arrays.asList(userInfo);// Configure UserInfoMapper.queryListByUserName(...).final UserInfo userInfo1 = new UserInfo();userInfo1.setId(0);userInfo1.setUserName("userName");userInfo1.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo1.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> userInfos = Arrays.asList(userInfo1);when(mockUserInfoMapper.queryListByUserName("userName")).thenReturn(userInfos);// Run the testfinal List<UserInfo> result = userInfoServiceImplUnderTest.queryListByUserName("userName");// Verify the resultsassertThat(result).isEqualTo(expectedResult);}@Testpublic void testQueryListByUserName_UserInfoMapperReturnsNoItems() {// Setupwhen(mockUserInfoMapper.queryListByUserName("userName")).thenReturn(Collections.emptyList());// Run the testfinal List<UserInfo> result = userInfoServiceImplUnderTest.queryListByUserName("userName");// Verify the resultsassertThat(result).isEqualTo(Collections.emptyList());}
原始方法:
@Overridepublic List<UserInfo> queryUserInfoList(String createTime, List<Integer> idList) {return userInfoMapper.queryListByIds(createTime,idList);}
单元测试方法:
@Testpublic void testQueryUserInfoList() {// Setupfinal UserInfo userInfo = new UserInfo();userInfo.setId(0);userInfo.setUserName("userName");userInfo.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> expectedResult = Arrays.asList(userInfo);// Configure UserInfoMapper.queryListByIds(...).final UserInfo userInfo1 = new UserInfo();userInfo1.setId(0);userInfo1.setUserName("userName");userInfo1.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo1.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> userInfos = Arrays.asList(userInfo1);when(mockUserInfoMapper.queryListByIds("createTime", Arrays.asList(0))).thenReturn(userInfos);// Run the testfinal List<UserInfo> result = userInfoServiceImplUnderTest.queryUserInfoList("createTime", Arrays.asList(0));// Verify the resultsassertThat(result).isEqualTo(expectedResult);}@Testpublic void testQueryUserInfoList_UserInfoMapperReturnsNoItems() {// Setupwhen(mockUserInfoMapper.queryListByIds("createTime", Arrays.asList(0))).thenReturn(Collections.emptyList());// Run the testfinal List<UserInfo> result = userInfoServiceImplUnderTest.queryUserInfoList("createTime", Arrays.asList(0));// Verify the resultsassertThat(result).isEqualTo(Collections.emptyList());}
原始方法:Controller层,MockMvc
mockMvc.perform(request):执行一个HTTP请求,并返回ResultActions对象。
ResultActions.andExpect(expected):验证请求的处理结果,如状态码、响应体等。
ResultActions.andDo(handler):处理请求的响应,如将响应体写入文件等。
ResultActions.andReturn():返回已执行请求的结果,以便直接访问结果。
MockMvc.perform(request).andExpect(expected).andDo(handler).andReturn():链式调用,执行请求、验证结果并处理响应,返回结果。
@Slf4j
@RestController
public class UserInfoController {@Autowiredprivate UserInfoService userInfoService;/*** 查询全部列表* @return*/@RequestMapping("/boot/query/users")public List<UserInfo> getUserInfoList(){List<UserInfo> list = userInfoService.list();return list;}/*** 保存用户信息* @return*/@RequestMapping("/boot/save/user")public String saveUser(){try {UserInfo user=new UserInfo();user.setUserName("MyBatis Log Free");userInfoService.save(user);} catch (Exception e) {log.error("save user error", e);throw new GlobalException("save user error");}return "success";}@RequestMapping("/boot/query/users/ids")public List<UserInfo> getUserInfoListIds(){List<Integer> list = Arrays.asList(1, 3, 5);String createTime="2022-09-05 15:11:21";List<UserInfo> userInfos = userInfoService.queryUserInfoList(createTime,list);return userInfos;}@RequestMapping("/boot/query/users/like")public List<UserInfo> getUserInfoListLike(){List<UserInfo> infoList = userInfoService.queryListByUserName("A");return infoList;}@RequestMapping("/boot/save/userinfo")public void saveUserInfo(){UserInfo userInfo = new UserInfo();userInfo.setId(5);userInfo.setUserName("Puck");Date startTime = new Date();Date endTime = new Date();userInfo.setCreateTime(startTime);userInfo.setUpdateTime(endTime);userInfoService.saveUser(userInfo);}
}
单元测试方法如下:
@RunWith(SpringRunner.class)
@WebMvcTest(UserInfoController.class)
public class UserInfoControllerTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate UserInfoService mockUserInfoService;@Testpublic void testGetUserInfoList() throws Exception {// Setup// Configure UserInfoService.list(...).final UserInfo userInfo = new UserInfo();userInfo.setId(0);userInfo.setUserName("MyBatis Log Free");userInfo.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> userInfos = Arrays.asList(userInfo);when(mockUserInfoService.list()).thenReturn(userInfos);// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/query/users").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
// assertThat(response.getContentAsString()).isEqualTo("expectedResponse");}@Testpublic void testGetUserInfoList_UserInfoServiceReturnsNoItems() throws Exception {// Setupwhen(mockUserInfoService.list()).thenReturn(Collections.emptyList());// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/query/users").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("[]");}@Testpublic void testSaveUser() throws Exception {// Setupwhen(mockUserInfoService.save(new UserInfo())).thenReturn(false);// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/save/user").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("expectedResponse");verify(mockUserInfoService).save(new UserInfo());}@Testpublic void testGetUserInfoListIds() throws Exception {// Setup// Configure UserInfoService.queryUserInfoList(...).final UserInfo userInfo = new UserInfo();userInfo.setId(0);userInfo.setUserName("MyBatis Log Free");userInfo.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> userInfos = Arrays.asList(userInfo);when(mockUserInfoService.queryUserInfoList("2022-09-05 15:11:21", Arrays.asList(0))).thenReturn(userInfos);// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/query/users/ids").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("expectedResponse");}@Testpublic void testGetUserInfoListIds_UserInfoServiceReturnsNoItems() throws Exception {// Setupwhen(mockUserInfoService.queryUserInfoList("2022-09-05 15:11:21", Arrays.asList(0))).thenReturn(Collections.emptyList());// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/query/users/ids").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("[]");}@Testpublic void testGetUserInfoListLike() throws Exception {// Setup// Configure UserInfoService.queryListByUserName(...).final UserInfo userInfo = new UserInfo();userInfo.setId(0);userInfo.setUserName("MyBatis Log Free");userInfo.setCreateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());userInfo.setUpdateTime(new GregorianCalendar(2020, Calendar.JANUARY, 1).getTime());final List<UserInfo> userInfos = Arrays.asList(userInfo);when(mockUserInfoService.queryListByUserName("A")).thenReturn(userInfos);// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/query/users/like").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("expectedResponse");}@Testpublic void testGetUserInfoListLike_UserInfoServiceReturnsNoItems() throws Exception {// Setupwhen(mockUserInfoService.queryListByUserName("A")).thenReturn(Collections.emptyList());// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/query/users/like").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("[]");}@Testpublic void testSaveUserInfo() throws Exception {// Setup// Run the testfinal MockHttpServletResponse response = mockMvc.perform(get("/boot/save/userinfo").accept(MediaType.APPLICATION_JSON)).andReturn().getResponse();// Verify the resultsassertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());assertThat(response.getContentAsString()).isEqualTo("expectedResponse");verify(mockUserInfoService).saveUser(new UserInfo());}
}
@Mock用于模拟不属于 Spring 上下文的对象,而@MockBean用于模拟属于 Spring Boot 应用程序中的 Spring 上下文的对象。@MockBean提供与 Spring Boot 测试框架的无缝集成,并允许在测试期间用模拟对象轻松替换实际 bean
Mockito提供了多种参数匹配器(Matchers)用于更灵活的验证和配置行为:
import static org.mockito.ArgumentMatchers.*;
when(mockRepository.findById(anyInt())).thenReturn(Optional.of(user));
verify(mockRepository).findById(eq(1));
常见的匹配器包括:
·any():匹配任何参数
· anyInt():匹配任何整数参数
· eq(value):匹配特定值
· isNull():匹配null值
· notNull():匹配非null值
Mock异常
Mockito.when(userMapper.getUserById(Mockito.anyInt())).thenThrow(new RuntimeException("运行时错误"));Assertions.assertThrowsExactly(RuntimeException.class, () -> userMapper.getUserById(1));// 对于没有返回值的方法,不能使用thenThrow()来抛出异常,可以使用doThrow()来抛出异常。
Mockito.doThrow(new RuntimeException("运行时错误")).when(userMapper).getUserById(1);
Assertions.assertThrowsExactly(RuntimeException.class, () -> userMapper.getUserById(1));
@MockBean 是 Spring Boot 提供的注解,它用于在测试中创建一个 mock 对象,并将其注入到 Spring 上下文中,替换掉原来的真实 Bean。 需要使用SpringJUnit4ClassRunner.class之类的注解
@Mock: 用于代替Mockito.mock创建mock对象,创建一个Mock实例,需要基于JUnit5环境。@InjectMocks: 创建一个实例,其余用@Mock(或@Spy)注解创建的mock将被注入到用该实例中。
你要测试哪个类(如TemplateUserServiceImpl ),那么就用 @InjectMocks注解;被测试的类中通过 @Autowired注解注入了几个,那么测试类里面就用@Mock注解创建几个实例!
原始代码:
@Service
public class TemplateUserServiceImpl implements TemplateUserService {@Autowiredprivate NamedParameterJdbcTemplate jdbcTemplate;@Transactional@Overridepublic void saveUser() {UserInfo userInfo = new UserInfo();userInfo.setId(7);userInfo.setUserName("Boot");Date startTime = new Date();Date endTime = new Date();userInfo.setCreateTime(startTime);userInfo.setUpdateTime(endTime);// JdbcTemplate的写入datetime,使用in方式
// String sql="insert into user_info(user_name,create_time,update_time) values(:user_name,:create_time,:update_time)";String sql="insert into user_info(user_name,create_time,update_time) values(:userName,:createTime,:updateTime)";SqlParameterSource sqlParameterSource=new BeanPropertySqlParameterSource(userInfo);
// HashMap paramMap = new HashMap<>();
// paramMap.put("user_name",userInfo.getUserName());
// paramMap.put("create_time",userInfo.getCreateTime());
// paramMap.put("update_time",userInfo.getUpdateTime());
// jdbcTemplate.update(sql,paramMap);jdbcTemplate.update(sql,sqlParameterSource);}
}
对应单元测试代码:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;@RunWith(MockitoJUnitRunner.class)
public class TemplateUserServiceImplTest {@Mockprivate NamedParameterJdbcTemplate mockJdbcTemplate;@InjectMocksprivate TemplateUserServiceImpl templateUserServiceImplUnderTest;@Testpublic void testSaveUser() {// Setup// Run the testtemplateUserServiceImplUnderTest.saveUser();// Verify the resultsverify(mockJdbcTemplate).update(eq("insert into user_info(user_name,create_time,update_time) values(:userName,:createTime,:updateTime)"),any(SqlParameterSource.class));}@Testpublic void testSaveUser_NamedParameterJdbcTemplateThrowsDataAccessException() {// Setupwhen(mockJdbcTemplate.update(eq("insert into user_info(user_name,create_time,update_time) values(:userName,:createTime,:updateTime)"),any(SqlParameterSource.class))).thenThrow(DataAccessException.class);// Run the testassertThatThrownBy(() -> templateUserServiceImplUnderTest.saveUser()).isInstanceOf(DataAccessException.class);}
}
@MockBean 和 @SpyBean和@Spy以及@Mock的使用场景和区别
五、单元测试生成插件
1、IDEA中安装Squaretest插件使用
文件右键即可生成对应单元测试,需要修改测试用例,满足业务诉求。
2、破解插件过程
idea版本:
下载字节码编译工具:jclasslib。
jclasslib下载地址
JAR包路径:C:\Users\Administrator\AppData\Roaming\JetBrains\IntelliJIdea2023.3\plugins\Squaretest
说明:不用版本的Squaretest插件的jar包名称或许不一样,找空间最大的那个,约15M左右的那个。
最后一步点击保存按钮,选择“overwrite”时,此时一定要将idea关闭,否则会保存失败的.
最后破解成功,可以正常使用。
相关文章:
Mockito+PowerMock+Junit单元测试
一、单元测试用途 1、日常开发团队要求规范,需要对开发需求代码进行单元测试并要求行覆盖率达到要求,DevOps流水线也会开设相关门禁阀值阻断代码提交,一般新增代码行覆盖率80%左右。 二、Mock测试介绍 1、Mock是为了解决不同的单元之间由于…...
Ncat: bind to :::7777: Address already in use报错问题解决
问题描述 Ncat: bind to :::7777: Address already in use. QUITTING. 具体解决方法 If you are in linux environment try, Use netstat -tulpn to display the processeskill -9 <pid> This will terminate the process If you are using windows, Use netstat -…...
Docker 搭建mysql 连接超时问题,xxl-job启动mysql连接报错,禁用dns
1.本地连接Navicat报错信息,猜测是navicat默认连接超时导致的,后面换成idea一个插件虽然慢但连接上了 2013 - Lost connection to MySQL server at reading initial communication packet 2.启动xxl-job会报错,网上有人mysql驱动与数据库不匹…...
在线图片像素颜色拾取工具
在线图片像素颜色拾取工具,非常方便的一个工具,无需登录,用完就走。 包括中文和英文版本。 https://getcolor.openai2025.com...
Qt之登录界面(splash)
在上一篇多文档窗口设计(MDI)的基础上增加了一个登录界面(splash). 该模块可以扩展为常规的软件登录界面。 界面展示如下 如果用户名和密码输入正确,则调到MDI界面,如果用户名和密码一共输入三次以上,则程序强制退出…...
NotebookLM:Google 最新 AI 笔记助理解析与实战应用
NotebookLM:Google 最新 AI 笔记助理解析与实战应用 在 AI 驱动的生产力工具不断进化的今天,Google 推出的 NotebookLM(Notebook Language Model)成为了一款备受关注的智能笔记助理。它结合了 Google 的大语言模型(LL…...
软路由系统iStoreOS 一键安装 docker compose
一键安装命令 大家好!今天我来分享一个快速安装 docker-compose 的方法。以下是我常用的命令,当前版本是 V2.32.4。如果你需要最新版本,可以查看获取docker compose最新版本号 部分,获取最新版本号后替换命令中的版本号即可。 w…...
vue3本地文件下载
开发记录: vue3本地下载文件要把文件放到public下,如果放在src里面可能会出现这个问题...
纯代码实现给WordPress添加文章复制功能
在给wordpress添加内容时,有时会遇到文章复制的功能,但是wordpress又没有这个功能。把下面一段代码添加到functions.php文件中,就可以实现这个功能。 /** Function for post duplication. Dups appear as drafts. User is redirected to the…...
Redis 中 TTL 的基本知识与禁用缓存键的实现策略(Java)
目录 前言1. 基本知识2. Java代码 前言 🤟 找工作,来万码优才:👉 #小程序://万码优才/r6rqmzDaXpYkJZF 单纯学习Redis可以看我前言的Java基本知识路线!! 对于Java的基本知识推荐阅读: java框架…...
【PyQt】图像处理系统
[toc]pyqt实现图像处理系统 图像处理系统 1.创建阴影去除ui文件 2.阴影去除代码 1.创建阴影去除ui文件 UI文件效果图: 1.1QT Desiger设置组件 1.两个Pushbutton按钮 2.两个label来显示图像 3.Text Browser来显示输出信息 1.2布局的设置 1.先不使用任何La…...
Ruby语言的循环实现
Ruby语言的循环实现深入探讨 在程序设计中,循环是一种常见的控制结构,用于重复执行某些代码块。不同的编程语言提供了不同类型的循环结构,以满足不同的需求。Ruby是一种灵活且易于使用的编程语言,其循环实现方式独具一格…...
javaEE安全开发 SQL预编译 Filter过滤器 Listener 监听器 访问控制
前言 java开发和其他开发的不同并且更安全就是因为他拥有简单的预编译机制 filter 过滤器 和 listener 监听器 这个很重要 就是 web应用监听器和过滤器是在 Servlet 之前的并且 我们的请求和响应都需要经过 两者的同意才可以通过 缺一不可 、 Listener 安全方面 监听器…...
一体机cell服务器更换内存步骤
一体机cell服务器更换内存步骤: #1、确认grdidisk状态 cellcli -e list griddisk attribute name,asmmodestatus,asmdeactivationoutcome #2、offline griddisk cellcli -e alter griddisk all inactive #3、确认全部offline后进行关机操作 shutdown -h now #4、开…...
Hadoop•用Web UI查看Hadoop状态词频统计
听说这里是目录哦 通过Web UI查看Hadoop运行状态🐇一、关闭防火墙二、在物理计算机添加集群的IP映射三、启动集群四、进入HDFS的Web UI 词频统计🦩1、准备文本数据2、在HDFS创建目录3、上传文件4、查看文件是否上传成功5、运行MapReduce程序6、查看MapRe…...
rhel7.9利用有网络环境打包ansible
RHEL7.9激活(可省略) # 注册 subscription-manager register --usernameyour_username --passwordyour_password --auto-attach # 查看订阅状态 subscription-manager list # 将 “enabled1” 改为 “enabled0” vi /etc/yum/pluginconf.d/subscription-manager.conf 配置阿…...
vim文本编辑器三种模式的转换关系
输入模式 ———— 末行模式 输入模式和末行模式不能相互转换。 输入模式 ———— 命令模式 输入模式可以通过点击esc进入命令模式。 命令模式可以通过点击i进入输入模式。 末行模式 ———— 命令模式 末行模式可以通过点击esc进入命令模式。 命令模式可以通过shift&…...
深度学习:大模型Decoding+MindSpore NLP分布式推理详解
大模型推理流程 1. 用户输入提示词(Prompt) 假设用户输入为:“从前,有一只小猫,它喜欢……” 我们的目标是让模型生成一段完整的故事。 2. 模型处理用户输入 2.1 分词:输入提示被分词为模型可以理解的…...
【JVM中的三色标记法是什么?】
JVM中的三色标记法是什么? 一、基本概念二、标记过程三、优势与问题四、漏标与多标的解决方案三色标记法(Tri-color Marking Algorithm)是Java虚拟机(JVM)中一种用于追踪对象存活状态的垃圾回收算法。 它基于William D. Hana和Mark S. McCulleghan在1976年提出的两色标记法…...
数据库服务体系结构
1. 数据库服务应用配置 服务进行配置有什么作用? 实现服务运行启动 实现某些功能 应用配置有三种方式? 利用编译安装进行配置 编写配置文件信息 ,.默认的配置文件: /etc/my.cnf 利用启动命令参数配置信息,mysqld_safe --skip-grant-tables --…...
vscode项目依赖问题
必读 一定要将前端下拉的项目备份一下,很容易运行导致依赖报错,重新下载 命令 使用幽灵分解器安装 pnpm install 替代 npm install 设置淘宝NPM镜像源 yarn config set registry https://registry.npmmirror.com 查看目前依赖包的版本 npm list ant-d…...
R数据分析:有调节的中介与有中介的调节的整体介绍
单独的有调节的中介或者有中介的调节好多同学还大概能看明白,但是两个东西一起说我发现大部分同学就懵逼了。今天我就尝试将两种方法一起讲讲,重点帮助大家厘清两种方法的异同。 先从整体上看下两者的概念: 有中介的调节首先落脚在调节,调节作用必须是显著的,并且这个调…...
RabbitMQ-消息可靠性以及延迟消息
目录 消息丢失 一、发送者的可靠性 1.1 生产者重试机制 1.2 生产者确认机制 1.3 实现生产者确认 (1)开启生产者确认 (2)定义ReturnCallback (3)定义ConfirmCallback 二、MQ的持久化 2.1 数据持久…...
Hack The Box-Starting Point系列Oopsie
一. 答案 With what kind of tool can intercept web traffic? (什么样的工具可以拦截Web流量?) proxyWhat is the path to the directory on the webserver that returns a login page?(Web服务器上返回登录页面的目录路径是什么?) /cdn-cgi/loginWhat can be modified …...
Linux运维篇-PAM安全模块配置
PAM是什么? PAM(可插入认证模块)是UNIX操作系统上一个实现模块化的身份验证的服务。当程序需要对用户进行身份验证时加载并执行。PAM文件通常位于/etc/pam.d目录中。 而Linux-PAM,是linux可插拔认证模块,是一套可定制…...
麒麟V10系统上安装Oracle
以下是在麒麟V10系统上安装Oracle数据库的详细步骤: 安装前准备 检查系统版本:使用uname -a、cat /etc/os-release等命令检查服务器是麒麟V10系统。 配置固定IP和本地yum源: 挂载麒麟V10的iso文件到/mnt目录,如mount -o loop Ky…...
项目开发实践——基于SpringBoot+Vue3实现的在线考试系统(七)
文章目录 一、题库管理模块实现1、新增题目功能实现1.1 页面设计1.2 前端功能实现1.3 后端功能实现1.4 效果展示2、题目列表功能实现2.1 页面设计2.2 前端功能实现2.3 后端功能实现2.3.1 后端查询题目列表接口实现2.3.2 后端编辑试题接口实现2.4 效果展示二、代码下载一、题库管…...
Elasticsearch:Jira 连接器教程第二部分 - 6 个优化技巧
作者:来自 Elastic Gustavo Llermaly 将 Jira 连接到 Elasticsearch 后,我们现在将回顾最佳实践以升级此部署。 在本系列的第一部分中,我们配置了 Jira 连接器并将对象索引到 Elasticsearch 中。在第二部分中,我们将回顾一些最佳实…...
Vulnhub Earth靶机攻击实战(一)
导语 首先需要我们进入到https://vulnhub.com/entry/the-planets-earth,755/地址去获取Earth靶机,然后导入到VMware中,如下所示。 文章目录 导入虚拟机信息收集路径扫描破解密码反射Shell提权总结导入虚拟机 下载并导入虚拟机,如下所示。 信息收集 首先我们通过arp-sc…...
51单片机——DS18B20温度传感器
由于DS18B20数字温度传感器是单总线接口,所以需要使用51单片机的一个IO口模拟单总线时序与DS18B20通信,将检测的环境温度读取出来 1、DS18B20模块电路 传感器接口的单总线管脚接至单片机P3.7IO口上 2、DS18B20介绍 2.1 DS18B20外观实物图 管脚1为GN…...
万网主机建设网站流程/攀枝花seo
问题: 1、如何仅用队列结构实现栈结构? 2、如何仅用栈结构实现队列结构? 实现思路: 1、使用两个队列结构Queue1和Queue2 ,push操作一样,添加push()到Queue1,pop()核心是把 Queue1 除最后添加的元素"剪切"…...
兴化网站建设/怎么制作属于自己的网址
本帖最后由 wushaominkk 于 2019-3-18 16:54 编辑好久没更新,主要是这一段时间的事情太多了,秋招签了家北京的企业,找了个当地法院的兼职,兼职还是比较轻松,所以那段时间更新比较多,后来老师给了个问卷数据…...
外贸网站 英文/最快的新闻发布平台
Flex Builder3 的长处是代码的写作,flash的长处是前台界面的制作,如何将这两者的长处结合起来,做到Flex builder 中写代码,然后导入到Flash cs4中,本文用到的产品是flex builder3 ,flash cs 4这两种工具使用flex builder 3做一个SWC类库新建一个flex library Project ,然后新建…...
泰州网站建设 思创/百度推广助手怎么用
LNMP由于 Nginx 轻量与高效的性能,Linux Nginx Mysql PHP 的部署模式,被更多的应用于 PHP 的开发与生产环境中。本文介绍 Nginx php-fpm 的部署模式的安装与配置过程,先介绍下几个概念cgi 是 web 服务器如 Apache、Nginx 等与 php 解释器…...
做彩票网站要什么接口/网站优化推广方案
自从1995年Java语言出世以来,从未跌落过神坛,但最近Python语言被抄的太火,看下面这张最新的语言排行榜,独受宠爱的Java似乎要失宠了。从上面这张图我们可以看出,Python一直处于上升趋势,而Java明显有下滑的…...
wordpress批量倒入txt/竹子建站官网
原标题:用Python分析了 7 万款 App后,我们发现...本文中使用 Scrapy 爬取了豌豆荚全网 70,000 App ,并进行探索性分析。写在前面:若对数据抓取部分不感兴趣,可以直接下拉到数据分析部分。1 分析背景之前我们使用了 Scr…...