2015-12-30 97 views
2

我是Junit的新手。最近,我需要爲Spring Web項目添加一些測試功能。 因此,我只爲測試添加一個新項目。JUnit在春季web項目

首先,我添加了一個用於測試ADServiceImpl的測試用例,下面是我的測試代碼。

@Test 
public void test() { 
    ADServiceImpl service = new ADServiceImpl(); 
    UserInfo info = service.getUserInfo("admin", "123456"); 
    assertEquals("Result", "00", info.getStatus().getCode()); 
} 

當我運行測試並得到一個錯誤是'端點'爲空。但'endpoint'由xml配置中的spring @Resource(name =「adEndpoint」)設置。
我該如何處理這個問題?或者還有其他建議春季Web項目測試?非常感謝!

@Service("ADService") 
public class ADServiceImpl implements ADService { 

private final static Logger logger = Logger.getLogger(ADServiceImpl.class); 

@Resource(name = "adEndpoint") 
private String endpoint; 

public UserInfo getUserInfo(String acc, String pwd) throws JAXBException, RemoteException { 

    if (StringUtils.isBlank(endpoint)) { 
     logger.error("***** AD Endpoint is blank, please check sysenv.ad.endpoint param ******"); 
    } 

    ADSoapProxy proxy = new ADSoapProxy(); 
    proxy.setEndpoint(endpoint); 
    logger.debug("***** AD endpoint:" + endpoint + "******"); 

    String xml = proxy.userInfo(acc, pwd); 
    StringReader reader = new StringReader(xml); 

    JAXBContext jaxbContext = JAXBContext.newInstance(UserInfo.class); 
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 

    return (UserInfo) jaxbUnmarshaller.unmarshal(reader); 
} 
} 
+0

你能包括類的聲明,你的JUnit測試是?我猜測你沒有指定一個測試運行器(通常是'@RunWith(SpringJUnit4ClassRunner.class)''這是告訴Spring從你的配置中注入依賴關係的東西。參見[Spring文檔](http:// docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-framework)獲取更多信息。 – DaveyDaveDave

+1

@DaveyDaveDave是的,這是一個觀點,我沒有@RunWith (SpringJUnit4ClassRunner.class)注入bean。非常感謝! – Louis

回答

0

當創建需要春天是運行單元測試,你需要以下添加到您的單元測試類。例如:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = MySpringApp.class) 
public MyTestClass{ 
    @Test 
    ... 
} 

更多信息here

+0

非常感謝。現在,它工作正常。 – Louis