Exp*_*ger 3 junit android mocking mockito android-intent
我正在尝试对使用 JUnit4 和 Mockito 侦听“com.android.music.metachanged”意图的广播接收器进行单元测试。
广播接收器在接收到意图时启动服务。我想断言服务已启动。我还想断言接收到的意图的字符串额外的“艺术家”与发送的意图之一相同。
这是我到目前为止...
@RunWith(PowerMockRunner.class)
public class MusicBroadcastReceiverUnitTest {
private MusicBroadcastReceiver mReceiver;
@Mock
private Context mContext;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mReceiver = new MusicBroadcastReceiver();
}
@Test
public void testStartMusicRegistrationService() {
Intent intent = new Intent("com.android.music.metachanged");
intent.putExtra("artist", "SampleArtist");
mReceiver.onReceive(mContext, intent);
assertNull(mReceiver.getResultData());
ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
verify(mContext, times(1)).startService(argument.capture());
Intent receivedIntent = argument.getValue();
assertEquals("SampleArtist", receivedIntent.getStringExtra("artist"));
}
}
Run Code Online (Sandbox Code Playgroud)
但这会触发 java.lang.RuntimeException: Method putExtra in android.content.Intent not mocked。
我检查了这个,但我认为 OP 有一个不同的问题,因为他们没有从测试主体内部发出意图。
如果你像我一样在运行单元测试时看到这个错误,但你并不关心测试putExtra代码的一部分,你可以使用:
android {
// ...
testOptions {
unitTests.returnDefaultValues = true
}
}
Run Code Online (Sandbox Code Playgroud)
在您的应用程序build.gradle文件中。
好吧,我看了一下Method of ContentValues is not migrate by @Jeff Bowman。可悲的是,这个问题没有提供任何代码,所以我希望这对某人有用......
@RunWith(PowerMockRunner.class)
public class MusicBroadcastReceiverUnitTest {
private MusicBroadcastReceiver mReceiver;
@Mock
private Context mContext;
@Mock
private Intent androidIntent;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mReceiver = new MusicBroadcastReceiver();
}
@Test
public void testStartMusicRegistrationService() {
try {
PowerMockito.whenNew(Intent.class)
.withArguments(String.class).thenReturn(androidIntent);
} catch (Exception e) {
e.printStackTrace();
}
when(androidIntent.getAction())
.thenReturn("com.android.music.metachanged");
when(androidIntent.getStringExtra("artist"))
.thenReturn("SampleArtist");
mReceiver.onReceive(mContext, intent);
ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
verify(mContext, times(1)).startService(argument.capture());
Intent receivedIntent = argument.getValue();
assertEquals("SampleArtist", receivedIntent.getStringExtra("artist"));
}
}
Run Code Online (Sandbox Code Playgroud)
所以是的,我宁愿嘲笑“getStringExtra”而不是“putExtra”。但这对我有用。
| 归档时间: |
|
| 查看次数: |
6983 次 |
| 最近记录: |