【问题标题】:Spring Boot ComandLinerRunner TestSpring Boot CommandLinerRunner 测试
【发布时间】:2019-03-13 21:32:19
【问题描述】:

我有一个问题

示例类

@SpringBootApplication(scanBasePackages = { "com.Sample.smartbuy" })
public class SmartBuyArtApi2ClientApplication implements CommandLineRunner {
    public static final Logger logger = Logger.getLogger(SmartBuyArtApi2ClientApplication.class);

    public static void main(String[] args) {
        logger.info("Entered the main app");
        SpringApplication.run(SmartBuyArtApi2ClientApplication.class, args);
    }

    @Autowired
    public SmartBuyController cmartBuyController;

    @Override
    public void run(String... args) throws SQLException {

        logger.info(" ********  Applications has started ******* ");

        logger.info(" cmartBuyController :: " + cmartBuyController.helloTest());

        logger.info(
                " *****************  cmartBuyController is not null ************* Arguments length :: " + args.length);

    }

}

控制器

@Configuration
@PropertySource(ignoreResourceNotFound = true, value = "classpath:smartbuy.properties")
public class SmartBuyController {

    @Autowired
    private Environment env;

    public String helloTest() {
        return "Hello World";
    }
}

测试类

@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
@DataJpaTest
@SpringBootTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class SmartBuyControllerTest {

    @MockBean
    private SmartBuyController cmartBuyControllerTest;

    @Autowired
    ApplicationContext ctx;

    @Test
    public void postEntityTest() throws Exception {
        CommandLineRunner runner = ctx.getBean(SmartBuyArtApi2ClientApplication.class);
        runner.run();
    } 
}

如果您仔细查看主函数 cmartBuyController.helloTest() 应该会打印“Hello World” 但我得到了 null ,主应用程序也在命令行运行器中打印了两次日志。 任何人都可以请帮助如何执行这些方法。

【问题讨论】:

  • 你的Test类有注解吗?
  • 是的,请,我的测试类被注释为以下 RunWith(SpringRunner.class) ActiveProfiles("dev") DataJpaTest SpringBootTest
  • 我什至创建了一个示例方法,它在组件( SampleTestComponents )中返回字符串“Hello World”,即使它返回 null 。请帮助解释 commandLinRunner 测试的任何项目,因为我只能在春季看到 Web 测试
  • 使用注释添加您的类和测试类代码
  • @drowny 我已经用以下 RunWith(SpringRunner.class) ActiveProfiles("dev") DataJpaTest SpringBootTest 进行了注释。您能否指导一下缺少哪些注释

标签: java spring spring-boot junit spring-boot-test


【解决方案1】:

像这样测试它,它对我有用;

@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
@SpringBootTest
class TestClass{

    @Autowired
    ApplicationContext ctx;

    @Test
    public void testRunMethod() {
        CommandLineRunner runner = ctx.getBean(CommandLineRunner.class);
        runner.run();
    }

}

【讨论】:

  • 感谢您的帮助..现在我可以开始测试课程并在其他地方遇到打嗝..请您帮忙,因为我已经更新了我的代码。
  • 它是否记录任何字符串?或者您的问题是打印 null 而不是 Hello world?
  • 嗨@drowny 它没有记录任何东西,所以主类中的记录器正在打印 null
  • 简而言之,使用模拟 bean 方法注释的类没有被执行
猜你喜欢
  • 2016-10-29
  • 2018-06-10
  • 2020-07-21
  • 2021-10-19
  • 2023-03-25
  • 2019-10-26
  • 2021-03-15
  • 2016-05-28
  • 2021-05-23
相关资源
最近更新 更多