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

时间:2020-04-09 12:09:24

标签: spring database spring-security mockito spring-boot-test

我正在使用@SpringBootTest来测试SpringSecurity基本身份验证。测试时,h2数据库无法保存数据。我在控制台中看不到insert语句,显然在运行实际的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方法:

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

1 个答案:

答案 0 :(得分:0)

您有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交付)