简体   繁体   中英

Tapestry + Spring Unit testing

I have a next situation - I have a service which have dependency with @Inject tapestry annotation which is injected through Spring context using Spring + Tapestry integration. I'd like to unit test this service using using test dependency injection instead of real one. I don't how to make Tapestry use test Spring context and inject into my service instance in test my mocked dependency, use testify or something, please help!

Tapestry has a inbuilt mechanism for testing its page classes using PageTester . Also it has a integration suit using Selenium as explained here .

But I prefer to test Tapestry - spring in a different way.

  1. Get the reference of the services from spring application context.
  2. Use a constructor of the page class and initialize the services. This way you does the job of tapestry by injecting the services.
  3. Now you are all set to test the methods inside the page classes directly.

If we are talking about Unit Testing here

All you need to do is define a public setter method for your dependency (the one you @Injecte'ed) in the Service code. When you write your test, just use the setter and pass the reference to your Mock/Stub/Fake instead of the real implementation.

public class SomeServiceWithDependecies {
    @Inject
    private SomeService _myService;

    // Use this setter in your Unit Test to set _myService to Mock/Stub/Fake implementation
    public void setMyService(SomeService someService) {
      _myService = someService;
    }
}

If you are writing an Integration Test

Spring provides a nice set of annotations which allow you to use a custom context configuration, make your test methods transactional (which is really useful for testing (Tapestry or Spring) services which interact with database), etc.

Here's how your Integration Test class could look like:

@ContextConfiguration(locations = { "/applicationContext-test.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SomeServiceWithDaoDependeciesITCase extends AbstractTransactionalTestNGSpringContextTests {
    // Make sure your applicationContext is properly written
    // and contains <context:annotation-config />
    @Autowired
    private SomeDAO _someDAO;

    // .. your transactional test methods go here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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