2

I saw that on here, you can have a framework called Mockery generate mocks for interfaces for you. This is close to a big deal, because I am already using testify, which has built-in mock API (which, until now, I have not used yet).

The drawback, however, is that it requires interfaces, whereas the code under test is a struct, with nested dependencies, both business logic and third-party code. I am not in charge of refactoring the code base (thank God), and am looking to mock this

package context

//ApplicationContext The context to use if the use of an application is needed.
type ApplicationContext struct {
    DatabaseContext
}

//GetAppId Gets the application id from the session.
func (c *ApplicationContext) GetAppId() int {
    if str := c.GetFromSession("ApplicationId"); str != nil {
        return str.(int)
    }
    return -1
}

//SetAppId Sets the application id into the session.
func (c *ApplicationContext) SetAppId(id int) {
    c.SetToSession("ApplicationId", id)
}

which extends DatabaseContext, which has Session.Store (third-party dependency that is used by those two functions) along with some other dependencies that are none of my concern.

How could I mock this struct?

Mike Warren
  • 3,796
  • 5
  • 47
  • 99
  • 3
    You can't. If something accepts a concrete type, that's the only type you can use, not a mock type. You can only mock/stub if it accepts an interface you can implement. – Adrian Aug 13 '18 at 15:05
  • Poorly-written Java code is also difficult to test. The dynamic classloader that lets you pull all sorts of runtime hijinks in Java comes with a significant runtime complexity and memory cost. There are always tradeoffs. – Adrian Aug 13 '18 at 15:08
  • Would it then be acceptable to "mock" (by this, I mean 'stub') the `Session.Store` that the code under test relies on under the hood, and then use it? – Mike Warren Aug 13 '18 at 15:39

0 Answers0