1
0

More than 1 year has passed since last update.

[エラー]SpringBoot Repository UPDATE文の単体テストが成功しない 原因@Modifyingの引数が不足していため。

Last updated at Posted at 2023-01-26

症状

RepositoryにおけるUPDATE処理の単体テストでエラーが出たので症状と対処法を投稿します。

プロダクトコード

CustomerRepository.java
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {

    @Modifying
    @Query("UPDATE Customer c SET  c.enabled= true  WHERE c.id = ?1")
    public void enabled(Integer id);
}

Customer.java
@Entity
@Table(name = "customers")
@Data
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;

    // Loginするときのパスワードして使う
    @Column(nullable = false, length = 64)
    private String password;

    // ログインするときのIDとして使用する
    @Column(nullable = false, unique = true, length = 45)
    private String email;

    // 認証コード
    @Column(name = "verification_code", length = 64)
    private String verificationCode;

    // 初期値はfalse 認証が成功すると trueになる。
    private boolean enabled;

    public Customer(Integer id, String password, String email, String verificationCode, boolean enabled) {
        this.id = id;
        this.password = password;
        this.email = email;
        this.verificationCode = verificationCode;
        this.enabled = enabled;
    }

    public Customer() {
    }
}


テストコード

CustomerRepositoryTest.java
@DataJpaTest
public class CustomerRepositoryTest {
    @Autowired
    CustomerRepository customerRepository;
    @Test
    @DisplayName("idを引数とし、enabledを実行したとき、enabledの値がfalseからtrueになる。")
    public void givenCustomerId_when_then() {
        // given-precondition or Setup
        Integer customerId = 1;
        customerRepository.save(new Customer(customerId,"password","testaaa@gmail.com","hogehogeaa",false));
        //when - action or the behavior that we are going test
        customerRepository.enabled(1);
        //then - verify the output
        Optional<Customer> enabledCustomer = customerRepository.findById(customerId);
        assertThat(enabledCustomer.get().isEnabled()).isTrue();

    }


}


テスト結果

NGになります。
UPDATE処理が実行されなく、enabled変数がfalseのままになっています。
本当はfalse→trueと変化させたい。
image.png

原因、解決

Repositoryレイヤーのメソッドのアノテーション@Modifyingに引数を加えてなかったから。

修正後

CustomerRepository

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {

+    @Modifying(clearAutomatically = true)
    @Query("UPDATE Customer c SET  c.enabled= true  WHERE c.id = ?1")
    public void enabled(Integer id);
}

テスト結果

成功しました。

image.png

開発環境

OS:windows10
IDE:IntelliJ Community
spring-boot-starter-parent 2.75
java : 11

参考

公式ドキュメント

image.png

stackoverflow

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0