繁体   English   中英

单元测试模拟和 jUnit

[英]Unit tests mock and jUnit

我尝试测试调用另一个方法的方法,我有一个错误 java.util.NoSuchElementException 即使我填写了 object 这导致错误始终存在并且我不知道如何模拟这部分,我需要帮助。

在这里,如果您能帮我解决问题,那就太好了

谢谢

 @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()和 spy 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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM