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

无法针对REST层运行单元测试

陈晟睿
2023-03-14

我无法使用jhipster对web层进行单元测试(根据spring gs指南):

@RunWith(SpringRunner.class)
@WebMvcTest
public class FlightControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private FlightService flightService;

    @Test
    public void testCreate() throws Exception {

        FlightDto expected = new FlightDto();
        ReflectionTestUtils.setField(expected, "id", 1L);

        when(flightService.createFlight(any(FlightDto.class))).thenReturn(expected);

        FlightDto flightDto = new FlightDto();
        flightDto.setNumber("CAI-123400");

        this.mockMvc.perform(post("/api/flight")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(flightDto)))
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(header().string("Location", endsWith("/api/flight/1")));
    }

}

上面的单元测试在green-field spring boot项目的情况下成功,但在基于green-field spring boot的jhipster项目的情况下失败:

在FlightResource的jhispter项目(springboot-with-jhipster)中运行单元测试时,我得到了:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:202)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:137)
    at org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:35)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:409)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:323)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:277)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:112)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:82)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
    at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

共有1个答案

杜良骏
2023-03-14

我可以使用以下代码运行测试:

@RunWith(SpringRunner.class)

//@WebMvcTest remove @WebMvcTest
//add SpringBootTest
@SpringBootTest(classes = JhUnittestRestApp.class)
public class FlightResourceTest {

    //@Autowired remove anotation
    private MockMvc mockMvc;

    @MockBean
    private FlightService flightService;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Before
    public void setup() {
        //initialize the bean
        MockitoAnnotations.initMocks(this);
        final FlightResource flightResource = new FlightResource(flightService);
        this.mockMvc = MockMvcBuilders.standaloneSetup(flightResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setControllerAdvice(exceptionTranslator)
            .setConversionService(createFormattingConversionService())
            .setMessageConverters(jacksonMessageConverter).build();
    }

    @Test
    public void testCreate() throws Exception {

        FlightDTO expected = new FlightDTO();
        ReflectionTestUtils.setField(expected, "id", 1L);

        when(flightService.save(any(FlightDTO.class))).thenReturn(expected);

        FlightDTO flightDto = new FlightDTO();
        flightDto.setNumber("CAI-123400");
        //update the url to /api/flights so that the test can pass 
        this.mockMvc.perform(post("/api/flights")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(flightDto)))
            .andDo(print())
            .andExpect(status().isCreated())
            .andExpect(header().string("Location", endsWith("/api/flights/1")));
    }

}

您的FlightControllerTest正在springboot-no-jhipster项目中工作,因为根据@springboot的文档,该项目的主类用@springboot进行了注释

The @SpringBootApplication annotation is equivalent to using:
@Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes

由于JHipster需要更多的配置而不仅仅是默认配置,所以JHipster没有像您在项目中看到的那样使用@SpringBootApplication。这是完全可以和工作没有问题。

另一方面,测试的错误消息是它无法检测@SpringBootConfiguration。还有其他注释,例如@ContextConfiguration或@SpringBootTest,它们是rocomandet用于测试的注释。实际上,main config类中的注解与测试注解之间存在一些不一致之处(参见此处或此处)。

 类似资料:
  • 我试图从命令行运行一个Android测试用例。 在IDE中,我只需右键单击并运行即可,但在具有以下命令的CLI中,它将失败: 错误: 我试了一下您提到的: 和 还有:but it.不起作用。如果您告诉我根据我的构建变体具体键入什么。默认情况下,它在一个名为“app”的模块中。 下面是我要运行的测试:

  • 我试图在我的项目中使用JerseyTest框架添加ReST调用的单元测试。我复制粘贴了一个最简单的示例,但出现了一个运行时异常: 附加代码和pom依赖项:

  • 我是新来的单元测试,我试图运行一个简单的测试,但按下"运行测试"按钮后,它的负载,然后什么都没有 怎么了????!!

  • 我已经开始考虑在我的项目中围绕一些业务逻辑添加一些单元测试。 我想测试的第一个方法是服务层中的一个方法,它返回给定节点的子节点列表。 该方法如下所示: 我想象这样的测试方法是提供一个假树结构,然后测试提供节点是否返回正确的子节点。 ssdsContext是一个对象上下文。 我已经看到可以为提取和接口如何模拟ObjectContext或ObjectQuery 我还读到,as Entity Frame

  • 一、JUnit 是什么? JUnit 是一个 Java 语言的回归测试框架(regression testing framework),由 Kent Beck 和 Erich Gamma 建立。 Junit 测试也是程序员测试,即所谓的白盒测试,它需要程序员知道被测试的代码如何完成功能,以及完成什么样的功能。 二、IDEA 的 开始JUnit测试 测试项:查询全部用户数据 junit测试方法:

  • 几周前,我正在进行单元测试,它们按照预期进行构建和运行。 我休假了一周,今天早上启动了我的机器,没有对单元测试项目进行任何代码更改,测试就不再运行了。 当我说“测试不再运行”时,我并不是说它们失败了;他们实际上不会逃跑。 我试过运行或调试一个特定的测试,我试过运行或调试所有的测试,我试过从每个测试方法名称旁边的Resharper图标,我试过从test菜单项,我试过从“Unit test Sessi