4

I want the closeSession() method to throw an Exception when it is called so that I can test to see my logging is being done. I have mocked the Crypto object as mockCrypto and set it up as follows:

@Test
  public void testdecrpyMcpDataExceptions() throws Exception {
    Crypto mockCrypto = Mockito.mock(Crypto.class);
      try {
            mockCrypto = CryptoManager.getCrypto();
            logger.info("Cyrpto Initialized");
      } finally {
            logger.info("Finally");
            try {
                logger.info("About to close Crypto!");
                Mockito.doThrow(new CryptoException("")).when(mockCrypto).closeSession();
                mockCrypto.closeSession();
                } catch (CryptoException e) {
                    logger.warn("CryptoException occurred when closing crypto session at decryptMcpData() in CipherUtil : esi");

                }
            }
    }

However when I run it I get the error :

Argument passed to when() is not a mock!

Am I mocking the class wrong or am I just missing something?

4

2 回答 2

4

don't you overwrite your mock at

mockCrypto = CryptoManager.getCrypto();

Tested

@Test(expected=RuntimeException.class)
    public void testdecrpyMcpDataExceptions() throws Exception {
        Crypto mockCrypto = mock(Crypto.class);

        doThrow(new RuntimeException()).when(mockCrypto).closeSession();
        mockCrypto.closeSession();

    }

works fine.

于 2013-03-13T14:37:04.267 回答
1

this line is overwriting your mock:

mockCrypto = CryptoManager.getCrypto();

and thats why it fails.

于 2013-03-13T14:37:14.950 回答