我在 Mockito junit 测试中遇到问题。我是新手,对问题有点困惑。对此的任何帮助将不胜感激。
这些是我打算写的类(class)
public class B extends QuartzJobBean {
private B b;
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
b.expireContract();
} catch (BusinessServiceException e) {
LOGGER.error("BusinessServiceException in B : " +
e.getMessage());
LOGGER.debug("BusinessServiceException in B : ", e);
} catch (Exception e) {
LOGGER.error("Exception in B : " +
e.getMessage());
LOGGER.debug("Exception in B : ", e);
}
}
public class C {
@Autowired
private D d;
public boolean expireTime() throws BusinessServiceException
{
try {
contractBusinessService.expireContract();
return true;
} catch (Exception e)
{
e.getMessage();
return false;
}
}
出现以下异常:
*org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!*
这是我的junit测试代码
class BTest(){
B b;
@Before
public void setUp() {
b= Mockito.spy(new B());
c= PowerMock.createMock(C.class);
b.setC(c);
}
@Test
public void testExpireContract() {
Mockito.doNothing().when(c).expireTime();
try {
b.executeInternal(j);
fail("BusinessServiceException should have thrown.");
} catch (Exception wse) {
assertEquals("BusinessServiceException should be same.", "BusinessServiceException", wse.getMessage());
}
verify(b).expireTime();
Assert.assertNotNull("value should not be null.", b);
}
最佳答案
测试使用两个不同的模拟库
问题就在这里c= PowerMock.createMock(C.class);
您尝试使用 c 对象(PowerMock 模拟对象),就好像它是 Mockito 模拟一样,这就是您收到异常的原因。
// Instead of PowerMock just use Mockito to create a mock
c = Mockito.mock(C.class);
// Then you can pass it to `Mockito.when()` method as an argument
Mockito.doNothing().when(c).expireTime();
实际上,可以use PowerMock along with Mockito ,但需要更多配置。将 PowerMock 与 Mockito 结合使用可提供额外的高级功能,例如模拟静态方法。
关于java - 使用 Mockito NotaMockException 进行 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38427394/