我正在使用PowerMock编写单元测试,模拟一些util类的行为.为测试类定义一次行为(通过@BeforeClass注释)会导致:
示例代码:
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest( {A.class, B.class})
public class TestMockedMethods {
private static B b;
@BeforeClass
public static void setUp() {
PowerMockito.mockStatic(A.class);
PowerMockito.when(A.getVal()).thenReturn("X");
b = PowerMockito.mock(B.class);
PowerMockito.when(b.getVal()).thenReturn("Y");
}
@Test
public void test1() { // PASS
Assert.assertEquals("X", A.getVal());
Assert.assertEquals("Y", b.getVal());
}
@Test
public void test2() { // FAIL
Assert.assertEquals("X", A.getVal()); // actual="A"
Assert.assertEquals("Y", b.getVal()); // actual="B"
}
}
class A {
static String getVal() {
return …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Espresso-2.2测试我的应用行为
在主要活动上,当按下按钮时,服务和另一个活动正在启动:
public class MainActivity extends Activity {
public void onButtonClicked() {
startActivity(SecondActivity.getStartIntent());
startService(MyIntentService.getStartIntent());
}
}
Run Code Online (Sandbox Code Playgroud)
我正在测试是否正在启动预期的组件:
public class MainActivityTest {
@Rule
public final IntentsTestRule<MainActivity> intentsRule = new IntentsTestRule<>(MainActivity.class, true);
@Test
public void shouldStartServiceOnButtonClicked() {
onView(withId(R.id.button)).perform(click());
intended(hasComponent(hasClassName(SecondActivity.class.getName())));
intended(hasComponent(hasClassName(MyIntentService.class.getName())));
}
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了错误:
Caused by: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 0 intents.
IntentMatcher: has component: has component with: class name: is "com.example.MyIntentService" package name: an instance of java.lang.String short class name: an instance of java.lang.String
Matched intents:[]
Recorded intents: …Run Code Online (Sandbox Code Playgroud) 我想测试B类:
class B : A {
override fun init() {
// do work here
}
}
class A {
protected fun init() { } // will be called by internal logic
}
Run Code Online (Sandbox Code Playgroud)
并且在Java中调用没有问题:b.init()在测试方法中(测试类与测试对象在同一个包中),但在Kotlin编译器中抱怨:
无法访问'init':它在'B'中受到保护
@Test
fun `checks init`() {
val b = B()
b.init()
// assert work done
}
Run Code Online (Sandbox Code Playgroud)
为什么不工作?如何解决此问题(我想避免将方法公开)?
执行声明
true || true ? false : true
Run Code Online (Sandbox Code Playgroud)
回报false.
不应该是真的,因为OR条件不会执行三元运算(右侧部分)?