Building Local Unit Tests

本文介绍如何设置本地单元测试环境,并使用JUnit4框架进行高效的单元测试。文中详细解释了如何配置测试依赖、创建测试类和方法,以及如何使用Mockito框架模拟Android依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

If your unit test has no dependencies or only has simple dependencies on Android, you should run your test on a local development machine. This testing approach is efficient because it helps you avoid the overhead of loading the target app and unit test code onto a physical device or emulator every time your test is run. Consequently, the execution time for running your unit test is greatly reduced. With this approach, you normally use a mocking framework, like Mockito, to fulfill any dependency relationships.

Set Up Your Testing Environment


In your Android Studio project, you must store the source files for local unit tests at module-name/src/test/java/. This directory already exists when you create a new project.

You also need to configure the testing dependencies for your project to use the standard APIs provided by the JUnit 4 framework. If your test needs to interact with Android dependencies, include theMockito library to simplify your local unit tests. To learn more about using mock objects in your local unit tests, see Mocking Android dependencies.

In your app's top-level build.gradle file, you need to specify these libraries as dependencies:

dependencies {
    // Required -- JUnit 4 framework
    testCompile 'junit:junit:4.12'
    // Optional -- Mockito framework
    testCompile 'org.mockito:mockito-core:1.10.19'
}

Create a Local Unit Test Class


Your local unit test class should be written as a JUnit 4 test class. JUnit is the most popular and widely-used unit testing framework for Java. The latest version of this framework, JUnit 4, allows you to write tests in a cleaner and more flexible way than its predecessor versions. Unlike the previous approach to Android unit testing based on JUnit 3, with JUnit 4, you do not need to extend the junit.framework.TestCase class. You also do not need to prefix your test method name with the ‘test’ keyword, or use any classes in the junit.framework or junit.extensions package. 

//JUnit是最流行的和广泛使用的Java测试框架。最近的版本Junit4比之前的版本都更加简洁和流畅。你也不需要继承TestCase类,你也不需要强制让测试方法的前缀为test

To create a basic JUnit 4 test class, create a Java class that contains one or more test methods. A test method begins with the @Test annotation and contains the code to exercise and verify a single functionality in the component that you want to test.

The following example shows how you might implement a local unit test class. The test method emailValidator_CorrectEmailSimple_ReturnsTrueverifies that the isValidEmail() method in the app under test returns the correct result.

import org.junit.Test;
import java.util.regex.Pattern;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class EmailValidatorTest {

    @Test
    public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
        assertThat(EmailValidator.isValidEmail("name@email.com"), is(true));
    }
    ...
}

To test that components in your app return the expected results, use the junit.Assert methods to perform validation checks (or assertions) to compare the state of the component under test against some expected value. To make tests more readable, you can use Hamcrest matchers (such as the is() and equalTo() methods) to match the returned result against the expected result.

Mock Android dependencies

By default, the Android Plug-in for Gradle executes your local unit tests against a modified version of the android.jar library, which does not contain any actual code. Instead, method calls to Android classes from your unit test throw an exception.

You can use a mocking framework to stub out external dependencies in your code, to easily test that your component interacts with a dependency in an expected way. By substituting Android dependencies with mock objects, you can isolate your unit test from the rest of the Android system while verifying that the correct methods in those dependencies are called. The Mockito mocking framework for Java (version 1.9.5 and higher) offers compatibility with Android unit testing. With Mockito, you can configure mock objects to return some specific value when invoked.

To add a mock object to your local unit test using this framework, follow this programming model:

  1. Include the Mockito library dependency in your build.gradle file, as described in Set Up Your Testing Environment.
  2. At the beginning of your unit test class definition, add the @RunWith(MockitoJUnitRunner.class) annotation. This annotation tells the Mockito test runner to validate that your usage of the framework is correct and simplifies the initialization of your mock objects.
  3. To create a mock object for an Android dependency, add the @Mock annotation before the field declaration.
  4. To stub the behavior of the dependency, you can specify a condition and return value when the condition is met by using the when() andthenReturn() methods.

The following example shows how you might create a unit test that uses a mock Context object.

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;

@RunWith(MockitoJUnitRunner.class)
public class UnitTestSample {

    private static final String FAKE_STRING = "HELLO WORLD";

    @Mock
    Context mMockContext;

    @Test
    public void readStringFromContext_LocalizedString() {
        // Given a mocked Context injected into the object under test...
        when(mMockContext.getString(R.string.hello_word))
                .thenReturn(FAKE_STRING);
        ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);

        // ...when the string is returned from the object under test...
        String result = myObjectUnderTest.getHelloWorldString();

        // ...then the result should be the expected one.
        assertThat(result, is(FAKE_STRING));
    }
}

To learn more about using the Mockito framework, see the Mockito API reference and the SharedPreferencesHelperTest class in the sample code.

Run Local Unit Tests


To run your local unit tests, follow these steps:

  1. Be sure your project is synchronized with Gradle by clicking Sync Project  in the toolbar.
  2. Run your test in one of the following ways:
    • To run a single test, open the Project window, and then right-click a test and click Run .
    • To test all methods in a class, right-click a class or method in the test file and click Run .
    • To run all tests in a directory, right-click on the directory and select Run tests .

The Android Plugin for Gradle compiles the local unit test code located in the default directory (src/test/java/), builds a test app, and executes it locally using the default test runner class. Android Studio then displays the results in the Run window.

转载于:https://www.cnblogs.com/yexiant/p/5681943.html

<think>嗯,用户的问题是关于如何正确配置或运行Profile Unit Tests,以及解决未找到的问题。首先,我需要理解“Profile Unit Tests”具体指的是什么。可能用户指的是某种特定的单元测试配置,或者是IDE(比如IntelliJ IDEA)中的测试配置问题。根据用户提供的引用,特别是引用[1]提到的单元测试报错“No tests found in XXXTest”,这可能和测试目录的配置有关。 用户提到test文件夹和src文件夹同级,并且需要正确标记为Test Sources Root。引用[1]中强调一定不要标记错,所以正确的目录结构配置是关键。接下来,我需要检查常见的测试配置步骤,比如在IntelliJ中,右键点击测试目录,选择“Mark Directory as” -> “Test Sources Root”,确保测试类符合命名约定,比如以Test结尾或使用@Test注解。 另外,用户可能使用了不同的构建工具,比如Maven或Gradle,这些工具对测试目录有默认的约定。如果项目结构不符合这些约定,即使标记正确,构建工具也可能找不到测试。比如Maven默认的测试目录是src/test/java,如果用户将测试放在其他位置,需要在pom.xml中配置。 还有可能是测试框架的问题,比如JUnit版本不兼容,或者测试方法没有正确使用注解。需要检查测试类是否导入了正确的JUnit包,以及测试方法是否有@Test注解。此外,检查运行配置是否正确,比如是否指定了正确的测试类或模块。 用户提供的引用[3]中有一个Perl脚本用于检查已安装的模块,这可能和依赖管理有关。如果项目依赖未正确安装或配置,可能导致测试无法运行。需要确保所有测试依赖项都已正确添加到构建配置中,比如pom.xml或build.gradle文件。 另外,环境变量或路径问题也可能导致测试找不到,如引用[2]提到的配置PATH变量。虽然主要是针对Flutter的,但类似的问题可能出现在其他环境,比如Java的CLASSPATH设置不正确,导致测试类无法被加载。 总结下来,解决步骤可能包括:检查测试目录配置、验证测试命名和注解、检查构建工具配置、确保依赖正确、检查环境变量和路径设置。需要逐步排除这些可能性,帮助用户定位问题所在。</think>### 如何正确配置或运行 Profile Unit Tests? #### 1. **确认测试目录配置** - **IDE中的测试标记**:在IntelliJ IDEA或类似IDE中,确保`test`目录已正确标记为**Test Sources Root**(右键目录 → Mark Directory as → Test Sources Root)[^1]。 - **目录层级规范**:测试目录应与`src`目录同级,例如: ``` project-root/ ├── src/ └── test/ # 标记为Test Sources Root ``` #### 2. **检查测试文件命名与结构** - **命名约定**:测试类需以`Test`结尾(如`ExampleTest.java`)或使用`@Test`注解(取决于框架要求)。 - **包路径一致性**:测试类应与被测试类处于**相同包路径**下。例如: - 源码包:`src/main/java/com/example/Service.java` - 测试包:`src/test/java/com/example/ServiceTest.java` #### 3. **依赖与框架配置** - **构建工具集成**: - **Maven**:确保`pom.xml`中包含测试框架依赖(如JUnit): ```xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> ``` - **Gradle**:在`build.gradle`中配置测试依赖: ```groovy dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' } ``` - **环境变量配置**:若涉及外部工具(如Flutter),需在系统PATH中添加路径(参考[^2]的`.zprofile`配置方法)。 #### 4. **运行与调试测试** - **IDE操作**:右键测试类 → Run/Debug,或使用命令行工具(如Maven的`mvn test`)。 - **常见报错处理**: - **No tests found**:检查测试方法是否含`@Test`注解,或尝试清理缓存(File → Invalidate Caches)。 - **依赖缺失**:通过类似引用[^3]的脚本验证依赖安装状态。 #### 5. **配置文件示例(以Flutter为例)** ```bash # macOS环境配置(~/.zprofile) export PATH="$PATH:/Applications/flutter/bin" # 确保Flutter命令可访问[^2] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值