【问题标题】:Mocking service in Spring BootSpring Boot 中的模拟服务
【发布时间】:2018-05-10 09:37:20
【问题描述】:

运行测试时出现异常:

java.lang.NullPointerException 在 com.example.demo.service.database.impl.UserServiceImplTest.getById(UserServiceImplTest.java:69) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:498) 在 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 在 org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 在 org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 在 org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) 在 org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) 在 org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) 在 org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

这里是 UserServiceImpl:

@Service
public class UserServiceImpl implements UserService {

private final UserRepository userRepository;

@Autowired
public UserServiceImpl(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
public List<User> getAll() {
    return userRepository.findAll();
}

@Override
public User getById(long id) {
    return userRepository.findOne(id);
}

这是我的测试:

@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceImplTest {

@InjectMocks
UserServiceImpl userService;

@Mock
UserRepository userRepositoryMock;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

@Test
public void getById() {
    long id = 12;
    when(userRepositoryMock.findOne(id)).thenReturn(new User(id));
    Assert.assertEquals(id, userService.getById(id).getId());
  }
}

如何解决这个问题?

【问题讨论】:

    标签: spring unit-testing spring-boot junit mockito


    【解决方案1】:

    只需从测试类中删除 setup() 方法即可。

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }
    

    不使用时需要@RunWith(SpringJUnit4ClassRunner.class)

    注解或 setup() 方法只需要一个,而不是两者都需要。

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 2019-06-06
      • 2018-01-29
      • 1970-01-01
      • 2017-07-29
      • 2017-07-30
      • 2021-05-26
      • 2019-12-26
      相关资源
      最近更新 更多