简体   繁体   English

Scala 在测试时不会抛出异常

[英]Scala does not throw Exception while testing

I am not able to simulate throwing an Exception in Scala test.我无法模拟在 Scala 测试中抛出异常。 Getting error: Expected exception java.lang.Exception to be thrown, but no exception was thrown获取错误:预期抛出异常 java.lang.Exception,但未抛出异常

test("test with Exception"){
   val generatorService=mock[GeneratorService]
   val entityProviderRequest=new EntityProviderRequest(entity:Entity)
   when(generatorService.generateVertex(entityProviderRequest.entity, "abc")).thenThrow(new RuntimeException)
   intercept[Exception]{
     generatorService.generateElements(entityProviderRequest, "abc")
   }
}

The method you call inside intercept is not the same as the one you defined above.您在intercept调用的方法与您在上面定义的方法不同。 That's why it doesn't throw an exception.这就是它不会抛出异常的原因。 When the behaviour is not defined, the mock object simply returns null .当行为未定义时,模拟对象仅返回null The below test should succeed.下面的测试应该会成功。

test("test with Exception"){
   val generatorService = mock[GeneratorService]
   val entityProviderRequest = new EntityProviderRequest(entity)
   when(generatorService.generateElements(entityProviderRequest, "abc"))
     .thenThrow(new RuntimeException)

   intercept[Exception]{
     generatorService.generateElements(entityProviderRequest, "abc")
   }
}

Update更新

If you want to use the real implementation of a method, but mock the others, you can achieve it by using when(..).thenCallRealMethod() :如果你想使用一个方法的真实实现,但模拟其他方法,你可以通过使用when(..).thenCallRealMethod()来实现它:

test("test with Exception"){
   val generatorService = mock[GeneratorService]
   val entityProviderRequest = new EntityProviderRequest(entity)

   when(generatorService.generateElements(entityProviderRequest, "abc"))
     .thenCallRealMethod()
   when(generatorService.generateVertex(entityProviderRequest.entity, "abc"))
     .thenThrow(new RuntimeException)


   intercept[Exception]{
     generatorService.generateElements(entityProviderRequest, "abc")
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM