Wondercease

浙ICP备2022017321号

常用注解(Json,测试)

json 数据处理

过滤 json 数据

@JsonIgnoreProperties 作用在类上用于过滤掉特定字段不返回或者不解析。

@JsonIgnore一般用于类的属性上,作用和上面的@JsonIgnoreProperties 一样。

//生成json时将userRoles属性过滤
@JsonIgnoreProperties({“userRoles”})
public class User {

private String userName;
private String fullName;
private String password;
@JsonIgnore
private List<UserRole> userRoles = new ArrayList<>();

}

格式化 json 数据

@JsonFormat一般用来格式化 json 数据

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern=”yyyy-MM-dd’T’HH:mm:ss.SSS’Z'”, timezone=”GMT”)
private Date date;

 扁平化对象

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;

  @Getter
  @Setter
  @ToString
  public static class Location {
     private String provinceName;
     private String countyName;
  }
  @Getter
  @Setter
  @ToString
  public static class PersonInfo {
    private String userName;
    private String fullName;
  }
}
未扁平化之前:
{
    "location": {
        "provinceName":"xxx",
        "countyName":"xxx"
    },
    "personInfo": {
        "userName": "xxx",
        "fullName": "xxx"
    }
}
扁平对象之后:
{
  "provinceName":"xx",
  "countyName":"xx",
  "userName": "xxx",
  "fullName": "xxx"
}

测试相关

@ActiveProfiles一般作用于测试类上, 用于声明生效的 Spring 配置文件

@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("test")
@Slf4j
public abstract class TestBase {
  ......
}
@Test声明一个方法为测试方法

@Transactional被声明的测试方法的数据会回滚,避免污染测试数据。

@WithMockUser Spring Security 提供的,用来模拟一个真实用户,并且可以赋予权限

    @Test
    @Transactional
    @WithMockUser(username = "user-id-181xxx", authorities = "xxx")
    void should_import_student_success() throws Exception {
        ......
    }

发表评论

您的电子邮箱地址不会被公开。