2011-08-10 61 views
5

我有一个Spring Web应用程序,我想为我的控制器进行unittests。我决定不使用Spring来设置我的测试,而是将Mockito模拟对象与我的控制器一起使用。Mockito Testcase忽略注释

我使用Maven2和surefire插件构建并运行测试。这是从我的pom.xml

 <!-- Test --> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-test</artifactId> 
      <version>${spring.framework.version}</version> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.junit</groupId> 
      <artifactId>com.springsource.org.junit</artifactId> 
      <version>4.5.0</version> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.mockito</groupId> 
      <artifactId>mockito-all</artifactId> 
      <version>1.9.0-rc1</version> 
      <scope>test</scope> 
     </dependency> 
    </dependencies> 
</dependencyManagement> 

设置我的编译器和神火插件这样的:

<build> 
    <pluginManagement> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <configuration> 
        <verbose>true</verbose> 
        <compilerVersion>1.6</compilerVersion> 
        <source>1.6</source> 
        <target>1.6</target> 
       </configuration> 
      </plugin> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-surefire-plugin</artifactId> 
       <version>2.4.3</version> 
      </plugin> 

我的测试类是这样的:

@RunWith(MockitoJUnitRunner.class) 
public class EntityControllerTest { 

private EntityController entityController; 

private DataEntityType dataEntityType = new DataEntityTypeImpl("TestType"); 

@Mock 
private HttpServletRequest httpServletRequest; 

@Mock 
private EntityFacade entityFacade; 

@Mock 
private DataEntityTypeFacade dataEntityTypeFacade; 

@Before 
public void setUp() { 
    entityController = new EntityController(dataEntityTypeFacade, entityFacade); 
} 

@Test 
public void testGetEntityById_IllegalEntityTypeName() { 
    String wrong = "WROOONG!!"; 
    when(dataEntityTypeFacade.getEntityTypeFromTypeName(wrong)).thenReturn(null); 
    ModelAndView mav = entityController.getEntityById(wrong, httpServletRequest); 
    assertEquals("Wrong view returned in case of error", ".error", mav.getViewName()); 
} 

注释各地: - )

但是,当从命令行构建时,我在行中得到NullPointerException时(dataEntityTypeF acade.getEntityTypeFromTypeName(错误))thenReturn(空)。因为dataEntityTypeFacade对象为null。当我在Eclipse中运行我的测试用例时,一切正常,我的模拟对象被实例化,并且用@Before标注的方法被调用。

为什么从命令行运行时,我的注释看起来被忽略?

/EVA

+0

通过“从命令行建设”,你的意思是行家建立还是其他的东西? –

回答

5

你打电话:

MockitoAnnotations.initMocks(testClass); 
在基类或测试运行如在这里提到

http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#9

+1

我忘了在问题中发布这个问题:我的测试类定义上方有@RunWith(MockitoJUnitRunner.class)。我理解它的方式,我不应该调用initMocs。 –

+0

是的,但这是它为我们工作的唯一方式。 –

+0

我阅读了文档,它听起来像你需要initMocks()行才能工作;它是粗体的“重要!”部分。它表示你“可能”使用Runner;我不确定有没有亚军的区别。但你肯定需要这条线。 IMO - @Mock注释不如手动设置模拟。 –