0

I have a question

Sample 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);

    }

}

Controller

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

    @Autowired
    private Environment env;

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

Test 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();
    } 
}

If you look closely in main function cmartBuyController.helloTest() should print "Hello World" but i am getting null , Also the main Application is printing log twice in command line runner. Can any one please help how to execute these methods please.

Pavel Gordon
  • 192
  • 2
  • 11

1 Answers1

0

Test it like this, it is working for me ;

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

    @Autowired
    ApplicationContext ctx;

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

}
drowny
  • 2,067
  • 11
  • 19