我使用Intellj Ultimate,并且有问题运行Mockito测试类。
如果我使用这样的类
import org.junit.jupiter.api.Test;
class FactoryTest {
@Test
void createEntry() {
}
}
我可以直接"运行"此类。
如果我有:
import static org.mockito.Mockito.when;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
//@InjectMocks annotation is used to create and inject the mock object
@InjectMocks
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
when(calcService.add(10.0,20.0)).thenReturn(30.00);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
}
}
我必须以前创建另一个课程并运行对我来说似乎是不正确的,因为在该教程中,关于启动测试的ExluCISV类别http://www.vogella.com/tutorials/mockito/article。
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
我的pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>1</groupId>
<artifactId>2</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>1</groupId>
<artifactId>2</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
</project>
MockitoJUnitRunner
已经弃用。
摆脱它后,您可以使用@Before
宣布的方法初始化模型:
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}