Salesforce TDD (Test-Driven Development)

Disclaimer: The following is written on the basis of what has worked for me in the past. This is not intended to be a formal or exhaustive description. Use it as you see fit, I do not take any responsibility if you screw it up! 🙂

Hi, I’m Diego and I have several years (I prefer not to say how many, but let’s say “enough”) working in Salesforce. I am also an Agile enthusiast and lover of applying related techniques throughout my work.

I’ve found test-driven development (TDD) can be a great technique for building robust software, but when we work in Salesforce, I find some constraints or restrictions can make it frustrating. In this post, I’m going to show when and how I use TDD while coding in Salesforce.

Let’s start at the beginning:

What is TDD?

TDD is an Agile development technique that requires you to write a failing unit test before writing any “production code.”

How are you supposed to do TDD?

First I’ll describe how TDD is done in general (this is the way to go in languages like Java).

  1. Write a unit test and make it fail (a compilation error is considered a failing test). Write no more lines of code than needed.
  2. Write the least possible production code lines to make the test pass (fixing a compilation error is considered a pass test).
  3. Refactor the code.
  4. Repeat until you are done.

Let’s check out an example in Java so you see how it works. In this example, we wanna create an advanced calculator of integers.

We work in split view when doing TDD

ROUND 1

Let’s write a failing unit test:

Oops, MyCalculator is not defined yet, compilation issue…therefore, it is a failing test.

Let’s make the test pass:

Compilation problem fixed! The test is passing again. Woohoo!

No tons of code to refactor. 

ROUND 2

Let’s continue with that test to make it fail again.

Mmm…getOpposite is not defined, ergo compilation issue, ergo failing test.

Let’s fix that. Let’s write the minimum code to fix the test:

getOpposite is defined and returns 0 to any parameter (in particular, 0). Test is passing again!!!

Let’s refactor.

We still don’t have much code to refactor, but there are some name changes we could use to make code easier to read ( yup, yup, yup…unit test code is code, too).

Much better now! 😀

Round 3

Let’s add a new minimum test to fail.

Right now, getOpposite returns 0 to any parameter… it’s a fail!

Let’s write the minimum code required to make the test pass.

Yay! It’s green again! Let’s continue.

Round 4

Let’s add a new failing test.

Last test fail (we are return 0 to any value different than 1), so now we need to write the minimum code to fix this test:

Test is passing again… but this solution is not good, let’s refactor.

Tests are still passing and we solve all the cases! We are done! Well, not actually, we still need to document, test more, write more tests and write even more tests…but we’re on the right path.

I expect this silly example gives you a feel for what TDD is and how it is done.

Now, let’s continue with the discussion, focused on Salesforce.

TDD Advantages

  • Code coverage: We get great code coverage without even thinking about it.
  • Testability: The code is designed to be testable by default (we are actually testing every time we change something).
  • Easier to refactor: We should not change or refactor code without having a set of tests we can lean on. As we are constantly writing tests that we know are able to catch bugs (we make it fail at the beginning), we know that we have a set we can rely on.
  • “Better” code: We are constantly refactoring the code, striving for the best possible code.
  • Predictability: After we finish a “round,” we are completely sure the code is working as we designed it to work and we know we didn’t break anything. We can say we have “working software.”
  • Prevents useless work in Salesforce: In Salesforce, aside from Apex, we have plenty of options to make changes like triggers, workflow rules, process builder, etc. Imagine that after we write a test that changes a value on a contact record, it passes. We could discover that there is another moving part that is taking care of that change (or we wrote the test badly).
  • Documentation: Tests are a great tool to communicate with other developers (or the future you) how, for example, a class API should be called and the expected results of each case.

TDD Disadvantages

  • Overtrust: It happens to me that, as we are testing continuously and we are getting test green, I sometimes have a feeling that the code is working perfectly…but it doesn’t mean it is. We may miss, or simply get lazy, and leave a case out of the unit test.
  • Slow in Salesforce: TDD is designed based on the theory that compiling or writing a test is really fast (a jUnit unit test has to run in less than 1ms). In Salesforce, we need several seconds to compile (the code is compiled on the server) and several more seconds to run the test. In my opinion, this is usually 10+ seconds. As we are compiling and running tests constantly, we add several minutes of “waiting for Salesforce.” However, this can be mitigated if you think you will need to write/compile/execute tests later anyway – you might as well do it upfront.

Me when I realize the QA found a case I had not considered when I was doing TDD

I will (probably) use TDD when…

In general, I’ve found that TDD is a great tool in several circumstances and I tend to do it almost always in the below cases.

  • Back-end bug fixes: Doing TDD in this context has two big advantages. First, you make sure you are able to reproduce the bug consistently. Second, and even more important, as you are writing a test specific to the bug, you know you will never introduce that bug again.
  • Back-end work with clear requirements and a clear implementation strategy: In this context, writing tests is going to be easy and implementing the production code will be easy, too, as you know where you are heading when you create the test cases.
  • Back-end work with clear requirements and minor implementation unknowns: In this context, the test is easy to write and the production code may be getting clearer as you move into cases.
  • Back-end work with some requirements discovery: Imagine in our calculator example you write a test to divide by zero and you realize you’ve never discussed that case with the BA. TDD helps you discover opportunities to clarify requirements.

I might do TDD, but it’s unlikely…

  • As part of requirements discovery: You could write unit tests as part of requirements discovery, and discuss it with your stakeholders, BA, or other technical people, but you probably have better techniques to support this process.
  • Front-end work: I’m gonna discuss this briefly later, when we talk about Lightning web components.

I will never do TDD when…

  • I’m doing a prototype: By definition, a prototype or PoC should be discarded after we show it, so I code it as fast as I can, focused on demonstrating the core functionality.
  • I’m experimenting: If I’m trying a new idea, I don’t focus on code quality (again, this is a prototype).
  • I’m evaluating implementation options: There are some cases where you want to compare two implementation options, so focus on having a good-enough-to-decide prototype and throw it away after you decide…then do the stuff well.
  • I don’t care about code quality: I know code quality is not usually negotiable, but in very limited and extreme situations, it may not be the top priority. For example, when everything is screwed up on prod and you need to fix the problem ASAP because the company is losing millions of dollars per minute. In this very extreme circumstance, fix the problem as fast as you can, make your company earn money again, go to sleep (or maybe get a drink) and tomorrow at 10 am (yup, after a stressful night, start working a little later the next day) make the code beautiful with TDD. Make a test that reproduces the bug and then fix and refactor the code properly.

Me again, but on one of THOSE nights.

  • When creating test code is extremely difficult (but not possible): In Salesforce there are a few elements that are very hard to test, like working with CMT. In this scenario, I’d probably split the problem into two parts – one that is TDD-doable using mocking data (@TestVisible is your best friend here) and a second, smaller part that I’d consider how to test later (if I even consider it).

How I do TDD in Salesforce

I really don’t do TDD as I defined at the beginning of this article when I’m working in Salesforce. Why? Mainly because of the slower compile/test flow, but also because in Apex we generally start writing integration tests instead of unit tests. Instead of “regular” TDD, I tweaked the formula a bit to work better under Salesforce circumstances.

  1. Write an entire deployable test that checks the flow or use case. Yup, I said deployable, so if I called a method I haven’t created yet, I will create it, empty, so I can deploy.
  2. Run it and get a failure.
  3. Write the minimum code that makes that test pass.
  4. Refactor.
  5. Continue with the next flow or use case.
  6. When I’m done with all the flows and use cases, I refactor the code again (splitting methods, checking code cleanliness, documentation). I run the unit test continuously, every few changes to check if everything continues to work as expected.

To make everything clear, let’s view an <could-be-real-world> example.

Requirement:
As a user, I want the values stored in any object copied into a number of specified contact fields. The specified “mappings” will be stored in a CustomMetadataType called Contact_Mappings__cmt. The Contact_Mappings_cmt has two fields:

  • Original_Fields__c Text
  • Mapped_Fields__c Text

Round 1
As I said before, I should start writing an Apex test that tests a business case. The first thing I’m thinking of developing is “The contact should not change if there is no mapping defined.” I have to write a deployable test that is going to fail with the minimum amount of code to make it fail:

We work in split view

As expected, the code deploys but the test fails. So, we need to fix it! We can simply return the same object.

Now It passes, but we don’t have a lot of code to refactor (we could extract some constants in the test).

This is a much better test.

Test still passes!

Round 2

Okay, let’s add another case. What if we check that the User.LastName is copied into the contact when I define the Mapping Lastname => Lastname? Great idea, let’s do it!

I start to write the unit test but…. I realize I can’t do an Insert in a CMT. Or, I give seeAllData permission to the test and define it in the project metadata. Or, I have to somehow deploy it. 

Remember that I said that I don’t do TDD when writing the test is extremely hard? Well, it looks like I’m in one of those situations. At this moment, I can quit writing this blog post and go cry…or I can redefine what I am developing with TDD, leaving all the complexities outside of scope. I imagine you would be very annoyed after reading this far to see me just quit, so let’s go with the second option.

I can’t use the CMT right now, so let’s do something different. What if we use a Map<String, String> where the key is the field in the original object and the value is the list of fields names in the Contact Object. It might work, later on we just need to read the CMT and create a Map with that information, but spoiler alert…that won’t be covered in this article.

But okay, great, let’s create a map and write the deployable failing test.

And as it was expected… it fails.

Let’s write the “minimum” code that makes that test pass

Our new test passes, but the other one failed! Let’s fix that.

Let’s do some refactoring, either in test or production code.

I think the put/get part is messy to read (and has its own meaning), so let’s split it into its own method.

Also, as we want that theMap could be injected into test case scenarios, the @TestVisible annotation is useful here.

Round 3

Now we should add a new test that executes a new flow and see it fail. I think you got the idea, so I won’t do it now, but just to specify the cases, I can think:

  • Mapping a field to multiple fields (separated by colon)
  • Does nothing if origin field is wrong
  • Does nothing if destination field is wrong
  • Does nothing if types are not compatible
    …and so on

Can we do TDD in Lightning web components (or front-end)?

The short answer is yes, we can. 
Long answer: As the Jest test can’t see the objects, but they see only the “generated DOM”, it may be harder to do TDD in an efficient way for front-end solutions. Usually, it is better to test visual code by watching the result and THEN write the tests we need to ensure code won’t break in the future.

Conclusion

TDD is a best practice that’s good to master so that you can decide the best moment to apply it (I don’t believe there is One Ring to rule them all, One Ring to find them, One Ring to bring them all, and in the darkness bind them, thank you J.R.R. Tolkien). Applied correctly it will make you produce better, more robust code…and fewer bugs, which means…

Homer is happy

Oktana is Growing: 200 Developers

  • The first half of 2019 has been a period defined by growth and expansion for Oktana.

200 Developers

We are thrilled to report we’ve officially reached a headcount of over 200 developers, testers and designers worldwide. As our family grows, our available skills grow which is exciting for all of our partners.

Introducing, Paraguay

Our company was founded in Montevideo, Uruguay. Like any technology company, we’re always on the hunt for great talent, encouraging our team to learn new skills to provide additional value to our partners. With that in mind, we expanded into neighboring Paraguay in late 2018, opening an office in the capital, Asunción. Over the past six months, we’ve been able to bring on new team members in Paraguay in a wide variety of roles. The team has become an essential part of the Oktana family.

Why Paraguay? The population is young and entrepreneurial. There has been increased investment by the government in science and technology and several accelerators and other programs have launched to help fuel entrepreneurship. For us, this is the right environment to find developers eager to work on big projects and expand their knowledge.

 

Asunción, Paraguay

Fun Facts about Paraguay

  • Population: 7,000,000+
  • Slightly smaller than the state of California
  • Literacy rate is 94% (vs. 86% in the United States)
  • World’s fourth-largest exporter of electricity
  • Host of Guinness Book of World Records world’s largest barbecue, attended by approximately 30,000 people

Next Stop: Peru

With offices in New York, San Francisco, Montevideo, and now Asunción, where are we headed next? After the successful expansion into Asunción, we looked for other cities to grow into and found Lima. So, we’re excited to announce our office in Lima, Peru is open and ready for business.

Why Peru? The capital, Lima, has a population of over nine million people, making it one of the largest cities in South America. Because the majority of our customers are based in the United States, it’s important for us to ensure our team schedules align with US timezones and work hours to enable collaboration. Like Paraguay, Peru’s workday naturally overlaps with the US workday. Peru is a growing and stable country, so we’re confident it’s a place we will be able to continue to grow.

 

Lima, Peru

Fun Facts about Peru

  • Population: 30,000,000+
  • Nearly twice the size of Texas
  • Founded in 1551, National University of San Marcos is the oldest in the Americas
  • Incan Empire was larger than imperial Rome at its peak
  • Home to both the world’s highest sand dune and deepest canyon

Company Culture

As we continue to expand, it’s important to ensure our Oktana family feels connected regardless of location so we’re increasingly focused on building our company culture and communication between offices. As the year progresses, we may reach out to you, as our partners, to share your story so each developer is able to better understand the projects keeping their colleagues up at night.

MuleSoft & Informatica Certification

With a growing team, we’ve also expanded on our certification game. We believe in continuous learning, so our developers are always training and working on new certifications. We recently stepped outside of core Salesforce certifications to explore other options that fit our team, including MuleSoft and Informatica certifications.

Hope you’ve enjoyed learning more about us. Our team has worked with different organizations and their projects. We are Salesforce platform experts and offer custom development to help you build your platform and solve the right problems. If you want to know more about our work, go check out our latest success stories.

5 Reasons Why We Think You Should Join Us At Dreamforce

Salesforce’s annual conference, Dreamforce, takes off in San Francisco and it gets bigger and better every year. We’re extremely excited to announce that Oktana will be attending again this coming November for the four-day event and we can’t wait to share what we’ve been up to!

While we’re super stoked and eager to plan our Dreamforce 2017 adventure, many of you are probably asking:

“What’s in it for me?” 

What exactly is all of the big hype about around Dreamforce, you ask? It’s just a tech conference, so why is it important for people outside of the tech industry?

Well to start off, Dreamforce isn’t just any kind of annual tech conference. Sure, it’s in San Francisco (aka the hub for any kind of high-tech event or news), but over every other tech event, Dreamforce is the largest software conference in the world. This means that there are more people and more opportunities related to software and innovation here than at any other conference in the world. That, itself, speaks volumes.

In today’s world, almost everything is run by technology. Additionally, the pace of technological revolution is at its record high and sometimes, it can be difficult to keep up with. This conference is here exactly to help bridge that gap. There are over 2000 learning sessions and learning programs at Dreamforce for everyone that teaches attendees what the latest Salesforce products are AND how to utilize them to the furthest potential. This is great for those that have no tech background because, at the end of the day, we all want our businesses to be successful and absorbing all of this knowledge is the best way to make that happen.

With it being the biggest software conference in the world, people from all over the globe are attracted to this event. All types of executives and creatives come to see what’s offered, which also makes Dreamforce the perfect opportunity to network. People aren’t just here to learn about Salesforce and its products, people also come to meet more folks! The number of doors that Dreamforce can open for a person is countless.

With so much intelligence packed into a four-day Salesforce conference, there will be so many ideas sparking from every corner! Whether it’s a new app possibility or a solution to a consistent issue, Dreamforce attendees have the advantage to discuss these thoughts with industry leaders already present at the conference to make these ideas become a reality.

Technology has constantly been changing the way we live, on a global level. In the hospital, the classroom or even laboratory, the creation of innovation has helped humanity reach levels of success like no other. Salesforce supports this ideology and continues to make Dreamforce an event of giving back. There’s plenty of ways to contribute to the community since the conference partners with many organizations such as (RED), Girls Who Code, and Vetforce. Dreamforce wants to help society and give to those that need it and by attending, it’s giving that much more support to an initiative to make our world better.

Bottom line: Dreamforce is THE event to go to for the year and no matter what, there’s always something to be taken away from it. Oktana is honored to be part of this event and we look forward to hopefully seeing you there!

How Our New App, Tok, Can Improve Business Communication

If you work in a large organization or collaborate with multiple teams within your department, then you know how important it is to make sure everyone is on the same page with communication. Not just dialogue, but all methods of effective and most importantly, efficient communication.

As technology has become increasingly innovative, we’re always finding better ways to manage the mutual response. Phone calls can get annoying, it’s hard sometimes to track down the person you want to speak to in person, emails take too much time with finding the person’s email and then adding a title and then writing your message….and then, you have chat.

Chat is the best way to send a quick message and it’s not time-consuming nor complicated. There are tons of chat apps you can use, but our chat app, Tok, is probably one of the best and currently, it’s the only instant messaging client that runs on Salesforce for free!

Oktana’s Tok team created an app that we began using at our company a few months ago.

Not only has the app improved internal communication for us, but it has created a work environment where we’re able to have more time on building quality work, rather than letting miscommunication take over our day.

From our experience of creating it and now using it, here are a few ways Tok can also help your business communication:

Group Messaging Features

With general chat applications such as iMessage, Skype, Facebook Messenger, etc., you can send messages to people quickly. The issue with this is there are too many mediums of chatting and sometimes, it can get difficult backtracking and remembering which method you used to reach colleagues. With Tok, your entire organization is in one place and if you need to reach out to more than one person, you can quickly set up a group message. No more searching for a colleague’s email or Facebook name!

Tok’s Built-In TokBot

To make things more efficient for you, our team has built a new TokBot within the app itself. Just send a message to TokBot and he’ll grab stored messages that you’re looking for, help you make a group chat quickly, and even set up a poll for others to vote on such as where to eat for lunch for the day! When it’s crunch time, TokBot can ease some of the stress and he’s always there to help you 24/7.

Mobile/Desktop/Browser Interface

Picture yourself during your lunch hour eating a salad at the nearby cafe. You have your phone on you just in case your boss calls, but the reality is he decides to message you on your chat app, instead. Unfortunately, you won’t see this message on your until you return from your lunch, and who knows, at that point, he may not even need you anymore. With Tok, we’ve set up a desktop version, a mobile version, and a browser interface! It’s all about keeping you connected, no matter where you are and with so many different ways you can access Tok, you’ll never miss an important deadline or reminder.

Salesforce Shield Protection 

Another concern that came up when using the app was privacy and security for messages. There may be times when you have to give confidential info to a supervisor or a colleague and by texting them the info or sending it through Gchat, the risk of that information getting hacked is SUPER HIGH. With Tok’s browser interface, the app is set up inside Salesforce, so there’s an extra layer of security with Salesforce Shield.

To bring it all together, the value that Tok can bring to your workplace would maximize your time with work and get business taken care of. Time is of the essence so if there’s an option out there that can give you some more of your time back, why not take advantage??

Install Tok here from the AppExchange and also check out the Tok page at this site!

See how your company’s communication gets better! Let us know of any thoughts or ways the app helped you and if you have any suggestions, we’re open to ideas since we’re constantly updating Tok with cooler features!

Tok 30 day trial

Our Take On Salesforce’s New, Einstein Analytics

The Salesforce platform has always been about helping you manage your business in a way that can leverage your growth. Whether it’s from a sales, marketing or even services perspective, understanding the analytics behind what we’re doing currently and how we can make it better is what Salesforce’s new Einstein Analytics is all about!

Thousands of Salesforce users are already noting data for performance to get a better understanding of their organization’s results. What’s great about Einstein Analytics is that it isn’t changing the way we strategize our data, instead it’s adding an extra layer of AI to our analytical productivity by automatically giving CRM insight and recommendations so we can make a better, informed decisions.

Einstein Analytics includes an entire portfolio of analytics-related apps exposing information even further for us, such as Sales Analytics, Service Analytics, and B2B Marketing Analytics.

GM of Salesforce Analytics, Ketan Karkhanis, states:

“With Einstein Analytics, every CRM user can now see not only what happened in their business, but why it happened and what to do about it, without requiring a team of data science experts.”

For Oktana, this new approach to analytics is something we see as extremely noteworthy. The new layer of AI in analytics, we believe, would help users tremendously with learning what exactly customers are looking for and give users the exact feedback needed to move up in the development process.

Einstein Analytics, in our perspective, brings users closer to reaching goals for growth. Rather than making decisions on assumptions, the analytics portfolio will expose raw data to help make decisions based on real numbers. Instead of creating campaigns believed to be great for exposure and branding, Einstein Analytics would assist with focusing on creating campaigns that customers would actually want to see.

It’s important for companies, including us, to ensure that customers are getting a great experience and if there’s an option available to link that to bringing value, such as Einstein Analytics, then we would like to take the opportunity to learn as much as we can to benefit from this!

Oktana’s Recent App Helps Customers Tok Better

Being a services and products company, we’re not just helping our customers, but we’re also building apps to make things easier for our customers. In the past few months, we’ve released an app, Tok, that makes communication efficient and easier in your workspace.

We’ve been using it ourselves and we’re constantly trying to make improvements on it. From sending GIPHYs and emojis to files and pictures, Tok lets you and your colleagues be on the same page with your work.

             

Since our release, we have launched it not only on Salesforce, but also in the App Store. Tok users can communicate through the Tok browser, the Salesforce interface and also on their mobile devices, so a message is never missed. We’ve also included email alerts just in case you’re away from your desk or don’t have the app open, you know when someone is trying to get in contact with you.

Because it’s been a recent launch, we’re here to say it’s not 100 percent perfect….yet! Give the app a try right here or here . Once you’ve downloaded it, try it out and let us know what you think. We’re always open to feedback and comments because in the end, these suggestions are making the app better to help you!

Start tokking!