Has anyone run into this problem? Let's say you have something like this in your Action class: MyObject o = new MyObject(); But you want to mock that object when you're creating a JUnittest for your action class. Now, with an ordinary class, you'd just create the mock object in your Test class, and send it to your Action class through a setter. But according to sourceforge, you should not create your Action class directly when testing it. You let Struts create it. So your Test class has no reference to your Action class. In fact, the Action object hasn't even been created when the Test class calls actionPerform(). How do I mock up this object, configure it the way I want, and then save it so the Action class can get it? The best I can come up with so far is to subclass my Action class, and when testing, have Struts call the subclass. I override the getter for MyObject in the subclass, and have it retrieve the mocked object from the HttpSession. (That's where I store the mocked object in my Test class.) My architect thinks this is a phony and bad approach. But I can't come up with anything else! Anybody?
I kind of feel that this question belongs in the Testing forum but I'll ask you to elaborate on a few things before deciding to move it there: 1. Why are you creating an object in your Action? Does the object truly belong in the Action? Would it be more appropriate in a business tier object that the action delegates to? Would it be easier to test if you refactored to that? 2. Are you using JUnit or some extension to JUnit? If you're using JUnit, I don't see any straightforward way to let the Struts framework create your action.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Originally posted by Junilu Lacar: 2. Are you using JUnit or some extension to JUnit? If you're using JUnit, I don't see any straightforward way to let the Struts framework create your action.
Take a look at StrutsTestCase. It is pretty sweet for Unit Testing Struts Applications. As far as the original question... why not introduce some type of Factory Method for the creation of the object. During testing the Factory could be configured to hand back your mock object. However, I have to agree with Junilu, we don't really know enough about what you are doing to really give a good suggestion. BTW, welcome to JavaRanch!
Do not set lab on fire. Or this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop