我在尝试使用此模拟时收到错误Checked exception is invalid for this method
:
InitialContext mockContext;
mockContext = mock(InitialContext.class);
when((DataSource) mockContext.lookup("java:comp/env/jdbc/foo")).thenThrow(new ConnectionFactoryException("test")); // <-- Fails on this line
@Test
public void shouldThrowExceptionIfDataSourceDoesNotExist() throws ConnectionFactoryException {
assertThatExceptionOfType(ConnectionFactoryException.class)
.isThrownBy(() -> { new DataSourceFactory(mockContext).getDataSource("foo"); })
.withMessage("Unable to find jdbc/foo");
}
I级尝试测试:
public class DataSourceFactory {
// Dependencies to be injected
private InitialContext context;
public DataSourceFactory(InitialContext context) throws ConnectionFactoryException {
if(context == null) {
throw new ConnectionFactoryException("context can't be null");
}
this.context = context;
}
public DataSource getDataSource(String dataSourceName) throws ConnectionFactoryException {
if(dataSourceName == null) {
throw new ConnectionFactoryException("dataSourceName can't be null");
}
// Ensure we have the correct syntax for the datasource name
if(!dataSourceName.startsWith("jdbc/")) {
dataSourceName = "jdbc/" + dataSourceName;
}
try {
System.out.println("java:comp/env/" + dataSourceName);
DataSource dataSource = (DataSource) context.lookup("java:comp/env/" + dataSourceName);
return dataSource;
} catch (NamingException e) {
throw new ConnectionFactoryException("Unable to find " + dataSourceName, e);
}
}
}
我知道我已经读过我不应该模仿我不拥有的对象,但我无法弄清楚如何在不模仿的情况下测试getDataSource()
方法{ {1}}。
答案 0 :(得分:5)
lookup
确实不会抛出ConnectionFactoryException
- 您的代码会这样做。相反,你应该抛出正确的异常 - NamingException
,并测试你的代码按预期处理它(即抛出ConnectionFactoryException`):
when(mockContext.lookup("java:comp/env/jdbc/foo"))
.thenThrow(new NamingExcetpion("test"));