{"id":16619498,"url":"https://github.com/guoguang/spring_junit_mockito_example","last_synced_at":"2026-04-18T21:04:23.111Z","repository":{"id":42540956,"uuid":"271543276","full_name":"GuoGuang/spring_junit_mockito_example","owner":"GuoGuang","description":"如何写好一个单元测试，使用junit_mockito完成","archived":false,"fork":false,"pushed_at":"2023-12-05T22:08:00.000Z","size":35,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-11T07:16:22.077Z","etag":null,"topics":["blog-junit","junit","mockito","test","test-case"],"latest_commit_sha":null,"homepage":"https://codeway.me","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GuoGuang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-06-11T12:42:02.000Z","updated_at":"2021-10-26T02:32:50.000Z","dependencies_parsed_at":"2024-11-17T04:01:57.014Z","dependency_job_id":null,"html_url":"https://github.com/GuoGuang/spring_junit_mockito_example","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/GuoGuang/spring_junit_mockito_example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GuoGuang%2Fspring_junit_mockito_example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GuoGuang%2Fspring_junit_mockito_example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GuoGuang%2Fspring_junit_mockito_example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GuoGuang%2Fspring_junit_mockito_example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GuoGuang","download_url":"https://codeload.github.com/GuoGuang/spring_junit_mockito_example/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GuoGuang%2Fspring_junit_mockito_example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31984558,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T20:23:30.271Z","status":"ssl_error","status_checked_at":"2026-04-18T20:23:29.375Z","response_time":103,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blog-junit","junit","mockito","test","test-case"],"created_at":"2024-10-12T02:42:07.681Z","updated_at":"2026-04-18T21:04:23.079Z","avatar_url":"https://github.com/GuoGuang.png","language":"Java","readme":"## spring_junit_mockito_example\n如何写好一个单元测试，使用junit_mockito完成\n\n\n## 单元测试\n单元测试是从测试**最小单元**为维度展开，也就是只测一个方法，只关注代码逻辑，其他的都不关心，这里我使用mockito+junit为案例演示\n\n### 配置Mockito和MockMvc\n```\npublic class UserControllerUnitTest {\n\n    private MockMvc mockMvc;\n\n\t/**\n\t * 被测类中用的类使用@Mock模拟\n\t */\n\t@Mock\n    private UserService userService;\n\n\t/**\n\t * 模拟被测类\n\t */\n\t@InjectMocks\n    private UserController userController;\n\n    @Before\n    public void init(){\n        MockitoAnnotations.initMocks(this);\n        mockMvc = MockMvcBuilders\n                .standaloneSetup(userController)\n                .addFilters(new CORSFilter())\n                .build();\n    }\n    \n    @Ignore\n\t@Test\n\tpublic void test_page() throws Exception {\n\t\t/*MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get(\"/welcomeController\").param(\"pn\", \"5\"))\n\t\t\t\t.andReturn();\n\t\t//请求成功以后，请求域中会有pageInfo；我们可以取出pageInfo进行验证\n\t\tMockHttpServletRequest request = result.getRequest();\n\t\tPageInfo pi = (PageInfo) request.getAttribute(\"pageInfo\");\n\t\tassertEquals(1,pi.getPageNum());*/\n\t}\n}\n\n```\n\n### 查询所有数据\n\n```\n @Test\n    public void test_get_all_success() throws Exception {\n        List\u003cUser\u003e users = Arrays.asList(\n                new User(1, \"Foo\"),\n                new User(2, \"Bar\"));\n\n        // 执行userService.getAll()时，返回users，这里是为了模拟/user接口的userService调用getAll返回的数据\n        when(userService.getAll()).thenReturn(users);\n\n        mockMvc.perform(get(\"/user\"))\n                .andExpect(status().isOk())\n                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))\n                .andExpect(jsonPath(\"$\", hasSize(2)))\n                .andExpect(jsonPath(\"$[0].id\", is(1)))\n                .andExpect(jsonPath(\"$[0].username\", is(\"Foo\")))\n                .andExpect(jsonPath(\"$[1].id\", is(2)))\n                .andExpect(jsonPath(\"$[1].username\", is(\"Bar\")));\n\n        // 验证调用次数\n        verify(userService, times(1)).getAll();\n        verifyNoMoreInteractions(userService);\n    }\n```\n\n\n\n## 集成测试\n集成测试每次测试都需要启动一次容器\n\n```\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class ResourceServiceTest {\n\n    @Autowired\n    private ResourceService resourceService;\n\n    @Test\n    public void findResourceByCondition() {\n        QueryVO queryVO = new QueryVO();\n        List\u003cResource\u003e dictByCondition = resourceService.findResourceByCondition(new Resource(), queryVO);\n        Assert.assertTrue(dictByCondition.size() \u003e 0);\n\n    }\n}\n```\n\n\n实际开发中业务并非如此简单，可能涉及三方、MQ、等中间件服务，所以测试覆盖率一般80%左右","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fguoguang%2Fspring_junit_mockito_example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fguoguang%2Fspring_junit_mockito_example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fguoguang%2Fspring_junit_mockito_example/lists"}