java - 单元测试 mock 和 jUnit
问题描述
我尝试测试调用另一个方法的方法,但我有一个错误 java.util.NoSuchElementException,即使我填充了导致错误始终存在并且我不知道如何模拟这部分的对象,我需要帮助。
在这里,如果您能帮我解决问题,那就太好了
谢谢
@Override
public User getQueriedUserForCurrentUser(Principal principal, int id) {
// Get the current user
User currentUser = getUser(principal);
// Is the current user the queried user
boolean areUsersEquals = currentUser.getId() == id;
if(areUsersEquals) {
return currentUser;
}
// Throw an exception if the current user does not have the rights to
// access data from another user
if(!isUserAdmin(principal)) {
throw new UnauthorizedOperationException(UnauthorizedOperationException.USER_FETCH);
}
// Find the queried user or throw an exception otherwise
return findById(id).orElseThrow(NoSuchElementException::new);
}
/**
* {@inheritDoc}
*/
@Override
public User getUser(Principal principal) {
if (principal == null) {
return null;
}
String keycloakID = keycloakUserMapper.getIdKeycloak(principal);
if(isUserExists(keycloakID)){
return findByKeycloakID(keycloakID);
}
State activeState = stateRepository.findById(StateEnum.ACTIVE.value()).orElseThrow(NoSuchElementException::new);
User user = keycloakUserMapper.getUserFromPrincipal(principal);
user.setState(activeState);
return save(user);
//tests
@Test
public void getQueriedUserForCurrentUser_SameUserFetch_User(){
when(userService.getUser(principal)).thenReturn(user);
User queriedUser = userService.getQueriedUserForCurrentUser(principal, userID);
assertThat(queriedUser.getId()).isEqualTo(userID);
}
//error
13:37:06.052 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [836969741] from cache with key [[MergedContextConfiguration@34123d65 testClass = UserOperationsTest, locations = '{}', classes = '{class fr.alteca.altevent.services.impl.userservice.UserOperationsTest$UserOperationsTestContextConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@65466a6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@78e117e3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@16120cc7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@72f926e6], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
13:37:06.052 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@15fa55a6 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 10, missCount = 1]
13:37:06.053 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [836969741] from cache with key [[MergedContextConfiguration@34123d65 testClass = UserOperationsTest, locations = '{}', classes = '{class fr.alteca.altevent.services.impl.userservice.UserOperationsTest$UserOperationsTestContextConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@65466a6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@78e117e3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@16120cc7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@72f926e6], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
13:37:06.053 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@15fa55a6 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 11, missCount = 1]
13:37:06.054 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@4802796d testClass = UserOperationsTest, testInstance = fr.alteca.altevent.services.impl.userservice.UserOperationsTest@bdc8014, testMethod = getQueriedUserForCurrentUser_DifferentUserFetch_User@UserOperationsTest, testException = java.util.NoSuchElementException, mergedContextConfiguration = [MergedContextConfiguration@34123d65 testClass = UserOperationsTest, locations = '{}', classes = '{class fr.alteca.altevent.services.impl.userservice.UserOperationsTest$UserOperationsTestContextConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@65466a6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@78e117e3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@16120cc7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@72f926e6], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].
java.util.NoSuchElementException
at java.base/java.util.Optional.orElseThrow(Optional.java:401)
at fr.alteca.altevent.services.impl.UserServiceImpl.getUser(UserServiceImpl.java:89)
at fr.alteca.altevent.services.impl.userservice.UserOperationsTest.getQueriedUserForCurrentUser_DifferentUserFetch_User(UserOperationsTest.java:110)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
13:37:06.063 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [836969741] from cache with key [[MergedContextConfiguration@34123d65 testClass = UserOperationsTest, locations = '{}', classes = '{class fr.alteca.altevent.services.impl.userservice.UserOperationsTest$UserOperationsTestContextConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@65466a6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@78e117e3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@16120cc7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@72f926e6], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
13:37:06.064 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@15fa55a6 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 12, missCount = 1]
13:37:06.065 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@4802796d testClass = UserOperationsTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@34123d65 testClass = UserOperationsTest, locations = '{}', classes = '{class fr.alteca.altevent.services.impl.userservice.UserOperationsTest$UserOperationsTestContextConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@65466a6a, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@78e117e3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@16120cc7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@72f926e6], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
13:37:06.068 [SpringContextShutdownHook] DEBUG org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@31e3250d, started on Tue Jun 09 13:37:04 CEST 2020
Process finished with exit code -1
解决方案
使用doReturn()
和监视userService
@Test
public void getQueriedUserForCurrentUser_SameUserFetch_User(){
// Arrange
doReturn(Optional.of("test")).when(userService).findById(userID);
// Act
User queriedUser = userService.getQueriedUserForCurrentUser(principal, userID);
// Assert
assertThat(queriedUser.getId()).isEqualTo(userID);
}
推荐阅读
- php - prepare($sql) 函数不适用于一个脚本
- ruby-on-rails - 如何优雅地检查对象和关联对象的存在?
- c++ - C ++ for循环多个条件不一致
- android - Android Studio 在安装过程中卡住了
- javascript - 如何使用 html 输入字段从 php 代码显示 javascript 数组中的列表?
- r - 如何使用朴素贝叶斯预测每个类的概率?
- c - C中typeof中的括号是什么意思?
- php - PHP获取数组的子值
- c# - 从来自 c# 中的线程的列表框中读取所有数据的逻辑问题
- c#-4.0 - 如何修复请求被中止:无法在 microsoft exchange wed 服务中创建 SSL/TLS 安全通道