无法使用 SpringBootTest 和 Spring JPA 存储库将数据保存在 H2 数据库中

Not able to save data in H2 Database using SpringBootTest and Spring JPA Repository

我正在使用@SpringBootTest 来测试 SpringSecurity 基础 authentication.When 我测试了它,h2 数据库不保存 data.I 在控制台中看不到插入语句,这显然是在什么时候看到的我是 运行 我的实际 SpringBoot 应用程序并从前端插入数据。请帮忙。

下面是我的测试:

        @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
        @ContextConfiguration(classes=ConnectionsAppApplication.class)
        @Transactional
        public class AuthenticationTest {

            @Autowired
            private WebApplicationContext context;

            private MockMvc mockMvc;

            @Mock
            CustDetailsRepository custRepository;

            @Mock
            BCryptPasswordEncoder encrypt;

            @InjectMocks
            CustomerServiceImpl customerServiceImpl;



           @BeforeEach
           public void setup() {

             MockitoAnnotations.initMocks(this);
             mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
           }


          @Test
          void testAuthentication() {

              CustomerDetails customer = new CustomerDetails();
              customer.setEmailid("abc.com");
              customer.setPassword("abc@123456");
              customerServiceImpl.saveUser(customer);
           try {
               this.mockMvc.perform(get("/api/login")
               .with(httpBasic("abc.com","abc@123456")))
               .andDo(print())
               .andExpect(status().isOk())
               .andReturn();
           } catch (Exception e) {
                e.printStackTrace();
            }
         }

       }

CustomerServiceImpl 中的 saveUser 方法class:

        public void saveUser(CustomerDetails customerDetails) {
          customerDetails.setPassword(bCryptPasswordEncoder.encode(customerDetails.getPassword()));
          custDetailsRepository.save(customerDetails);
         }

您有 2 个选项来实施此测试:

选项 1:使用真实的 h2

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes=ConnectionsAppApplication.class)
@Transactional
public class AuthenticationTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Autowired
    CustomerServiceImpl customerServiceImpl;

    @BeforeEach
    public void setup() {

        mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())
            .build();
    }


    @Test
    void testAuthentication() {

        CustomerDetails customer = new CustomerDetails();
        customer.setEmailid("abc.com");
        customer.setPassword("abc@123456");
        customerServiceImpl.saveUser(customer);
        try {
             this.mockMvc.perform(get("/api/login")
                 .with(httpBasic("abc.com","abc@123456")))
                 .andDo(print())
                 .andExpect(status().isOk())
                 .andReturn();
         } catch (Exception e) {
             e.printStackTrace();
         }
    }
}

选项 2:模拟您的服务/存储库

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes=ConnectionsAppApplication.class)
@Transactional
public class AuthenticationTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @MockBean
    CustomerServiceImpl customerServiceImpl;

    @BeforeEach
    public void setup() {
        mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())
            .build();
    }


    @Test
    void testAuthentication() {
        // set expectations on CustomerServiceImpl
        CustomerDetails customer = new CustomerDetails();
        customer.setEmailid("abc.com");
        customer.setPassword("abc@123456");
        // mock the method you use to fetch the customer
        when(customerServiceImpl.getUser("abc.com").thenReturn(customer);
        try {
            this.mockMvc.perform(get("/api/login")
                .with(httpBasic("abc.com","abc@123456")))
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn();
           } catch (Exception e) {
                e.printStackTrace();
           }
      }
}

请注意,您也可以使用@WebMvcTest 仅测试应用程序的 Web 切片(意味着不会实例化其他 bean,例如,您在控制器中依赖的所有服务都必须由 @MockBean 提供)