当前位置: 首页 > 知识库问答 >
问题:

Controller-Test中抛出异常“必须至少存在一个JPA元模型”

闾丘德宇
2023-03-14

application.java

package com.particles.authservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@Import({ ApplicationConfiguration.class })
public class Application {
    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

applicationconfiguration.java

package com.particles.authservice;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EntityScan(basePackageClasses = { Application.class, Jsr310JpaConverters.class })
@EnableJpaRepositories
public class ApplicationConfiguration {
}

AccountController.java

package com.particles.authservice.accountservice;

import ...

@RestController
public class AccountController {
    @Autowired
    private AccountService accountService;

    /**
     * This method attempts to login a user and issue a token if the login was successful.
     * <p>
     * If login fails due a login attempt with a non-existent username or an invalid password, an exception is thrown.
     * 
     * @param credentials
     *            ({@link Credentials}) credentials in a JSON-form, that can be unserialized into an object of this type
     * @param response
     *            ({@link HttpServletResponse}) response, which will be sent to the client;
     *            if the credentials were valid the response receives a JWT as an additional header
     * @return ({@link PersistableAccount}) JSON (automatically serialized from the given TO);
     *         if the request was successful, an additional header containing the freshly issued JWT is added into the response
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public PersistableAccount login(@RequestBody final Credentials credentials, final HttpServletResponse response)
            throws IOException, URISyntaxException {
        final Optional<PersistableAccount> account = accountService.login(credentials);
        if (!account.isPresent()) {
            throw new AccountLoginFailedException(credentials);
        }
        response.setHeader("Token", jwtService.tokenForPersistableAccount(account.get()));
        return account.get();
    }
}
package com.particles.authservice;

import static ...
import ...

@RunWith(SpringRunner.class)
@WebAppConfiguration
@WebMvcTest(AccountController.class)
public class AccountControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AccountService accountServiceMock;

    @Test
    public void test() throws Exception {
        final Credentials credentials = TestHelper.createCredentials();
        final Optional<PersistableAccount> account = Optional.of(TestHelper.createPersistableAccount());

        given(accountServiceMock.login(credentials))
                                                    .willReturn(account);

        mockMvc
               .perform(MockMvcRequestBuilders.post("/login").accept(MediaType.APPLICATION_JSON))
               .andExpect(status().isOk());
    }
}
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at org.springframework.util.Assert.notEmpty(Assert.java:277)
    at org.springframework.data.jpa.mapping.JpaMetamodelMappingContext.<init>(JpaMetamodelMappingContext.java:52)
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:71)
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:26)
    at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 40 more
    null

删除@enableJParepositories注释解决了这个问题,但不幸的是,它似乎破坏了我的应用程序。

我做错了什么?

共有1个答案

娄学文
2023-03-14

添加ContextConfiguration。测试没有看到ApplicationConfiguration,因此没有看到任何实体。

@ContextConfiguration(classes = {ApplicationConfiguration.class})
public class AccountControllerTest { ... }

更新:

代码缺少的另一件事是@SpringBootTest。试着用这个注释测试类。

 类似资料: