我想为大量代码编写测试用例,我想知道JUnit @Rule注释功能的细节,以便我可以用它来编写测试用例.请提供一些好的答案或链接,通过一个简单的例子详细说明其功能.
在编写新的jUnit4测试时,我想知道是否使用@RunWith(MockitoJUnitRunner.class) 或MockitoAnnotations.initMocks(this).
我创建了一个新测试,向导自动使用Runner生成测试.MockitoJUnitRunner的Javadocs说明如下:
与JUnit 4.4及更高版本兼容,此运行器添加了以下行为:
初始化用Mock注释的模拟,因此不需要明确使用MockitoAnnotations.initMocks(Object).在每种测试方法之前初始化模拟.验证每个测试方法后的框架使用情况.
我不清楚使用Runner是否比我过去使用的initMocks()方法有任何优势.
任何想法或链接将不胜感激!
如何使用Mockito和JUnit 5注射?
在JUnit4中,我可以使用@RunWith(MockitoJUnitRunner.class)Annotation.在JUnit5中没有@RunWith注释?
在我的测试中我需要Robolectric和Mockito,每个人都提出自己的TestRunner,我该怎么办?
我有这个代码:
@RunWith(MockitoJUnitRunner.class)
@EBean
public class LoginPresenterTest {
@Bean
LoginPresenter loginPresenter;
@Mock
private LoginView loginView;
@AfterInject
void initLoginPresenter() {
loginPresenter.setLoginView(loginView);
}
@Test
public void whenUserNameIsEmptyShowErrorOnLoginClicked() throws Exception {
when(loginView.getUserName()).thenReturn("");
when(loginView.getPassword()).thenReturn("asdasd");
loginPresenter.onLoginClicked();
verify(loginView).setEmailFieldErrorMessage();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是AndroidAnnotations没有注入依赖项,我在尝试使用时获得了NPELoginPresenter
有人告诉我使用LoginPresenter_构造函数,以便我可以通过这种方式强制注入依赖项:
LoginPresenter loginPresenter = LoginPresenter_.getInstance_(context);
Run Code Online (Sandbox Code Playgroud)
为了获得对上下文的访问,我不得不从单元测试切换到Android Instrumentation测试,getInstrumentation().getTargetContext()
但我想要单元测试,而不是仪器测试.
所以另一个人告诉我使用Robolectric它 - 它应该能够为我提供应用程序上下文.
但是,当我查看入门页面时Robolectric,它说
@RunWith(RobolectricGradleTestRunner.class)
Run Code Online (Sandbox Code Playgroud)
这将与我目前@RunWith对Mockito的注释冲突,所以我该怎么办?
android studio 2.1. preview 4
Run Code Online (Sandbox Code Playgroud)
我正在创建一个junit4 unit test测试来打开原始目录中包含的文件.
但是,每次代码运行时我都可以使用空指针openRawResource.
这是我试图测试的功能.这在实际设备上运行时有效.但不是在单元测试中.
public String getNewsFeed(Context mContext) {
InputStream inputStream = mContext.getResources().openRawResource(R.raw.news_list); // Null pointer
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferReader = new BufferedReader(inputReader);
int n;
while ((n = bufferReader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
inputStream.close();
}
catch (IOException ioException) {
return "";
}
return writer.toString();
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试用例
@RunWith(MockitoJUnitRunner.class)
public class NewsListPresenterTest { …Run Code Online (Sandbox Code Playgroud) 我正在使用 Junit 4.8.2。当我@RunWith(MockitoJUnitRunner.class)使用 @Mock运行我的测试类并仅使用 @Mock 注释模拟时,它似乎没有初始化模拟。但是当我使用静态 mock() 并去掉 runner 和 annotations 时,我可以看到 mocks 已初始化。
@RunWith(MockitoJUnitRunner.class)
public class MyTestClass
{
private static final String DOMAIN = "mock";
@Mock private TransactionManager transactionManager;
@Mock private SearchManager searchManager;
private final filter = new Filter(transactionManager,searchManager, DOMAIN);
@Test
public void myTest()
{
filter.callMethod(); // This throws NPE since transactionManager was null
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?我已经研究了这个Initialising mock objects - MockIto并根据它做了一切,但仍然没有运气。
鉴于以下@Component课程:
@Component
public class MovieFinderImpl implements MovieFinder {
@Autowired
private Movie movie;
@Override
public List<Movie> findAll() {
List<Movie> movies = new ArrayList<>();
movies.add(movie);
return movies;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试学习如何在不进行集成测试的情况下对此示例组件进行单元测试(因此测试类上没有@RunWith(SpringRunner.class)和@SpringBootTest注释).
当我的测试类看起来像这样:
public class MovieFinderImplTest {
@InjectMocks
private MovieFinderImpl movieFinderImpl;
@Mock
public Movie movieMock;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
movieMock.setTitle("test");
movieMock.setDirector("directorTest");
}
@Test
public void testFindAll() {
List<Movie> movies = movieFinderImpl.findAll();
Assert.assertNotNull(movies.get(0));
String expectedTitle = "test";
String actualTitle = movies.get(0).getTitle();
Assert.assertTrue(String.format("The expected name is %s, but …Run Code Online (Sandbox Code Playgroud) 前言:
这个问题和答案旨在作为对由于误用 Mockito 或误解 Mockito 如何工作以及与用 Java 语言编写的单元测试交互而产生的大多数问题的规范答案。
我已经实现了一个应该进行单元测试的类。请注意,此处显示的代码只是一个虚拟实现,Random仅供说明之用。真实的代码将使用真实的依赖项,例如另一个服务或存储库。
public class MyClass {
public String doWork() {
final Random random = new Random(); // the `Random` class will be mocked in the test
return Integer.toString(random.nextInt());
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用 Mockito 来模拟其他类,并编写了一个非常简单的 JUnit 测试。但是,我的类在测试中没有使用模拟:
public class MyTest {
@Test
public void test() {
Mockito.mock(Random.class);
final MyClass obj = new MyClass();
Assertions.assertEquals("0", obj.doWork()); // JUnit 5
// Assert.assertEquals("0", obj.doWork()); // JUnit 4
// this fails, because the `Random` mock is not …Run Code Online (Sandbox Code Playgroud) @Before 需要JUnit测试中的符号,因为几个测试需要在运行之前创建类似的对象.
但是我没有区分在将testcase函数作为全局对象之前实例化一个对象和放入一个对象之间@Before.
例如,我正在测试我的国际象棋程序,我正在测试我的Piece对象是否移动到正确的位置:
public class PawnTest { //The Test Class itself
Board board = new Board();
@Test
/**
* Testing the right movement
*/
public void correctMovementTest() {
Pawn p1 = new Pawn(Player.UP);
board.placePiece(4, 3, p1);
board.movePieceTo(5, 3, p1);
assertEquals(board.getPiece(5, 3), p1);
}
@Test
/**
* Testing the right movement
*/
public void correctMovementTest2() {
Pawn p1 = new Pawn(Player.UP);
board.placePiece(4, 3, p1);
board.movePieceTo(6, 3, p1);
assertEquals(board.getPiece(6, 3), p1);
}
....
Run Code Online (Sandbox Code Playgroud)
如果我在测试用例方法之外进行decalre Board,那么它不会起作用Pawn p1吗?我们为什么需要 …
考虑以下代码:
@Singleton
public class MyServiceImpl {
public int doSomething() {
return 5;
}
}
@ImplementedBy(MyServiceImpl.class)
public interface MyService {
public int doSomething();
}
public class MyCommand {
@Inject private MyService service;
public boolean executeSomething() {
return service.doSomething() > 0;
}
}
public class MyCommandTest {
@InjectMocks MyServiceImpl serviceMock;
private MyCommand command;
@Before public void beforeEach() {
MockitoAnnotations.initMocks(this);
command = new MyCommand();
when(serviceMock.doSomething()).thenReturn(-1); // <- Error here
}
@Test public void mockInjected() {
boolean result = command.executeSomething();
verify(serviceMock).doSomething();
assertThat(result, equalTo(false));
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Mockito API运行JUnit测试.
我有以下CacheTest类
public class CacheTest {
public static final String KEY_1 = "key1";
public static final long VALUE_1 = 1L;
public static final long VALUE_2 = 2136L;
private static final String KEY_2 = "key2";
private Cache<String, Long> objectUnderTest;
@Mock
private CacheLoader<String, Long> cacheLoader;
@Before
public void setUp() {
objectUnderTest = new Cache<>(1000L, cacheLoader); //cacheLoader is null here
when(cacheLoader.load(Matchers.eq(KEY_1))).thenReturn(VALUE_1); //nullpointer when trying to load from null
when(cacheLoader.load(Matchers.eq(KEY_2))).thenReturn(VALUE_2);
}
@Test
public void shouldLoadElement() {
// when
Long value = objectUnderTest.get(KEY_1);
// …Run Code Online (Sandbox Code Playgroud) 我有一个简单的spring boot控制器,我想为其编写单元测试,但是有错误。我已经搜索了几个小时,但仍然找不到解决方案。这是代码:
HelloController.java
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String sayHello(){
return helloService.sayHello();
}
}
Run Code Online (Sandbox Code Playgroud)
HelloService.java:
@Service
public class HelloService {
public String sayHello(){
return "Hello";
}
}
Run Code Online (Sandbox Code Playgroud)
和单元测试文件:HelloControllerTest.java:
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private HelloService helloService;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void sayHello() throws Exception {
when(helloService.sayHello()).thenReturn("thach");
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("thach"));
}
}
Run Code Online (Sandbox Code Playgroud)
但是有一个错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at …Run Code Online (Sandbox Code Playgroud) java ×9
mockito ×9
unit-testing ×6
junit ×5
junit4 ×3
android ×2
spring-boot ×2
guice ×1
junit-rule ×1
junit5 ×1
mocking ×1
robolectric ×1
spring ×1