0
我有一些問題嘲笑方法(使用mockito),這取決於從輸入參數返回一個字符串或異常。嘲笑異常
單元測試的代碼似乎是錯誤的,但即使在詢問谷歌後我找不到解決方案。
感謝所有幫助
public class MyClassTest
{
public MyClass mc;
public ClassUnknown cu;
@Before
public void setUp()
{
mc = new MyClass();
cu = mock(ClassUnknown.class);
// The next two lines seems to be wrong
when(cu.methodUnknown("hello")).thenReturn("hello there");
when(cu.methodUnknown("???")).thenThrow(new Exception("don't know"));
}
@Test
public void testMain()
{
mc.mainMethod("hello");
.....;
}
}
這裏是 「classUnknown」:
public class ClassUnknown
{
public String methodUnknown(String s) throws Exception
{
// The real logic is much more complex and does some CRUD operations
if (s.equals("Hello"))
{
return "Hello there";
}
throw new Exception("don't know");
}
}
和類來進行測試:
public class MyClass
{
public void mainMethod(String s)
{
ClassUnknown cu = new ClassUnknown();
try
{
String methodUnknown = cu.methodUnknown(s);
System.out.println(methodUnknown);
} catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
謝謝。我添加了向SetUp()添加拋出異常,否則IDE將標記類錯誤,但不是它的工作。是否真的有必要添加到SetUp()? – ken 2014-09-23 07:13:24