UT Case

Mock

public class UtCaseController   {

    private MockMvc mvc;

    @InjectMocks
    private DeclarationController declarationController;

    @Mock
    private DeclarationService declarationService;

    @Mock
    private ConfirmationPdfService confirmationPdfService;

    @Mock
    private QueryHistoryService queryHistoryService;

    @Mock
    private SubmitVersionService submitVersionService;

    @Mock
    private JPAQueryFactory queryFactory;

    /**
     * 分页注入的参数
     */
    @InjectMocks
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Mock
    AuditLogService auditLogService;


    @Mock
    ObjectMapper objectMapper;



    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);//这句话执行以后,service自动注入到controller中。
        mvc = MockMvcBuilders.standaloneSetup(declarationController).setCustomArgumentResolvers(pageableArgumentResolver).build();
        initJwt();
    }

    private void initJwt() {
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("123456", "123456"));
        SecurityContextHolder.setContext(securityContext);
        Optional<String> login = SecurityUtils.getCurrentUserLogin();
    }



    @ApiOperation(value = "savePerInfo")
    @Test
    void savePerInfo() throws Exception {
        String uri = "/api/rp/declaration/savePerInfo";
        Mockito.when(declarationService.saveRpInfo(Mockito.anyObject())).thenReturn(true);
        doNothing().when(auditLogService).save(Mockito.anyObject());
        MvcResult mvcResult = this.mvc.perform(MockMvcRequestBuilders.post(uri)
            .contentType(MediaType.APPLICATION_JSON)
            .content("JsonStr"))
            .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String resultBody = mvcResult.getResponse().getContentAsString();
        assertThat(status).isEqualTo(200);
        System.out.println("成功!");
    }



    @ApiOperation(value = "saveTransferDate")
    @Test
    void saveTransferDate() throws Exception {
        String uri = "/api/rp/declaration/saveTransferDate";
        Mockito.when(declarationService.saveTransferDate(Mockito.anyObject(),Mockito.anyString())).thenReturn(true);
        doNothing().when(auditLogService).save(Mockito.anyObject());
        MvcResult mvcResult = this.mvc.perform(MockMvcRequestBuilders.post(uri)
            .param("transferDate","2020-12-27")
            .param("zhanghao","22333")
        ).andReturn();
        int status = mvcResult.getResponse().getStatus();
        String resultBody = mvcResult.getResponse().getContentAsString();
        assertThat(status).isEqualTo(200);
        System.out.println("成功!");
    }

    /**
     *  上传文件
     * @throws Exception
     */
    @ApiOperation(value = "submitRPForm")
    @Test
    void submitRPForm() throws Exception {
        String url="/api/rp/declaration/submitRPForm";
        File file = new File("C:\\Users\\2\\work\\design\\pdf\\PDFDemo.pdf");
        //文件之外的参数
        String pwid = "22233";
        Mockito.when(declarationService.submitRPForm(Mockito.anyString())).thenReturn(true);
        MockMultipartFile firstFile = new MockMultipartFile("file", "RPForm.pdf",
            "application/pdf", new FileInputStream(file));
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.fileUpload(url)
            .file(firstFile)//文件
            .param("pwid", pwid))
            .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(status).isEqualTo(200);
        assertThat(content);
    }

    /**
     * 下载
     * @throws Exception
     */

    @ApiOperation(value = "downRpForm")
    @Test
    void downRpForm() throws Exception {
        String uri = "/api/rp/declaration/downRpForm";
        byte[]  result =  new byte[]{};
        Mockito.when(declarationService.downRpForm(Mockito.anyString())).thenReturn(result);
        mvc.perform(MockMvcRequestBuilders.post(uri).param("pwid","ddddf")).andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(new ResultHandler() {
                @Override
                public void handle(MvcResult result) throws Exception {
                    result.getResponse().setCharacterEncoding("UTF-8");
                    MockHttpServletResponse contentRespon = result.getResponse();
                    InputStream contentInStream = new ByteArrayInputStream(
                        contentRespon.getContentAsByteArray());
                    String fileName = GlobalConstant.df2.format(LocalDate.now()) + ".xlsx";
                    String filePath =  "./"+"test-"+fileName;
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    OutputStream out = new FileOutputStream(file);
                    out.write(contentInStream.read());
                    contentInStream.close();
                    out.close();
                    Assert.assertTrue(file.exists());
                }
            });
    }


    /**
     * 分页
     * @throws Exception
     */
    @Test
    public void fetchQueryHistory() throws Exception {
        String uri = "/api/rp/queryhistory/fetchQueryHistory";
        QueryHistoryResultVO result =  new QueryHistoryResultVO();
        Mockito.when(queryHistoryService.fetchQueryHistory(Mockito.any(),Mockito.any(),Mockito.any(),Mockito.any())).thenReturn(result);
        MvcResult mvcResult = this.mvc.perform(MockMvcRequestBuilders.post(uri)
            .param("page","1")
            .param("size","10")
            .param("sort","id,desc")
            .contentType(MediaType.APPLICATION_JSON))
            .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(status).isEqualTo(200);
        System.out.println("成功!");
    }


    @ApiOperation(value = "getRpInfo")
    @Test
    void getRpInfo() throws Exception {
        String uri = "/api/rp/declaration/getPerInfo";
        RpInfoVO result = new  RpInfoVO();
        Mockito.when(declarationService.findRpInfoByPwid(Mockito.anyString())).thenReturn(result);
        MvcResult mvcResult = this.mvc.perform(MockMvcRequestBuilders.post(uri)
            .param("pwid","wwssss")
        ).andReturn();
        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();
        RpInfoVO resultBody = JsonMapper.getInstance().readValue(content, new TypeReference<RpInfoVO>() {
        });
        assertThat(status).isEqualTo(200);
        System.out.println("成功!");
    }

}



@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
@ActiveProfiles("local")
public class ExcoServiceImplTest2 {


    @Autowired
    ExcoRepository excoRepository;



  @Test
    public void validateExco() {
        Boolean aBoolean = excoService.validateExco("1223");
        System.out.println("122 is a Directors:"+aBoolean);
        Boolean aBoolean1 = excoService.validateExco("223");
        System.out.println("223 is a Directors:"+aBoolean1);
        Boolean aBoolean2 = excoService.validateExco("123");
        System.out.println("123 is a Directors:"+aBoolean2);
        Boolean aBoolean3 = excoService.validateExco("234");
        System.out.println("234 is a Directors:"+aBoolean3);
    }

    @Test
    public void getEmailListbypwid() {
        String emailListbypwid = excoService.getEmailListbypwid("123");
        System.out.println(emailListbypwid);
        String emailListbypwid1 = excoService.getEmailListbypwid("234");
        System.out.println(emailListbypwid1);

    }

    @Before
    public void setUp() throws Exception {
        List< RpInfoEntity> rpList =new ArrayList<>();
        rpList.add(RpInfoEntity.builder()
            .pwid("123")
            .department(staticDataRepository.findByConfValue("Ventures").get())
            .roleAppointDate(new HashSet<RoleAppointEntity>(){{
                add(RoleAppointEntity.builder()
                    .role(staticDataRepository.findByConfValue("ors").get())
                    .build());
            }})
            .build());
        rpList.add(RpInfoEntity.builder()
            .pwid("234")
            .department(staticDataRepository.findByConfValue("Ventures").get())
            .roleAppointDate(new HashSet<RoleAppointEntity>(){{
                add(RoleAppointEntity.builder()
                    .role(staticDataRepository.findByConfValue("China").get())
                    .build());
            }})
            .build());
        rpList.add(RpInfoEntity.builder()
            .pwid("223")
            .department(staticDataRepository.findByConfValue("Compliance").get())
            .roleAppointDate(new HashSet<RoleAppointEntity>(){{
                add(RoleAppointEntity.builder()
                    .role(staticDataRepository.findByConfValue("China").get())
                    .build());
                add(RoleAppointEntity.builder()
                    .role(staticDataRepository.findByConfValue("vitoty").get())
                    .build());
            }})
            .build());

        rpInfoRepository.saveAll(rpList);


        List<ExcoEntity> list = new ArrayList<>();
        list.add(ExcoEntity.builder()
            .pwid("123")
            .department(staticDataRepository.findByConfValue("Ventures").get())
            .build());
        list.add( ExcoEntity.builder()
            .pwid("234")
            .department(staticDataRepository.findByConfValue("Compliance").get())
            .build());
        list.add( ExcoEntity.builder()
            .pwid("23344")
            .department(staticDataRepository.findByConfValue("Ventures").get())
            .build());
        excoRepository.saveAll(list);
    }
}
public class JsonMapper extends ObjectMapper {

    private static final long serialVersionUID = 1L;

    private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);

    private static JsonMapper mapper;

    public JsonMapper() {
        this(JsonInclude.Include.ALWAYS);
    }

    public JsonMapper(JsonInclude.Include include) {
        // 设置输出时包含属性的风格
        if (include != null) {
            this.setSerializationInclusion(include);
        }
        // 允许单引号、允许不带引号的字段名称
        this.enableSimple();
        this.registerModule(new JavaTimeModule());
        this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        this.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false);
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 空值处理为空串
        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {

            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
                jgen.writeString("");
            }
        });
    }

    /**
     * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
     */
    public static JsonMapper getInstance() {
        if (mapper == null) {
            mapper = new JsonMapper().enableSimple();
        }
        return mapper;
    }

    /**
     * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
     */
    public static JsonMapper nonDefaultMapper() {
        if (mapper == null) {
            mapper = new JsonMapper(JsonInclude.Include.NON_DEFAULT);
        }
        return mapper;
    }

    /**
     * 转换为JSON字符串
     *
     * @param object
     * @return
     */
    public static String toJsonString(Object object) {
        return JsonMapper.getInstance().toJson(object);
    }

    /**
     * 测试
     */
//    public static void main(String[] args) {
//        List<Map<String, Object>> list = Lists.newArrayList();
//        Map<String, Object> map = Maps.newHashMap();
//        map.put("id", 1);
//        map.put("pId", -1);
//        map.put("name", "根节点");
//        list.add(map);
//        map = Maps.newHashMap();
//        map.put("id", 2);
//        map.put("pId", 1);
//        map.put("name", "你好");
//        map.put("open", true);
//        list.add(map);
//        String json = JsonMapper.getInstance().toJson(list);
//        System.out.println(json);
//    }

    /**
     * Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
     */
    public String toJson(Object object) {

        try {
            return this.writeValueAsString(object);
        } catch (IOException e) {
            logger.warn("write to json string error:" + object, e);
            return null;
        }
    }

    /**
     * 反序列化POJO或简单Collection如List<String>. 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合. 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
     *
     * @see #fromJson(String, JavaType)
     */
    public <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return this.readValue(jsonString, clazz);
        } catch (IOException e) {
            logger.warn("parse json string error:" + jsonString, e);
            return null;
        }
    }

    /**
     * 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
     *
     * @see #createCollectionType(Class, Class...)
     */
    @SuppressWarnings("unchecked")
    public <T> T fromJson(String jsonString, JavaType javaType) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            return (T) this.readValue(jsonString, javaType);
        } catch (IOException e) {
            logger.warn("parse json string error:" + jsonString, e);
            return null;
        }
    }

    /**
     * 構造泛型的Collection Type如: ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class) HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
     */
    public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
     */
    @SuppressWarnings("unchecked")
    public <T> T update(String jsonString, T object) {
        try {
            return (T) this.readerForUpdating(object).readValue(jsonString);
        } catch (JsonProcessingException e) {
            logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        } catch (IOException e) {
            logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        }
        return null;
    }

    /**
     * 輸出JSONP格式數據.
     */
    public String toJsonP(String functionName, Object object) {
        return toJson(new JSONPObject(functionName, object));
    }

    /**
     * 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
     */
    public JsonMapper enableEnumUseToString() {
        this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        return this;
    }

    /**
     * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。 默认会先查找jaxb的annotation,如果找不到再找jackson的。
     */
    public JsonMapper enableJaxbAnnotation() {
        JaxbAnnotationModule module = new JaxbAnnotationModule();
        this.registerModule(module);
        return this;
    }

    /**
     * 允许单引号 允许不带引号的字段名称
     */
    public JsonMapper enableSimple() {
        this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        return this;
    }

    /**
     * 取出Mapper做进一步的设置或使用其他序列化API.
     */
    public ObjectMapper getMapper() {
        return this;
    }

}

### UThash 使用方法与教程 #### 增加元素到哈希表 为了向UTHASH中的哈希表增加元素,可以定义结构体并利用宏`UT_hash_add`来完成这一过程。下面的例子展示了如何创建一个新的键值对,并将其加入到已有的哈希表中[^1]。 ```c #include "uthash.h" struct my_struct { int id; /* key */ char name[10]; UT_hash_handle hh; /* makes this structure hashable */ }; void add_user(struct my_struct **users, int user_id, const char *user_name) { struct my_struct *s; HASH_FIND_INT(*users, &user_id, s); /* id already in the hashtables? */ if (s==NULL) { s = (struct my_struct *)malloc(sizeof(struct my_struct)); memset(s, 0, sizeof(struct my_struct)); /* zero it out*/ s->id = user_id; strncpy(s->name,user_name,sizeof(s->name)-1); HASH_ADD_INT( *users, id, s ); /* id: name of key field */ } else { // Handle duplicate ID case here. } } ``` #### 删除哈希表中的元素 删除哈希表里的某个节点可以通过调用`HASH_DEL`函数实现,之后再释放该节点所占用的空间即可。 ```c void delete_user(struct my_struct **users, struct my_struct *user_to_delete){ HASH_DEL(*users, user_to_delete); free(user_to_delete); } ``` #### 修改已有记录的信息 当需要更新现有条目的时候,先通过查找定位目标项的位置,接着修改其属性值。 ```c void update_user(struct my_struct **users, int user_id, const char* new_name){ struct my_struct *s; HASH_FIND_INT(*users, &user_id, s); if (s != NULL) { strncpy(s->name,new_name,strlen(new_name)+1); } } ``` #### 遍历整个哈希表 遍历所有存储的数据项可借助于循环迭代器来进行访问每一个成员对象。 ```c void traverse_users(struct my_struct *users){ struct my_struct *current_user,*tmp; HASH_ITER(hh, users, current_user,tmp){ printf("ID:%d Name:%s\n",current_user->id,current_user->name ); } } ``` 上述代码片段演示了基本的操作方式,更多高级特性和细节可以在官方文档或者GitHub页面上找到更多信息[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值