在方法return和UnsupportedOperationException方法中模拟注入的对象

时间:2019-04-10 22:55:30

标签: junit mockito

我有一个使用Mockito返回注入对象的类。每次测试时,它都会返回公牛。我将如何正确测试它以返回正确的对象?

我要测试的班级:

@Component
 public class CarImpl {
    @Inject
     private Engine v6EngineImpl;

    public Engine getEngine() {
        return v6EngineImpl;
}

public Exhaust getExhaust() {
         throw new UnsupportedOperationException("unsupported");
     }
}

测试:

@RunWith(MockitoJUnitRunner.class)
 public class CarTest {
    @InjectMocks
     private CarImpl carImpl;

@Mock
private Engine v6EngineImpl;

     @Test
     public void testGetEngine(){
       Engine v6EngineImpl = mock(V6EngineImpl.class);
       Engine engine = carImpl.getEngine();

      // always returns a bull no matter what, how to mock inject. 
      //return object correctly? 
      Assert.assertNotNull(engine);
   }

    @Test
     public void testGetExhaust() {
         // how to test thrown exception? 
     }
}

谢谢,我不太熟悉

1 个答案:

答案 0 :(得分:1)

尝试一下:

@RunWith(MockitoJUnitRunner.class)
 public class CarTest {

 @InjectMocks
 private CarImpl carImpl;

 @Mock
 private Engine v6EngineImpl;

     @Test
     public void testGetEngine(){
      Engine engine = carImpl.getEngine();

      //engine is the mock injected to CarImpl
      Assert.assertNotNull(engine);
      Assert.assertSame(engine,v6EngineImpl);
   }

    @Test(expected=UnsupportedOperationException.class)
     public void testGetExhaust() {
          carImpl.getExhaust();
     }
}