正确测试Spring服务

Dar*_*olt 5 java junit spring hibernate spring-ws

以下测试失败,NullPointerException并在线上显示usersRepo.save(user);。我相信这是因为当测试进入performProvision()功能时,usersRepo对象就是null

但是,当Web服务实际上正在运行并且控制器的端点被命中时,一切正常,并且数据库已更新。

知道为什么测试失败了吗?我的想法是PAutoProvision引用真实的数据库,而它应该处理内存数据库,所以也许存在某种冲突?我还看到了很多不同的示例,它们的注释设置不同,所以我想这可能也是一个问题。

UsersRepo扩展了JpaRepository,其中PAutoProvision是一个SQL表实体。

如果没有足够的信息,我可以提供的UsersRepoPAutoProvision以及ProvisionController如果必要的类。

服务:

@Service
public class ProvisionService {

    @Autowired
    private UsersRepo usersRepo;


    public String performProvision(UserData userData) {
        try {
            PAutoProvision user = new PAutoProvision(userData);
            usersRepo.save(user);  // OOTB CRUD repository functionality of springData to update/insert record data
            return String.format("Success: User %s has been added to the database", userData.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
            System.out.println("\n\n Cannot perform the provisioning of the user " + userData.getUserId() + ": \n" + e.toString() + "\n\n");
        }

        return "problem";
    }
}
Run Code Online (Sandbox Code Playgroud)

考试:

@RunWith(SpringRunner.class)
public class ProvisionServiceTest {

    private ProvisionService provisionService;

    @MockBean
    private UsersRepo usersRepo;

    @Before
    public void setUp(){
        provisionService = new ProvisionService();
    }

     @Test
    public void performProvision_shouldPass() {
        UserData userData = new UserData("userid", 30, 1, "spot", 1);
        try {
            String result = provisionService.performProvision(userData);
            assertThat(result, is(equalTo("Success: User userid has been added to the database")));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑1:

添加@Autowired和删除setUp()方法将导致以下结果:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.autoprovision.ProvisionServiceTest': Unsatisfied dependency expressed through field 'provisionService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.autoprovision.ProvisionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

小智 5

正如 JB Nizet 已经指出的那样,UserRepo模拟不会注入到 ProvisionService 实例中,因为 ProvisionService 实例是在 setUp 方法中使用new.

你的测试应该是这样的:

@RunWith(SpringRunner.class)
public class ProvisionServiceTest {
    @Autowired // let Spring instantiate the instance to test
    private ProvisionService provisionService;

    @MockBean
    private UsersRepo usersRepo;

    @Test
    public void performProvision_shouldPass() {
        UserData userData = new UserData("userid", 30, 1, "spot", 1);

        String result = provisionService.performProvision(userData);
        assertThat(result, is(equalTo("Success: User userid has been added to the database")));
    }
}
Run Code Online (Sandbox Code Playgroud)