springboot之使用junit測試
阿新 • • 發佈:2018-11-27
專案結構
application.properties
user.username=tom
user.password=123
User.java
package com.fengqing.qqspringboot.bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "user") public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
ApplicationContextUtil.java
package com.fengqing.qqspringboot.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (ApplicationContextUtil.applicationContext == null) { ApplicationContextUtil.applicationContext = applicationContext; } } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } }
QqspringbootApplicationTests.java
package com.fengqing.qqspringboot; import com.fengqing.qqspringboot.bean.User; import com.fengqing.qqspringboot.util.ApplicationContextUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class QqspringbootApplicationTests { @Test public void contextLoads() { User user = (User)ApplicationContextUtil.getBean("user"); System.out.println(user.getUsername()); } }