簡體   English   中英

java.lang.AssertionError:預期狀態:<400> 但原為:<200> 預期:400 實際:200

[英]java.lang.AssertionError: Status expected:<400> but was:<200> Expected :400 Actual :200

所以,我今天一直在測試一個springboot MVC,當我運行測試時,我無法通過使用測試來激活錯誤:


  @Test
    void post_A_User_passwords_do_notMatch() throws  Exception {

         User newUser = new User("TestName", "TestEmail@email.com", "NOT_THE_SAME","password123", true);

        // * Building the request
        RequestBuilder postAUser = MockMvcRequestBuilders.post("/users")
                .contentType(MediaType.APPLICATION_JSON)
                .header("authorization", "Bearer " + accessToken)
                .content(objectMapper.writeValueAsString(newUser));

        // * Sending the request
        ResultActions posting = mockMvc.perform(postAUser);

        // * Analysing the result
        MvcResult mvcResult = posting
                .andExpect(status().isBadRequest())
                .andReturn();


    }

即使我以 JSON 形式通過模擬帖子傳遞數據,該錯誤也不會受到影響。 我得到的是:

java.lang.AssertionError:預期狀態:<400> 但原為:<200> 預期:400 實際:200

因此,我更改了實際的原始實體,以便實例字段具有匹配的密碼,然后是不匹配的密碼,嘿,當實體在實例字段中具有不匹配的密碼時,就會出現錯誤。 所以,這讓我得出結論,當調用映射時,將一個空白的用戶實體模板傳遞給服務(嗯,與在用戶模型中設置的相同),然后它貫穿業務服務,然后 JSON 數據在此發生后保存到 repo 中,然后在可以訪問的 JSON 中發送響應。

理想情況下,我希望能夠通過 JSON 數據命中錯誤,這樣如果傳入數據上的兩個密碼不匹配,則通過用戶服務激活錯誤。

所以,我有問題,關於測試,試圖命中錯誤和 output:

  1. 在沒有 JSON 數據的情況下,我是否對實體獲得了正確的結論。
  2. 如果有任何數據保存在 JAVA 端(IntelliJ)中的 JAVA 中,並且它不僅保留在數據庫中並作為 JSON 響應返回。
  3. 一個人怎么會遇到錯誤?

用戶 controller 和用戶服務的實體和相關部分發布在下面。 我只是為用戶存儲庫擴展一個 CRUD 存儲庫。 我已將 spring 安全設置為允許所有路徑。

package bookapp.backend.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "users")
@Getter @Setter
public class User {
    @Id // Change to UUID later after testing
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Integer id;

    @Column
    @JsonProperty("userName")
    private String userName;

    @Column
    private String email;

    @Column
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY, value = "password")
    private String password = "";

    @Transient
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column
    private String passwordConfirmation = "";

    @Column
    private Boolean isAdmin;

    // Relationships

    // reviews
    @OneToMany
    private List<Review>reviewList;

    // Not sure how the relationship between myLibrary and myReadBooks with books will work
    // Leaving this as it is for now, but might have to change annotations etc

    @OneToMany
    private List<Book> myLibrary;

    @OneToMany
    private List<Book> myReadBooks;

    // * Constructors Added for Testing
    public User() {
    }

    public User(String userName, String email, String password, String passwordConfirmation, Boolean isAdmin) {
        this.userName = userName;
        this.email = email;
        this.password = password;
        this.passwordConfirmation = passwordConfirmation;
        this.isAdmin = isAdmin;
    }

    // * ToString Added for Testing
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", email='" + email + '\'' +
                ", password='" + password + '\'' +
                ", passwordConfirmation='" + passwordConfirmation + '\'' +
                ", isAdmin=" + isAdmin +
                '}';
    }
}

controller中的controller方法

 // ! Create a new user
    @PostMapping("/users")
    public User postUser(@RequestBody @Valid User user) { return userService.createUser(user); }


它在服務中也有這個方法:

    // ! This method creates a new user in the UserRepo
    public User createUser(User user) {
        // ! Check if password matches the passwordConfirmation

        if (!user.getPassword().equals(user.getPasswordConfirmation())) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Password does not match password confirmation");
        }

        // ! Check if the user already exists in the UserRepo
//        Optional<User> existingUser = userRepo.findByUsername(user.getUserName());
//        if (existingUser.isPresent()) {
//            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "A user with that username already exists");
//        }

        // ! Encrypt password with bCrypt
        String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        return userRepo.save(user);
    }

@Test void post_A_User_ErrorCheck2() 拋出異常 {

    objectMapper.disable(MapperFeature.USE_ANNOTATIONS);

    User newUser = new User("testName", "TestEmail@email.com", "password$DO_NOT_MATCH123","password$123", true);

    // *  Building the request
    RequestBuilder postAnUser = MockMvcRequestBuilders
            .post("/users")
            .contentType(MediaType.APPLICATION_JSON)
            .header("authorization", "Bearer " + accessToken)
            .content(objectMapper.writeValueAsString(newUser));

    // * Performing the Request
    ResultActions postingAnUser = mockMvc.perform(postAnUser);

    // * Analysing the results
    MvcResult testResult = postingAnUser
            .andExpect(status().isNotFound())
            .andReturn();
}

因此,事實證明,注釋實體的 JSON 忽略屬性 @JsonProperty(access = JsonProperty.Access.WRITE_ONLY, value = "password") 會阻止數據的序列化。 這發生在測試中存在的 object 映射器 object 上。 需要 @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 來防止密碼在響應中返回,但在這種情況下,我們使用 objectMapper.disable(MapperFeature.USE_ANNOTATIONS) 來允許它們被寫入。 此外,@Test 中的測試有一個錯誤 isBadrequest() 與用戶服務中的 HttpStatus.NOT_FOUND 錯誤不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM