Spring Boot ComandLinerRunner 测试

Spring Boot ComandLinerRunner Test

我有一个问题

样本Class

@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";
    }
}

测试Class

@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 ,而且主要应用程序在命令行运行器中打印日志两次。 任何人都可以请帮助如何执行这些方法。

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

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

    @Autowired
    ApplicationContext ctx;

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

}