我想嘲笑我的課內的對象。Java測試與mockito:模擬類對象
public class Controller{
private StandardEmailSender sender = new StandardEmailSender();
public void process() throws EmailException {
// do some stuff
sender.sendEmail(to, subject, body);
// do some stuff
}
}
我想模擬sender.sendEmail(to, subject, body);
。我花了一些時間找到一個解決方案,但我卡住了。我試圖直接嘲笑對象StandardEmailSender是這樣的:
@Mock
StandardEmailSender sender;
@Before
public void setUp() throws EmailException {
MockitoAnnotations.initMocks(this);
doNothing().when(sender).sendEmail(anyString(), anyString(), anyString());
}
@Test
public void test() throws EmailException {
Controller controller= new Controller();
controller.process();
//make some asserts
}
有人有我的問題的解決方案嗎?謝謝!
好,謝謝,@InjectMocks詮釋完美的作品 – Kagelmacher
@Kagelmacher是它。但有些人仍然不喜歡它:https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/ ...並在如果您發現我的答案充足,請不要忘記在某些時候接受。 – GhostCat