假设我有一个类;
public class FooBar {
public int getMethod(List<String> code){
if(code.size() > 100)
throw new Exception;
return 0;
}
}
我有一个这样的测试类;
@RunWith(PowerMockRunner.class)
@PrepareForTest(FooBar.class)
public class FooBarTest{
FooBar fooBarInstance;
@Before
public void setUp() {
//MockitoAnnotations.initMocks(this);
fooBarInstance = new FooBar();
}
@Test(expected = Exception.class)
public void testGetCorrelationListCodesParameter() {
List<String> codes = Mockito.spy(new ArrayList<String>());
Mockito.doReturn(150).when(codes).size();
fooBarInstance.getMethod(codes);
}
}
如何让这个测试方法抛出异常?我已经处理了几个小时才能做到这一点。好吧,还是谢谢你。
最佳答案
不需要 spy , mock 就足够了。正如@David 所说,也不需要也不建议对值对象进行模拟。
使用@Test(expected = Exception.class)
有很多缺点,当从意想不到的地方抛出异常时,测试可以通过。测试不工作,但显示为绿色。
我更喜欢使用 catch-exception 进行 BDD 风格测试.
Reasons for using catch-exceptions
(...) in comparison to the use of try/catch blocks.
- The test is more concise and easier to read.
- The test cannot be corrupted by a missing assertion. Assume you forgot to type fail() behind the method call that is expected to throw an exception.
(...) in comparison to test runner-specific mechanisms that catch and verify exceptions.
- A single test can verify more than one thrown exception.
- The test can verify the properties of the thrown exception after the exception is caught.
- The test can specify by which method call the exception must be thrown.
- The test does not depend on a specific test runner (JUnit4, TestNG).
import static com.googlecode.catchexception.CatchException.caughtException;
import static com.googlecode.catchexception.apis.CatchExceptionAssertJ.*;
public class FooBarTest {
FooBar sut = new FooBar(); // System Under Test
@Test
public void shouldThrowExceptionWhenListHasTooManyElements() {
when(sut).getMethod(listWithSize(150));
then(caughtException()).isInstanceOf(Exception.class);
}
private List<String> listWithSize(int size) {
return new ArrayList<String>(Arrays.asList(new String[size]));
}
}
此测试的完整工作代码:https://gist.github.com/mariuszs/8543918
不推荐的解决方案,带有预期的
和模拟。
@RunWith(MockitoJUnitRunner.class)
public class FooBarTest {
@Mock
List<String> codes;
FooBar fooBarInstance = new FooBar();
@Test(expected = Exception.class)
public void shouldThrowExceptionWhenListHasTooManyElements() throws Exception {
when(codes.size()).thenReturn(150);
fooBarInstance.getMethod(codes);
}
}
关于java - 在使用 Mockito 测试时监视方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21262768/