All posts by Joshua Howard

How To Mock Dependencies In Unit Tests

Writing unit tests for your code base is extremely valuable, especially in the DevOps world we’re living in. Being able to automate and execute those unit tests after each round of changes ensures your code base is, at the very least, functional.



But sometimes we need to be able to write a test for a function that connects to some other service. Maybe it connects to a database or it connects to a 3rd party service. Maybe also, this database or service isn’t currently available from your local work stations or hasn’t completed development yet. Better yet, what if we want to run our unit tests as part of our DevOps build pipeline on server that doesn’t have an open connection to our 3rd party service?

Advertisements

In any of these cases, we need to find a way to write our code, and test our code without having to connect to that extra service. In .NET this can be done with Moq. Let’s start off with what Moq is. Moq is an open source code base on GitHub. It provides functionality to write “fake” implementations of things like databases that we can then test against. We can get a better understanding by looking at some examples.

Say we have a function that looks like this:

void AddDatabaseNumbers()
{
   Database db = new DatabaseHelper();
   Connection conn = db.CreateConnection("172.23.42.134");
   string query = "select number1, number2 from numberTable";
   Table results = db.Execute(query);
   return results.number1 + results.number2;
}

When we run this function it is going to connect to our database, execute a query, and then add the two results together. If we were to write a unit test for this it might look like:

[Fact]
public void TestAddNumbers()
{
   AddDatabaseNumbers();
}

In our development environment this test might pass just fine. It connects to the database and executes the query no problem BUT when we push this code to our repository and kick off the next build, the unit test fails. How come?

Well in this case, our build server doesn’t have a direct line of sight to our database, so it can’t connect and therefore the unit test fails trying to make that connection. This is where Moq can help!

Instead of having the function connect to the database, we can write a “fake” connection that pretends to do what the “db.CreateConnection” does. This way the rest of our code can be tested and we don’t have to worry about always having a database available. We can also use Dependency Injection (more on that in a later post)!

Here’s how we can rework this with a Mock. First let’s refactor our function to pass in the Database object so we can Mock its functions:

void AddDatabaseNumbers(Database db)
{
   Connection conn = db.CreateConnection("172.23.42.134");
   string query = "select number1, number2 from numberTable";
   Table results = db.Execute(query);
   return results.number1 + results.number2;
}

Now let’s look at how our unit test will change to mock the database functionality:

[Fact]
public void TestAddNumbers()
{
   var mock = new Mock<Database>();
   mock.Setup(db => db.CreateConnection()).Returns(Connection);

   var fakeQuery = "blah do nothing";
   mock.Setup(db => db.Execute(fakeQuery)).Returns(Table);

   AddDatabaseNumbers(mock.object);
}

What we’ve done here is that instead of passing a true Database object to our function we’re passing in this mock one. The mock one has had both of it’s functions ‘CreateConnection’ and ‘Execute’ setup so that instead of actually doing anything they just return a ‘Connection’ and ‘Table’ object. We’ve essentially faked all of the functionality that relates to the database so that we can run our unit test for all of the other code.

Advertisements

Now when we push our code changes up to our repository, the unit tests run and pass with flying colors, and since we used Dependency Injection to pass our Database object to the function our unit tests can use the mock object and our actual production code can pass the real Database object. Both instances will work as they should and our code is all the better for it!

I highly encourage you to write unit tests for as much code as you can and to take a look at the Quickstart guide for writing Moq’s to get a better understanding: Moq Quickstart Guide.


How To Gain Mass By Eating Right On Pennies (Part II)

Read Part I Here



In Part I, we covered some of the early stages of getting on the right track to gain mass. Starting small and working towards a bigger goal is always ideal so long as you continue to make progress. After going from skipping most meals to starting to eat breakfast I shifted my focus towards lunch.

Now again, historically, I wasn’t a lunch eater. Really my biggest hang up with lunch was two-fold. Having the time to eat it, and then not letting lunch put me into a food coma by the early afternoon. I wanted to really avoid grains and greasy foods as much as possible since these tended to put me in that food coma.

I started by making my lunches consist of either a small $3 steak or frozen fish. I always went with one or the other and used it as a way to gain some variety in my meals. I also consistently switched up the type of fish I was eating just to keep things from being too boring. In all honesty, the lack of complexity in the meals really did make things easier.

Advertisements

In addition to the main protein I added in some brown rice and cottage cheese. Getting enough fiber in any diet can be extremely difficult so the brown rice was a good supplement for that. The cottage cheese was just an additional boost of protein but ultimately I ended up swapping it out for a can of beans to avoid the dairy intake. Here is my rice of choice:

Minute Instant Brown Rice, 14 oz

Now that I had breakfast and lunch covered I started to iterate over my meal plan. As the weeks went on I adjusted and added in things or took things out. Once I was consistently hitting my breakfast goal I started adding in eggs. Eggs are very cheap and a great source of protein. The only problem was… I learned I had an egg allergy.

This forced me to substitute out the eggs but I didn’t want to lose the protein gain that I was getting from them so I opted to go with some slightly more expensive protein waffles and I smothered them in peanut butter. The ‘Kashi GO’ brand of waffle is pretty good for the price. The real winner here though is peanut butter. Any brand of peanut butter will do and the cheaper the better. I typically just go with a knock off store brand.

Amazon Brand – Happy Belly Creamy Peanut Butter, 16 Ounce

Lunch was the next target to iterate on. Dairy has always been a love-hate relationship type of thing for me and the cottage cheese was starting to get more expensive than I preferred. Again, protein was the name of the game so I wanted to swap it out with something that would keep the protein count high.

Canned beans for the win! You can grab a can of beans at any local grocery store and depending on what brand, they can easily fall under $1. There’s also an enormous amount of options when it comes to beans so you’ll get some extra variety there too. Bush’s tends to be a good one to go with.

Bush’s Best black beans Frijoles Negros – 15 Ounce (12)

At this point I felt like my meals were pretty set, as far as breakfast and lunch. I still ate whatever the rest of the family ate for dinner and because I was slowly building into this meal plan a bit each week I was able to keep it going steadily forward increasing my protein and calorie intake without spending a lot of cash.

I had two more spots that I wanted to add into my meal plan though to really help me top off my protein intake and also get some more variety into my diet like fruits and vegetables. For my morning snack I went with a 12-Grain bread made by Lewis. I couldn’t find this one on Amazon but these types of specialty breads tend to be cheaper than regular bread. You’ll also benefit from the extra fiber of a whole grain bread. PS… smother that bad boy in peanut butter too!

For my afternoon snack I focused on getting my veggie and fruit intake. A protein smoothie is ideal here. You can really get creative when it comes to your smoothies so I would go with whatever you think will work and do some experimentation.

I typically go with some sort of a milk or almond milk along with a Greek yogurt or frozen yogurt. I use store brands for all of these. I’ll then add in frozen spinach or kale and frozen strawberries or pineapple, which ever is cheaper at the store that week, along with a banana. Add in a scoop of peanut butter and some protein powder and you’re set.

Advertisements

This has been my diet for the last 3 months and I expect it to continue to be for a while. Meal planning always failed me in the past and trying to do all that work to create these outlandish meals for the week never worked out. Keeping things as simple as possible and as cheap as possible has been what really worked!

And if you’re thinking it sound boring to eat the same meals day-after-day it really hasn’t been. Instead of trying to figure out what I’m going to eat and then misstepping and eating something that really didn’t give me any energy was a bigger problem than getting bored.

It’s so much easier to just know what you’re going to have and have it, so you can get back to your day. Besides, I still have dinner to throw in some variety and because I ate pretty healthy all day, I don’t feel as guilty to go ham on some tacos at night.

If you’ve found some cheap and healthy alternatives in your diet let me know! I’m always looking for ways to add something new in or swap something out that might be better!


They’re Always Listening, Even When They Aren’t

Sometimes it feels like we tell our kids certain things or give them certain pieces of advice and they just don’t seem to grasp what we’re telling them. This becomes especially true as our kids get older and start to reach the teen years. They become more independent and that mom or dad, “I told you so” becomes more of an annoyance than it does an affirmation.



The interesting thing about watching kids grow is how they wind up doing the things you’ve always told them to do all along. It’s really a surprise twist but our kids actually do listen to us more than we realize. I’m not talking about that one thing you told them to do that one time. I mean the things that you really tried to advise your kids on over-and-over.

Eat your vegetables

Wear your seatbelt

Wash your hands

In these moments, where we are telling our kids to do these things, it always seems like they will never get it. It seems like it goes in one ear and right back out the other. That they’ll never catch on or remember to do the things we tell them. And then you end up feeling like a broken record repeating yourself. However, what actually happens is quite surprising.

Advertisements

As your kids start to get older, they actually start to do those things you’ve repeated to them over the years. It’s almost like they know you’re going to say it anyways, so they try to do it before you can even say it, just so you can’t say it… lol

But maybe it’s also that subconscious part of their mind that is reminding them. That because they’ve heard the advice so much, it sort of sticks with them over-time. And then when that moment comes where you would normally say, “Don’t do that” their subconscious mind just says it for you.

It’s almost like practicing how to do or learn something new. It starts to become a matter of repetition and then before too long the body can just do it automatically.

I think as parents we often feel frustrated that we have to repeat ourselves over-and-over to our kids about things, I know I have, but what we really need to realize is the power that we have in that repetition. If we start to look at that process as practice or training, and not just as us saying something again, we can actually influence our children to a much greater degree than we realize.

By understanding that repeating something, we can help our children actually remember it and actually act in a positive way on it, can be incredibly powerful. And so it becomes very important that we use that power for the things that matter most with our children. Yes we can remind them to pickup their toys or to clean up after themselves but we shouldn’t forget about the things that really matter in life.

Advertisements

We should be reminding our kids, as often as we can, to hold the door for someone, to say thank you, to think of something they’re grateful for, to help a friend out, to say something nice to someone, to work hard on things, to never give up… These are the things we should be repeating to our children every day over-and-over.

As parents, we should remember that picking up the toys is a short-term concept with low value. Yes things look nice, but it doesn’t make anyone else’s life better. It doesn’t make someone whose down, feel good about themselves. It doesn’t help make the world a better place, and as our kids get older, it won’t matter. We should remember to focus on the things that do matter like kindness, hard work, and passion.

So the next time you feel like your kids aren’t listening to you, remember, they are listening, it just takes practice and the question you really need to ask yourself is, are you practicing the right things?


How To Get More Done

Whenever we’re researching things online, and we’re trying to learn something new or trying to gain some insights into a topic, we always hope to come across the perfect article. The one that is the one stop shop, that’s going to have all the answers we need, in one place, and we’re usually willing to jump around, from source-to-source, as we search for it.

When a source does just seem to perfectly nail everything we’re looking to learn, it tends to bring us a lot of value. Value is the keyword here.



Someone spent time to create that source or article, whether employed or as a hobbyist, and it brought a lot of value to you. Things that tend to bring a lot of value, to a lot of people, also tend to be in good company with success.

If we think about how value relates to success, and that by creating value we can create success we can start to rethink how we set our to do list (which really should be an I HAVE To List…). A lot of times we tend to prioritize and keep track of items on our to do list that don’t really bring us great value.

Advertisements

When we’re working towards goals and trying to create success we want to try and identify where the value is in what we’re doing. The tricky part is that value has no one way to be defined. Sometimes things can seem like they should be bringing value, when they don’t. Other times the great value task is right in front of your face and you just can’t seem to grasp it or you’re hesitating to.

If you do find it difficult to identify what your high value tasks are, that will move you towards your goals, you can start by trying things.

That’s the secret right there.

Try more new things.

That’s really how you get more done. You try different things, and then you evaluate how much value they brought, to yourself and hopefully others because then that’s a double win.

You are never going to be able to predict, into the future, what all of the right choices are going to be, and which ones have the most value. The only way to figure out what has value is to start trying things.

That doesn’t mean we should take extreme actions, unless they’re positive ones, but we can still get trapped into doing all the reading and research we want on a topic or goal and still not be able to achieve it. We can think we have the perfect plan and that the problem isn’t with our strategy, but it’s with life… when it’s actually the other way around.

There is so much content available in this day and age for people to learn from. The problem is not all content is equal. We may find information we need or we may read something that isn’t even true. We might read something that just isn’t a good fit for our own life. The only way we can really know, is to try things.

By trying different strategies, different approaches, different techniques, different products, different everything, we get the advantage of collecting data that is exactly specific to our unique situation.

You can’t find that data any where else. No where else can you get data on how things do or don’t work best, for your life, for your career, for your family, than from your own self.

Advertisements

No matter how good at it you may already be, we should always be experimenting and re-evaluating how we’re trying to reach our goals. Life changes, pandemics happen, family changes, friends change, jobs change, and it’s not all bad or negative either. It’s just the fact that life is about change. Life wants to change and change and change. That’s just what it does.

If you want to figure out how to get more done you have to start experimenting with different actions. Take a different approach, adjust the current plan, or start with a completely new one. You may even go back to an older strategy, but be sure to always review how much value you’re getting.

If we try to employ one tactic or one strategy, that we learned somewhere in our lives, and we try to apply that strategy over-and-over, eventually… it’s going to fail. We can have a high value strategy that is very successful, but someday… it will fail. It’s just trying to identify when things has changed enough that the current strategy is no longer effective.

And the way you figure that out is by trying more new things.


THE MANDALORIAN (S2:E7) – THE Believer REVIEW

The Good, the Bad, and the Awesome!



For the first time in a while, no Baby Yoda, but we did get to see a familiar face in Mayfield. What I really wish was we had his over-the-shoulder gun again because let’s be honest, that was pretty bad ass.

The tie fighter graveyard to start the episode was a stark reminder of where the universe is left, in the aftermath of the previous wars and man do I love seeing Boba Fett in these episodes. Hiss armor looks much cleaner now but it would be nice to see him ditch the robe.

Advertisements
photo cred: M8 Head

As for the Mayfield character, I wasn’t really excited to see him. I mean yea, loved the over-the-shoulder firearm but overall, not a big fan of the character. Was happy to see him go by the episodes end.

The trip into the Imperial base wasn’t all that exciting for me but I always enjoy the fan service, such as the use of thermal detonators. It was pretty obvious Mando and Mayfield were going to get some assistance just before reaching the base but I wasn’t expecting it to come from the tie fighters (was expecting the Slave I to swoop in) so it was cool and unexpected twist. It also create an interesting scenario where the bad guys were helping the good guys.

What’s really interesting in this episode is that we are starting to see a new Mando. Mayfield specifically calls him out in this regard referring to how people change their rules when they are in a pinch. Mando taking off his helmet for the first time this season was a significant moment for his character and makes me wonder if we’ll see more of that in season 3.

It was intriguing to watch Mayfield talk with his commanding officer but I felt like it was a little bit of a stretch for him to go AWOL and then for them to escape. I wouldn’t say it was an easy escape but it felt like if you shot a commanding officer in an Imperial base, getting out would be a little more difficult… Well I guess you could blame that storm trooper accuracy.

Advertisements

I want to pause for a second to note the bomb that was deployed by Boba Fett. This was the same style of bomb that Boba’s father, Jango Fett deployed on Obi-wan during the Attack of the Clones. It’s one of my favorite explosives in all of the fantasy content I’ve seen. You just can’t beat the sound effects on that thing!

My biggest disappointment is how short this episode is with the last two episodes coming in at around 30 minutes or so. I would really like to see these episodes push closer to the hour mark and maybe just bring a little more meat into the dialog and character development. It sometimes feels like we’re moving to fast in this regard.

The closing scene showing Mando making his threat to Moff Gideon was great. We usually don’t see Mando try to be such a hard ass. He tends to try and play it neutral so it’s great when he muscles up on someone. I am a little confused on what his attachment is to Gorgu though. I mean, in the Ahsoka episode he was ready to hand him off, now he’s super attached to him?

I’m not sure I’m fully sold on that story line but I’m enjoying each episode despite that. Hoping season two closes out with an absolute banger of an episode and we get some more episode length in season 3.

I still haven’t had my epic space battle yet either damnit!


How To Build A Spawner In Unity

Spawning objects in Unity exists in just about every project out there. Whether we’re spawning enemies for a player to fight or collectables for them to pickup, at some point and time you’re going to need systems that can create and manage these objects. Let’s walk through what this can look like in a Unity 2D project.

There’s no best way to implement a system that creates objects and every project has slightly different needs but there are some commonalities and ways you can create your system to be reusable. For this particular example we’re going to look at spawning for Survive!

Advertisements

There are two main objects that are currently created in Survive using the current spawning system with a handful more on the way. The great part is that implementing each objects spawning logic and system is fairly simple after the first one is in place. Let’s take a look at how that’s done.

Currently we are creating two objects at game start. The white blocks that act as walls and the green enemies the player must avoid. Both of these are built using the same spawning system and code base. We do this so that we can then re-use these objects and scripts to easily add new features to our project. Here is what our spawner code currently looks like:

Advertisements
using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject objectToSpawn;
    public GameObject parent;
    public int numberToSpawn;
    public int limit = 20;
    public float rate;

    float spawnTimer;

    // Start is called before the first frame update
    void Start()
    {
        spawnTimer = rate;
    }

    // Update is called once per frame
    void Update()
    {
        if (parent.transform.childCount < limit)
        {
            spawnTimer -= Time.deltaTime;
            if (spawnTimer <= 0f)
            {
                for (int i = 0; i < numberToSpawn; i++)
                {
                    Instantiate(objectToSpawn, new Vector3(this.transform.position.x + GetModifier(), this.transform.position.y + GetModifier())
                        , Quaternion.identity, parent.transform);
                }
                spawnTimer = rate;
            }
        }
    }

    float GetModifier()
    {
        float modifier = Random.Range(0f, 1f);
        if (Random.Range(0, 2) > 0)
            return -modifier;
        else
            return modifier;
    }
}

And here is what our script looks like from the Editor:

As you can you see, our script allows us to pass in the ‘Object To Spawn’ which is the prefab of the object we want to create. We can then assign it an empty parent object (to help keep track of our objects) and from there we are free to tweak the number of objects it spawns at a time as well as if there should be a limit and how frequently they should be spawned.

Advertisements

With this approach we have a ton of flexibility in how we can control and manipulate object creation. We could attach another script to this object that randomly moves the spawner to different places on the screen (this is how it currently works) or we could create multiple spawners and place them in key locations on the map if we wanted more control over the spawn locations. The point is, we have options.

The best part about this approach is that we can easily include or add another object to use this same functionality with little effort. Here’s the same script, same code, but for creating wall objects:

And a third time for a new feature I’m currently working on:

Advertisements

Each object and system has it’s own concept and design to how it should work, for example the wall objects need to create so many objects quickly (higher rate) and then stop (reach their limit). The zombie objects need to be created over and over as the player destroys them but not as fast (slower rate). The new Heart Collectible needs to be created only once until the player collects it (limit).

When building objects and writing scripts in Unity we should always be thinking of how we can create something that is reusable. It might not be reusable in this particular project, but it can save you mountains of time when you go to the next project and you already have a sub-system like spawning built and ready to go!

If you want to take an even deeper dive, take a look at an article on Object Pooling: Taking Your Objects for a Swim that can help with performance issues you may run into while working with Spawning Systems.

Don’t forget to go checkout Survive and sign up for more Unity tips and updates:

How To Put Bad Things Into Perspective

Ever had a day where things just weren’t working out? Maybe life decided to throw you a little curve ball or you just had a bad day. That tends to happen from time-to-time but there’s one thing you can do to really change that.



Most times when we start to get down about a situation we tend to focus on the situation itself. We start thinking within the context of that situation. We basically zoom in and focus on just that moment.

Think about someone who has had a bad morning and then that bad morning carries on into the rest of the day. While only the morning was bad, that feeling of a bad morning continues on with that person throughout the day.

That’s because this person is still very zoomed in on that morning. Their thoughts and focus are still zoomed in to that exact moment.

Think about when someone has road rage. That moment where they are angry or frustrated with other drivers is an extremely zoomed in moment. When I say zoomed in I mean, they are really only thinking about their current situation. They are thinking about the traffic, their day, and probably why they’re late to where they need to be going.

Advertisements

Another common situation when things aren’t working out and we are very zoomed in is in our goal setting. When we try to set a goal and achieve it but we misstep or we fail some where. Maybe we miss a day going to the gym or we relapse on trying to quit smoking.

Often times when that happens for people the next thing that follows is them giving up on that goal all together and abandoning it. That one bad day, that one slip up, ruined the entire thing for them. They are still very zoomed in and focused on this one mistake.

BUT, there’s a better way you can deal with all of these situations and scenarios and it’s not hard to do. It’s probably more difficult to just remember to do it but it does work.

Whenever we have a situation like this, where we’re feeling like things aren’t working or we’re feeling frustrated, all we have to do is take a second to zoom out.

photo cred: Krissana Porto

We tend to try and think of our lives in only the present. We tend to think that only the current moment and maybe the next few moments or the previous few moments really ever matter. When we take a second to zoom out and think about where this moment in our life really fits, we realize how insignificant this small moment is.

Yes maybe you’re stuck in traffic today, but where does that land in the scope of your life to this day? Do those 20 or 30 minutes really matter in the scope of 20, 30, 40, or even 50 years of your life?

When you start zooming out and thinking more about the overall timeline of your life, it becomes much easier to not be bothered by smaller unfortunate happenings in life. Once you realize that even having a bad hour in the morning really means nothing in the scope of your entire life, you realize your morning really wasn’t that bad.

Advertisements

Missing a goal or making a mistake and then zooming out and realizing that one or two slip ups doesn’t have to define the entire year for you can help you put those mistakes into perspective. Most people aren’t perfect and are going to make mistakes.

Instead of focusing in and being zoomed in on those mistakes, zoom back out and think about your life as a whole. See the bigger picture and understand where that mistake falls when you look at the timeline of your life.

It can be incredibly difficult to remember to zoom out but zooming out is one of the most effective ways to put perspective on any situation. So the next time you’re having a bad day pause and take a second to zoom out. See how much that bad day really matters in the scope of your entire life.