Using mocks in Karate DSL feature file with stanal

2019-07-04 21:23发布

I have REST service, written in language different from Java. It have few dependencies from other REST services.

For example service under development and testing is A, other services are respectively B and C.

I want to run system test for A, some tests require B or/and C to be online and perform queries from A.

I wrote b-mock.featue and c-mock.feature to represent that services in mock.

Also I wrote some a-test-smth.feature files to run test against A

Is it possible to add some information into a-test-smth.feature to enable some mocks for concrete test?

Now I should run standalone karate.jar twice, first - for mocking. second - for run tests. That approach works, but, I can't ceck that:

  • some API calls to A not required B or C
  • can't emulate service B down or for example slow or incorrect response answer fetching

Thanks.

标签: karate
1条回答
Bombasti
2楼-- · 2019-07-04 22:09

Are you using Java ? If so then the best approach is to perform the set-up of your test in Java code. You can start 2 mocks for B and c and then start the main test for your service A. And at the end do clean-up if needed.

You can refer this as an example: https://github.com/intuit/karate/tree/master/karate-netty#consumer-provider-example

Row 3 shows how you can start a mock and run a Karate test.

If you are not using Java and would like to use only the stand-alone JAR, it is actually possible using Java-interop and quite easy, I just tried it.

First create this bit of JavaScript code that is smart enough to start a Karate mock:

function() {
  var Mock = Java.type('com.intuit.karate.netty.FeatureServer');
  var file = new java.io.File('src/test/java/mock/web/cats-mock.feature');
  var server = Mock.start(file, 0, false, null);
  return server.port;
}

And this is how it can look in the Background of your main Karate test. You can see how you can do some conditional logic if needed and you have plenty of ways to change things based on your environment.

Background:
    * def starter = read('start-mock.js')
    * def port = karate.env == 'mock' ? starter() : 8080
    * url 'http://localhost:' + port + '/cats'

Does this answer your question ? Let me know and I will add this trick to the documentation !

查看更多
登录 后发表回答