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

如何使用 Spring Boot 1.4.0 对 JUNIT 测试用例使用随机端口

农飞尘
2023-03-14

我使用的是spring boot 1.3.6,我的JUNIT测试用例运行良好,在升级到spring boot 1.4.0并尝试删除不推荐的类后,我遇到了错误

我与1.3. x的JUNCLASS

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
public class CustomerControllerIT {

    @Value("${local.server.port}")
    private int port;
    private URL base;
    private RestTemplate template;

    @Autowired
    private DataBuilder dataBuilder;

    @Autowired
    private CustomerRepository customerRepository;

    private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8"; 


    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/rest/customers");
        template = new TestRestTemplate();      

        /* remove and reload test data */
        customerRepository.deleteAll();     
        dataBuilder.createCustomers().forEach(customer -> customerRepository.save(customer));       
    }

    @Test
    public void getAllCustomers() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);     
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

        List<Customer> customers = convertJsonToCustomers(response.getBody());      
        assertThat(customers.size(), equalTo(3));       
    }

private List<Customer> convertJsonToCustomers(String json) throws Exception        {        
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, Customer.class));
}
}

我的类与1.4.0

已完成更新

    < li >用spring建议的模板删除了已弃用的TestRestTemplate < li >使用SpringRunner而不是SpringJUnit4ClassRunner运行 < li >将@ SpringApplicationConfiguration(classes = application . class)替换为@ spring boot test(classes = application . class,webEnvironment=WebEnvironment。随机端口)

更改后

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class , webEnvironment=WebEnvironment.RANDOM_PORT)
@WebAppConfiguration
public class CustomerControllerIT {

    @Value("${local.server.port}")
    private int port;
    private URL base;
    private TestRestTemplate template;

    @Autowired
    private DataBuilder dataBuilder;

    @Autowired
    private CustomerRepository customerRepository;

    private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8"; 


    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/rest/customers");
        template = new TestRestTemplate();      

        /* remove and reload test data */
        customerRepository.deleteAll();     
        dataBuilder.createCustomers().forEach(customer -> customerRepository.save(customer));       
    }
}

现在当我尝试运行JUNIT测试用例时,我收到了NPE,如何设置随机端口以使我的JUNIT测试用例在Spring Boot 1.4.0中运行?

更新:

这是问题的症结所在

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    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:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NullPointerException
    at org.springframework.test.context.web.socket.MockServerContainerContextCustomizer.customizeContext(MockServerContainerContextCustomizer.java:38)
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextCustomizerAdapter.initialize(SpringBootContextLoader.java:270)
    at org.springframework.boot.SpringApplication.applyInitializers(SpringApplication.java:633)
    at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:347)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 more

共有1个答案

巫马松
2023-03-14

从Spring Blog我更新了您的最新样品。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment=WebEnvironment.RANDOM_PORT)
public class CustomerControllerIT {
    @Autowired
    private TestRestTemplate template;

    @Autowired
    private DataBuilder dataBuilder;

    @Autowired
    private CustomerRepository customerRepository;

    private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8"; 


    @Before
    public void setUp() throws Exception {
        /* remove and reload test data */
        customerRepository.deleteAll();     
        dataBuilder.createCustomers().forEach(customer -> customerRepository.save(customer));       
    }

    @Test
    public void getAllCustomers() throws Exception {
        ResponseEntity<String> response = template.getForEntity("/rest/customers", String.class);     
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

        List<Customer> customers = convertJsonToCustomers(response.getBody());      
        assertThat(customers.size(), equalTo(3));       
    }
}
 类似资料:
  • 我对junit mockito非常陌生,并尝试使用mockito编写junit测试用例。 这是我的方法,我必须为此编写一个jUnit。 ChefService和ChefApi传递的方法参数来自第三方api 这里是呼叫chefService。listCookbookVersions()将返回CookBookVersion类类型的迭代器,如

  • 我能够测试代码,但代码覆盖率不包括第二个开关情况。 请参考以下代码。 下面是我的测试代码。 由于我已经声明了一个带有测试值的字符串变量,所以我无法涵盖第二个switch语句。我尝试过if else的情况,但同样的问题发生了。我们还有别的办法吗?

  • 我想为RESTful API Web服务编写junit测试用例,以检查DB的响应和预期响应。这里的基本流程是REST文件(调用)- 这是我的REST文件: } 这是业务逻辑文件: } 这里的问题是如何在测试用例中提供从DB for n3获取的值,因为实际代码位于不同的数据库中,我不想清理这些数据库。因此,基本上,测试用例将在不同的空数据库上运行,在运行数据库时,我必须在测试用例执行后插入数据并清理

  • 确实给了我们单独的JVM,但是JUnit(当然)不知道单独的测试,所以报告是非常无用的。 (c)每个JUnit类一个测试: } 我们显然在这里遗漏了一些东西,因为我们的测试情况并不罕见!任何建议都非常感谢。

  • 问题内容: 目前,我有以下 build.gradle 文件: 这 的build.gradle 文件是我的仓库 在这里 。我所有的主文件都在 src / model /中 ,它们各自的测试在 test / model中 。 如何正确添加JUnit 4 依赖项 ,然后在 测试/模型 文件夹中运行那些测试? 问题答案: 如何正确添加junit 4依赖关系? 假设您要针对标准Maven(或等效版本)存储库

  • 我想为我的一个编写一个简单的测试,并断言输入已正确映射到: 问题:如何向该servlet发送请求正文。然后再检查一下字段是否都设置正确? 这可能与此类似,但我不知道如何检查/监视已解析的DTO? @重复标记:这不是链接问题(关于如何读取响应正文字符串)的重复。我实际上是在要求进行身体测试。