2011-08-10 117 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註釋不如手動設置模擬。 –