【发布时间】:2014-03-22 06:02:21
【问题描述】:
以下是我在单元测试时所面临的模拟情况。
Sample Class
class FooService extends Service
{
public static FooService sFooService;
private Bar mBar = new Bar();
//Other private objects
@Override
protected void onCreate()
{
sFooService = this;
}
public static FooService getInstance()
{
return sFooService;
}
@Override
protected void onDestroy()
{
sFooService = null;
}
public void doSomething()
{
//do Some stuff here
if(done)
{
mBar.perfomAction(true);
// Now this performAction method doing many stuffs using some other classes
// that may have dependency and initialized from some else. Hence throwing exceptions.
// Therefore need to mock Bar class. but how ??
}
else
{
mBar.perfomAction(false);
}
}
}
Sample Test Class
class FooTest extends ServiceTestCase<FooService>
{
protected void setUp() throws Exception
{
super.setUp();
MockitoAnnotations.initMocks(this);
startService(new Intent(getContext(), FooService.class));
}
protected void tearDown() throws Exception
{
super.tearDown();
}
public void testdoSomething()
{
Bar bar = mock(bar.class);
doThrow(new RuntimeException re).when(bar).performAction(true);
//How to inject bar mocked object?
assertNotNull(FooService.getInstance());
try
{
FooService.getInstance().doSomeThing();
Assert.Fail("Runtime exception should be thrown");
}
catch (RuntimeException re)
{
}
}
}
现在,我如何注入使用 Mockito 创建的 bar 模拟对象?
我用谷歌搜索了这个,发现有些人建议为 Bar 类创建 getter 和 setter。我认为这不是一个有效的解决方案,因为可能有许多私有对象,这些对象在 FooService 类之外是可见的。
问候, 尤维
【问题讨论】:
标签: android unit-testing junit mocking mockito