I'm trying to mock twilio module but it's being a pain. I'm new to Jest and I've read docs but it's not clear how should I mock a class and a type.
This is the code that I'm trying to mock:
const Twilio = require('twilio')
const client = new Twilio('sid', 'auth')
const response = new Twilio.twiml.VoiceResponse()
The part of constructor new Twilio is doing fine:
jest.mock('twilio', () => class {
constructor (accountSid, authToken) {
this.conferences = {
list () {
return mockTwilioListConferences()
}
}
}
})
But how can I mock the part new Twilio.twiml.VoiceResponse()?
Twilio developer evangelist here.
Disclaimer, I haven't tried this, but here's how I believe this works.
The twiml property on the Twilio class is just that, a property. In your mock you instantly return a new anonymous class, but if you add the property to the class itself before you return you should find it is then part of your mock.
For example:
jest.mock('twilio', () => {
const mockClass = class {
constructor (accountSid, authToken) {
this.conferences = {
list () {
return mockTwilioListConferences()
}
}
}
}
mockClass.twiml = {
// complete your mock implementation here
}
return mockClass;
);
Let me know if that helps at all.
I am trying to test a method that does an invocation with a closure, something like this:
def foo(Long param) {
AnObject.doSomething {
bar(param)
}
}
And I want to test that doSomething is called with a closure that calls bar with the expected value inside.
I'm able to test properly the doSomething invocation by creating a spy and doing
when:
service.foo(1L)
then:
1 * AnObject.doSomething{_}
However, I cannot seem to find a way to perform assertions on the contents of the closure.
What's the appropriate way to assert that inside the closure bar gets called with 1L?
Without seeing more of your code, I think you would need to spy on the class providing the bar method. This is a bit contrived because the test is supplying the closure, but I think it is something like this:
import spock.lang.Specification
class Bar {
void bar(def param) {
println param
}
}
class DoSomethingTestSpec extends Specification {
class AnObject {
void doSomething(Closure c) {
def param = 1L
c.call(param)
}
}
def "test AnObject doSomething calls the closure"() {
given:
def closure = { def p ->
Bar.bar(p)
}
and:
GroovySpy(Bar, global:true)
and:
AnObject anObject = new AnObject()
when:
anObject.doSomething(closure)
then:
1 * Bar.bar(_) >> { args ->
assert args[0] == 1L
}
}
}
I am using JDBI 3 and have written the following utility function.
public class JdbiHelper {
// ...
public <T, DAO> T fetch(final Function<DAO, T> function, Class<DAO> daoClass) {
return dbi.withHandle(handle -> {
final DAO dao = handle.attach(daoClass);
try {
return function.apply(dao);
}
finally {
handle.close();
}
});
}
}
which I can call in methods like this
public Optional<Account> findByEmailAddress(final String emailAddress) {
if (!exists(emailAddress))
return Optional.empty();
return jdbiHelper.fetch(dao -> ofNullable(dao.selectByEmailAddress(emailAddress)), AccountDAO.class);
}
private boolean exists(final String emailAddress) {
return jdbiHelper.fetch(dao -> dao.count(emailAddress) > 0, AccountDAO.class);
}
I am trying to write a test for the findByEmailAddress mocking jdbiHelper using Mockito 2 but cannot work out how to mock the dao -> part of the method.
I've tried using jdbiHelper.fetch(any(Function.class), eq(AccountDAO.class)) but as there are two different expectations of what to return it fails trying to cast one or the other.
Passing in a mocked Function causes a NPE as the dao param is null.
I am fairly new to golang and I am struggling with a simple task.
I have the following class in golang
type struct A {
}
func (s *A) GetFirst() {
s.getSecond()
}
func (s *A) getSecond() {
// do something
}
And I want to write some tests for it however for that I need to override getSecond(). I attempted to do the following in my test files
type Ai interface {
getSecond()
}
type testA struct {
A
}
func (s *testA) getSecond() {
// do nothing
}
func TestA(t *testing.T) {
a := &A{}
t := &testA{A: a}
t.GetFirst()
}
The idea here is to expose A getSecond() method to an interface and override by using embedding however this does not seem to work. The test still calls the original implementation of getSecond() instead of my mocked one.
One solution would of course be to create a proper interface for A which contains getFirst() and getSecond() and then in the test create a struct implementing both where getFirst() call the original implementation and getSecond() a dummy however I feel this is cumbersome and not the correct way of doing things.
Another possibility would be to assign getSecond() in the real implementation to a variable and override the variable in test but I also feel it is a bit strange to do this just for a simple override.
Am I going all wrong about this? Is there any way simpler way to do this using golang?
You can't really override methods in golang as per this answer. However, as you point out you can have a separate interface for the "getSecond method" and have one implementation in your test cases and one implementation in your actual code.
type s interface{
getSecond()
}
type A struct{
s
}
type a struct{
}
func (s *A) GetFirst() {
s.getSecond()
}
func (s a) getSecond() {
// do something
}
//Use a
A{a{}}
Then in Test have a different implementation of 'a'
type ta struct {
}
func (s ta) getSecond() {
// do nothing
}
A{ta{}}
mockcompose (https://github.com/kelveny/mockcompose) was created by me to address exactly the problem.
Class in Go is not the first class citizen, for those who come from other language worlds (i.e. Java), lack of ability for mocking sibling methods sometimes bothers.
Say you have a class foo
package foo
type foo struct {
name string
}
func (f *foo) Foo() string {
if f.Bar() {
return "Overriden with Bar"
}
return f.name
}
func (f *foo) Bar() bool {
if f.name == "bar" {
return true
}
return false
}
You want to test Foo() method, however, when Foo() calls Bar(), you want Bar() to be mocked.
With mockcompose, you can first configure go generate and let mockcompose generate plumbing things for you.
mocks.go
//go:generate mockcompose -n testFoo -c foo -real Foo -mock Bar
package foo
mockcompose will then generate code: mockc_testFoo_test.go
//
// CODE GENERATED AUTOMATICALLY WITH github.com/kelveny/mockcompose
// THIS FILE SHOULD NOT BE EDITED BY HAND
//
package foo
import (
"github.com/stretchr/testify/mock"
)
type testFoo struct {
foo
mock.Mock
}
func (f *testFoo) Foo() string {
if f.Bar() {
return "Overriden with Bar"
}
return f.name
}
func (m *testFoo) Bar() bool {
_mc_ret := m.Called()
var _r0 bool
if _rfn, ok := _mc_ret.Get(0).(func() bool); ok {
_r0 = _rfn()
} else {
if _mc_ret.Get(0) != nil {
_r0 = _mc_ret.Get(0).(bool)
}
}
return _r0
}
Now, all you need to do is just to write your unit testing logic as you do in other languages (i.e. Java), for example:
func TestFoo(t *testing.T) {
assert := require.New(t)
fooObj := &testFoo{}
// Mock sibling method Bar()
fooObj.On("Bar").Return(false)
s := fooObj.Foo()
assert.True(s == "")
}
For details, please check out https://github.com/kelveny/mockcompose, mockcompose can also help you test regular functions with callouts to imported functions from other packages.
I think there are at least two alternatives.
Use always a function field
When the function mocked is something not related to the struct I'm mocking, maybe a third party function, or something written from another component of my application.
I will assign the real working one when initializing the service or the mocked one on the tests.
// service.go
type MyService struct {
getRandomID func() string
}
type Car struct {
ID string
Name string
}
func (s *MyService) NewCar() (*Car, error) {
car := Car{
ID: s.getRandomID(),
Name: "ThisCar",
}
return &car, nil
}
// service_test.go
func newIDsForTests() func() string {
i := 0
return func() string {
i++
return fmt.Sprintf("%024d", i)
}
}
func TestNewCar(t *testing.T) {
s := MyService{
getRandomID: newIDsForTests(),
}
actual, err := s.NewCar()
if err != nil {
panic(err)
}
expected := Car{ID: "000000000000000000000001", Name: "ThisCar"}
if *actual != expected {
panic("cars don't match")
}
}
The Go Playground working example
Use a function field only when mocking
When the function to be mocked is something really related to the struct I'm working with, that is part of this component.
I will always use the real working, and assign a mock function when needed for the tests.
While I think this solution is quite ugly, I also think that is for sure easily to use and to maintain, while also let you unit test your code at 100%!
My idea is to add a field mockedGetSecond to the struct, and to set its value only in the tests where you want to mock the real getSecond. In the real implementation you have to add a check of course, that if this func isn't nil, it must be used.
This is probably not a good pattern, or something I would like to use often, but I think I'll will use it to mock a function that do a lot of logic (and a lot of db calls, and need various input, ...) and is often called in the functions in the same service.
// service.go
import (
"fmt"
"testing"
)
type MyService struct {
mockedGetSecond func() (string, error)
}
func (s *MyService) GetFirst() error {
secondVal, err := s.getSecond()
if err != nil {
return err
}
fmt.Println("getSecond returned: ", secondVal)
return nil
}
func (s *MyService) getSecond() (string, error) {
if s.mockedGetSecond != nil {
return s.mockedGetSecond()
}
// very complex function
return "real", nil
}
// service_test.go
func TestGetFirst(t *testing.T) {
myService := MyService{
mockedGetSecond: func() (string, error) {
return "mocked", nil
},
}
err := myService.GetFirst()
if err != nil {
panic(err)
}
}
func TestGetSecond(t *testing.T) {
myService := MyService{}
actual, err := myService.getSecond()
if err != nil {
panic(err)
}
if actual != "real" {
panic("I would expect 'real'")
}
}
The Go Playground working example
=== RUN TestGetFirst
getSecond returned: mocked
--- PASS: TestGetFirst (0.00s)
=== RUN TestGetSecond
--- PASS: TestGetSecond (0.00s)
PASS
In case someone ends up here on a similar dive down the rabbit hole: I wanted to mock a function called by another function to ensure it's called x times under specific conditions, such as you would do with Jest for example. I wanted to keep the program code as test-agnostic as possible, and having had little success with receiver methods and overriding functions in interfaces I opted for simply passing a function reference as an argument. So if you aren't dead set on an OOP style approach:
// app.go
type SubDoer func(string) string
func SubDo(something string) string {
...
return something
}
func DoHandler(somethings []Something) string {
return Do(somethings, SubDo)
}
func Do(somethings []Something, subDoer SubDoer) string {
...
subDoer(something)
return somethingElse
}
The DoHandler() function gives us a wrapper to call Do() with the actual SubDo() implementation, and we can unit test Do() with a mocked SubDo() by skipping the handler function:
// app_test.go
type MockDoer struct {
counter int
}
func (m *MockDoer) SubDo(string) string {
m.counter++
return "something"
}
// Calls the mocked function from Do()
func TestDoWithMockedSubDo(t *testing.T) {
mock := &MockDoer{}
...
assert.Equal(t, "something", Do(somethings, mock.SubDo))
assert.Equal(t, mock.counter, xAmount)
}
// Calls DoHandler() which calls Do() with the unmocked SubDo()
func TestDo(t *testing.T) {
...
assert.Equal(t, "something else", DoHandler(somethings))
}
// SubDo() is unaffected by the mocks
func TestSubDo(t *testing.T) {
...
assert.Equal(t, "a thing", SubDo(something))
}
I have this Java test with Mockito:
public class PersistentNodeDeserializerTests {
#Test
public void userInfoPersistentNodeDeserializer() {
PersistentNode node = mock(PersistentNode.class);
when(node.stringChild("username")).thenReturn("cliff12");
//more stuff
}
}
PersistentNode is a Kotlin class:
open class PersistentNode(private val path: PersistentNodePath, val content: Any) {
val stringPath: String
get() = path.get()
val key: String
get() {
val parts = stringPath.split("/");
return parts[parts.size - 1];
}
val mapContent: Map<String, Any>
get() {
return content as HashMap<String, Any>
}
fun stringChild(child: String): String {
return mapContent.get(child) as String
}
}
I get this error:
kotlin.TypeCastException: null cannot be cast to non-null type
java.util.HashMap
How can I mock the property stringChild properly?
this library may solve your issue https://github.com/nhaarman/mockito-kotlin
EDIT: sorry, didn't realize you were using a Java test. If it's an option, try writing your test in kotlin too