Java-正确测试Spring服务
作者:互联网
这个问题已经在这里有了答案: > How to access Spring @Service object from jUnit test 2个
以下测试失败,并在usersRepo.save(user);行上显示NullPointerException.我相信这是因为当测试进入performProvision()函数时,usersRepo对象为null.
但是,当Web服务实际运行且控制器的端点被命中时,一切正常,并且数据库已更新.
知道为什么测试失败了吗?我的想法是PAutoProvision引用真实的数据库,而它应该处理内存数据库,所以也许存在某种冲突?我还看到了很多不同的示例,它们的注释设置不同,所以我想这可能也是一个问题.
UsersRepo扩展了JpaRepository,其中PAutoProvision是一个SQL表实体.
如果这还不够,我可以根据需要提供UsersRepo,PAutoProvision和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";
}
}
考试:
@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());
}
}
}
编辑1:
添加@Autowired并删除setUp()方法将导致以下结果:
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为’com.autoprovision.ProvisionServiceTest’的bean时出错:通过字段’provisionService’表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为’com.autoprovision.ProvisionService’的合格Bean:至少应有1个可以作为自动装配候选的Bean.依赖项注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}
解决方法:
如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")));
}
}
标签:spring-ws,junit,hibernate,spring,java 来源: https://codeday.me/bug/20191025/1932103.html